使用 GrabCut 去除琐碎的背景
Removing trivial background using GrabCut
我正在尝试从背景趋于白色的几张图像中删除相对琐碎的背景。但是,生成的蒙版会与前景重叠,即使它不包含太多白色。例如,给定以下输入:
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 来做类似的事情?
更新:修复矩形后,我现在得到一个留下空隙的遮罩:
rect = (int(width * 0.05), 0, height, int(width * 0.9))
仔细看。你在第一和第四位置有一些与宽度成正比的东西。那可能是错误的。 the elements are (x,y,w,h).
此外,您的观察基于 matplotlib 的假彩色绘图。也许让它画出本色。
我正在尝试从背景趋于白色的几张图像中删除相对琐碎的背景。但是,生成的蒙版会与前景重叠,即使它不包含太多白色。例如,给定以下输入:
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 来做类似的事情?
更新:修复矩形后,我现在得到一个留下空隙的遮罩:
rect = (int(width * 0.05), 0, height, int(width * 0.9))
仔细看。你在第一和第四位置有一些与宽度成正比的东西。那可能是错误的。 the elements are (x,y,w,h).
此外,您的观察基于 matplotlib 的假彩色绘图。也许让它画出本色。