如何用相邻颜色填充图像上的对象?

问题描述 投票:0回答:2

我在用相邻颜色为粉色框着色时遇到了麻烦,这样图像看起来更真实。我的头像是这样的:

enter image description here

到目前为止,我使用了 CV2 包并实现了这一点:

enter image description here

我的代码:

up = np.array([151,157,255])
pink_mask = cv2.inRange(img, up, up)
cnts, _ = cv2.findContours(pink_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for c in cnts:
    color = tuple(map(int, img[0, 0]))
    cv2.fillPoly(img, pts=[c], color=color)

在这里,我填充了图像上的第一个像素,因为我不确定如何用相邻的颜色填充它。

python opencv image-processing computer-vision inpainting
2个回答
1
投票

我们可以扩大遮罩,并使用cv2.inPaint

import numpy as np
import cv2

img = cv2.imread('input.png')

up = np.array([151,157,255])
pink_mask = cv2.inRange(img, up, up)
#cnts, _ = cv2.findContours(pink_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# for c in cnts:
#     color = tuple(map(int, img[0, 0]))
#     cv2.fillPoly(img, pts=[c], color=color)
pink_mask = cv2.dilate(pink_mask, np.ones((3, 3), np.uint8))  # Dilate the mask

img = cv2.inpaint(img, pink_mask, 5, cv2.INPAINT_TELEA)

cv2.imwrite('output.png', img)

输出:
enter image description here


0
投票

使用 'cv2.boundingRect[c]' 获取当前轮廓的 x、y、w 和 h。 如果要根据检测到的轮廓的左侧填充颜色,请使用 (x - 5, y)。如果你想根据右侧填充颜色,请使用(x + w + 5, y)。

请注意,5 只是使用的偏移量。你可以从1开始。

© www.soinside.com 2019 - 2024. All rights reserved.