【发布时间】:2020-12-11 01:29:35
【问题描述】:
我正在尝试使用 OpenCV 从图像中移除黑色背景,但我无法移除像素以仅捕获没有黑色背景的主图像。这是我正在使用的代码以及原始输入图像。
import numpy as np
import cv2
from matplotlib import pyplot as plt
img = cv2.imread('C:\\Users\\mdl518\\Desktop\\input.png')
mask = np.zeros(img.shape[:2],np.uint8)
bgdModel = np.zeros((1,65),np.float64)
fgdModel = np.zeros((1,65),np.float64)
rect = (0,0,1035,932) # image width/height re-formatted as (x,y,width,height)
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.savefig('C:\\Users\\mdl518\\Desktop\\output.png')
我实际上是在重新格式化此处概述的代码 (https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_grabcut/py_grabcut.html),该代码说明了使用 OpenCV 进行前沿提取。但是,我仍然无法从输入图像中裁剪周围的背景像素,同时在输出图像中保留图像本身的完整性。有没有更简单的方法来解决这个问题?我还尝试使用 cv2.thresholding 和轮廓来裁剪/删除背景,但仍然无法弄清楚。非常感谢任何帮助!
【问题讨论】:
-
您是要裁剪图像还是使黑色背景透明?如果裁剪为矩形,您将切断大量数据,因此不会保留您的图像。请澄清你想要什么。使背景透明,应该没有那么难。阈值,用形态学清理,获取外部轮廓并将其绘制为黑色背景上的填充白色。然后将其放入图像的 alpha 通道中。
-
fmw42 - 我正在尝试完全裁剪/删除黑色背景,而不创建矩形以丢失原始图像中的数据。我希望能够在基本的照片浏览器中打开图像并且看不到黑色背景,因此目标是清晰/不存在的背景。再次感谢你的帮助! :)
标签: python image opencv pixel threshold