如何填充裁剪图像的背景
How to fill the background of a cropped image
目前我有一张在 OpenCV 中用给定的 x,y 坐标裁剪的图像。我正在尝试检测所述图像上的白色像素并显示它们。该代码工作正常,但在我用来制作屏幕截图的示例视频的某些帧上,裁剪背景也包含带有白色的元素。
我有以下代码:
import cv2
img = cv2.imread('Image_crop.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,gray = cv2.threshold(gray, 150,255,0)
gray2 = gray.copy()
cv2.imshow('IMG',gray2)
cv2.waitKey(0)
cv2.destroyAllWindows()
作物产量:
白色像素输出:
想要的输出:
有没有办法填充裁剪图像的背景或获得想要的输出?
嗯,这并不像看起来那么容易。简单的解决方案可能是使用 cv2.grabCut
(Sample 教程),但它不会为您带来完美的结果。
不要先裁剪图像,而是将边界给 cv2.grabCut
,屏蔽背景,然后再裁剪图像。
img = cv2.imread('image.jpg')
mask = np.zeros(img.shape[:2], np.uint8)
bgdModel = np.zeros((1, 65), np.float64)
fgdModel = np.zeros((1, 65), np.float64)
rect = (x, y, width, height) # boundary of interest
cv2.grabCut(img, mask, rect, bgdModel, fgdModel, 5, cv2.GC_INIT_WITH_RECT)
mask2 = np.where((mask == 2) | (mask == 0), 0, 1).astype('uint8')
img = img * mask2[:, :, np.newaxis]
# crop the image and ...
如果输入是视频,您可以使用对象跟踪算法提高性能。
目前我有一张在 OpenCV 中用给定的 x,y 坐标裁剪的图像。我正在尝试检测所述图像上的白色像素并显示它们。该代码工作正常,但在我用来制作屏幕截图的示例视频的某些帧上,裁剪背景也包含带有白色的元素。
我有以下代码:
import cv2
img = cv2.imread('Image_crop.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,gray = cv2.threshold(gray, 150,255,0)
gray2 = gray.copy()
cv2.imshow('IMG',gray2)
cv2.waitKey(0)
cv2.destroyAllWindows()
作物产量:
白色像素输出:
想要的输出:
有没有办法填充裁剪图像的背景或获得想要的输出?
嗯,这并不像看起来那么容易。简单的解决方案可能是使用 cv2.grabCut
(Sample 教程),但它不会为您带来完美的结果。
不要先裁剪图像,而是将边界给 cv2.grabCut
,屏蔽背景,然后再裁剪图像。
img = cv2.imread('image.jpg')
mask = np.zeros(img.shape[:2], np.uint8)
bgdModel = np.zeros((1, 65), np.float64)
fgdModel = np.zeros((1, 65), np.float64)
rect = (x, y, width, height) # boundary of interest
cv2.grabCut(img, mask, rect, bgdModel, fgdModel, 5, cv2.GC_INIT_WITH_RECT)
mask2 = np.where((mask == 2) | (mask == 0), 0, 1).astype('uint8')
img = img * mask2[:, :, np.newaxis]
# crop the image and ...
如果输入是视频,您可以使用对象跟踪算法提高性能。