我正在尝试从几张背景趋于白色的图像中删除相对微不足道的背景。但是,即使不包含太多白色,生成的蒙版也会与前景重叠。例如,给定以下输入:
GrabCut提供了:
下面是我的代码:
img = cv2.imread('test.jpg')
mask = np.zeros(img.shape[:2], np.uint8)
bgdModel = np.zeros((1,65),np.float64)
fgdModel = np.zeros((1,65),np.float64)
height, width, _ = img.shape
rect = (int(width * 0.05), 0, height, int(width * 0.9))
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]
plt.imshow(img),plt.colorbar(),plt.show()
我实际上是在模仿Photoshop的魔术棒,它可以很容易地挑出白色背景。有谁知道使用opencv的好方法吗?有没有办法调整GrabCut来做类似的事情?
更新:在修复了矩形之后,我现在得到了一个留下间隙的遮罩:
发布于 2019-07-10 23:57:45
rect = (int(width * 0.05), 0, height, int(width * 0.9))
仔细看看。你在第一个和第四个位置有一些与宽度成比例的东西。这可能是错误的。the elements are (x,y,w,h)。
此外,您的观察基于matplotlib的假彩色绘图。也许让它画出真实的颜色。
https://stackoverflow.com/questions/56973569
复制相似问题