OpenCV grabcut()背景颜色和Python中的轮廓 [英] OpenCV grabcut() background color and Contour in Python

查看:1155
本文介绍了OpenCV grabcut()背景颜色和Python中的轮廓的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using Python and OpenCV. I am now using grabcut() to crop out the object I want. Here is my code:

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]


之后,我试图找出轮廓。

Afterwards, I try to find out the contour.

我试图通过以下代码找到轮廓:

I have tried to find the contour by the code below:

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)

它返回一个轮廓数组长度 48 。当我画出来的时候:

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

第一个问题是如何获得轮廓(这个抓斗的数量?


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

谢谢。

推荐答案

首先,您需要获得背景信息。必须使用蒙版图像从原始图像中减去此值。然后将黑色背景更改为白色(或任何颜色)。然后回来添加掩码的图像。

At first, you need to get the background. To this must be subtracted from the original image with the mask image. And then change the black background to white (or any color). And then back to add with the image of the mask.

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 /

这篇关于OpenCV grabcut()背景颜色和Python中的轮廓的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆