Python中OpenCV的grabcut()背景颜色和轮廓

2024-01-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)

And it returns a contours array with length 48. When I draw this out: enter image description here

第一个问题是如何获得此抓取切割的轮廓(数组)?

enter image description here Second question: as you can see, the background color is black. How can I change the background color to white?

谢谢。


首先,您需要了解背景。为此必须用掩模图像从原始图像中减去。然后将黑色背景更改为白色(或任何颜色)。然后返回添加蒙版图像。

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/ https://nxtify.wordpress.com/2015/02/24/image-background-removal-using-opencv-in-python/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python中OpenCV的grabcut()背景颜色和轮廓 的相关文章

随机推荐