【问题标题】:OpenCV grabcut() background color and Contour in PythonPython中的OpenCV grabcut()背景颜色和轮廓
【发布时间】:2016-10-29 03:42:03
【问题描述】:

我正在使用 Python 和 OpenCV。我现在使用grabcut() 裁剪出我想要的对象。这是我的代码:

img = cv2.imread('test.jpg')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
mask = np.zeros(img.shape[:2], np.uint8)

bgdModel = np.zeros((1, 65), np.float64)
fgdModel = np.zeros((1, 65), np.float64)

rect = (2,2,630,930)
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]

然后,我试着找出轮廓。

我尝试通过下面的代码找到轮廓:

imgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,127,255,0)
im2, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

它返回a contours array,长度为48。当我把它画出来时:

第一个问题是如何获得这个抓刀的轮廓(数组)?

第二个问题:如您所见,背景颜色为黑色。 如何将背景颜色更改为白色?

谢谢。

【问题讨论】:

  • 我应该将contours 连接到一个合并列表中是否正确?

标签: python image opencv image-processing


【解决方案1】:

首先,您需要获取背景。必须从带有掩码图像的原始图像中减去这一点。然后将黑色背景更改为白色(或任何颜色)。然后回来加上面具的图片。

import numpy as np
import cv2

cv2.namedWindow(‘image’, cv2.WINDOW_NORMAL)

#Load the Image
imgo = cv2.imread(‘input.jpg’)
height, width = imgo.shape[:2]

#Create a mask holder
mask = np.zeros(imgo.shape[:2],np.uint8)

#Grab Cut the object
bgdModel = np.zeros((1,65),np.float64)
fgdModel = np.zeros((1,65),np.float64)

#Hard Coding the Rect… The object must lie within this rect.
rect = (10,10,width-30,height-30)
cv2.grabCut(imgo,mask,rect,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_RECT)
mask = np.where((mask==2)|(mask==0),0,1).astype(‘uint8’)
img1 = imgo*mask[:,:,np.newaxis]

#Get the background
background = imgo – img1

#Change all pixels in the background that are not black to white
background[np.where((background > [0,0,0]).all(axis = 2))] =[255,255,255]

#Add the background and the image
final = background + img1

#To be done – Smoothening the edges….

cv2.imshow(‘image’, final )

k = cv2.waitKey(0)

if k==27:
cv2.destroyAllWindows()

从网站获取的信息 https://nxtify.wordpress.com/2015/02/24/image-background-removal-using-opencv-in-python/

【讨论】:

    【解决方案2】:

    如果你想要一个类似边界的单一轮廓,你可以在grabcut的输出上进行边缘检测,并对边缘图像进行形态膨胀,得到一个合适的连接轮廓,并可以得到边界的像素数组。

    为了使背景变白,边界框外的所有像素都可以默认为白色。你的bounding box里面的黑色像素,你可以和原图对应的灰度进行比较,如果是黑色的可以保留,否则就变成白色。因为如果原始像素不是黑色的,而是被抓取变成黑色的,那么它就被认为是背景。如果前景中有黑色像素,则抓取永远不会使其变为黑色(理想情况)。

    【讨论】:

    • 首先,轮廓数组包含37个不同的轮廓。我怎样才能得到“正确的”一个。其次,如果我只是简单地将黑色像素替换为 255,它不仅会转换背景,还会转换图像上下文。
    猜你喜欢
    • 1970-01-01
    • 2019-02-09
    • 1970-01-01
    • 2022-01-09
    • 2021-10-18
    • 1970-01-01
    • 1970-01-01
    • 2021-01-03
    • 1970-01-01
    相关资源
    最近更新 更多