OpenCV-Grabcut-python中同时使用rect和mask

2024-10-02 00:44:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Windows的Python中使用opencv3alpha。我有一个背景减法,它可以使用grabcut进行图像分割。所以我有MOG探测器,它能给我一些关于前景和背景的信息。例如,这是当前图像(rect只是为了可视化而给出的)。在

Input image

这是MOG探测器的输出。在

enter image description here

我想把这个信息输入cv2.grabcut。我希望我不需要分割整个图像,而且它会更快(?)指定已知对象周围的区域并传递可能的前景和背景。水滴存储为shapely多边形,其边界为xmin、ymin、xmax、ymax

#expand the bounding box of the polygons about 5 times
b=blob.buffer(50).bounds

#change to integer
rect=[int(x) for x in b]

#Shapely give coordinates in xmin,ymin,xmax,ymax

#Format into x,y,w,h required by grabcut in opencv
rectf=tuple([rect[0],rect[1],rect[2]-rect[0],rect[3]-rect[1]])                                                 

#create a mask
mask = np.zeros(grabCUTimage.shape[:2],np.uint8)

#Make anywhere black in the grey_image (output from MOG) as likely background
#Make anywhere white in the grey_image (output from MOG) as definite foreground
mask[grey_image == 0] = 2
mask[grey_image == 255] = 1    

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

#Run grabcut
cv2.grabCut(grabCUTimage,mask,rectf,bgdModel,fgdModel,4,cv2.GC_INIT_WITH_RECT)

#Multiple new mask by original image to get cut            
mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8')
cGB =grabCUTimage*mask2[:,:,np.newaxis]

这总是给我一个黑色的形象。所有背景。在

当我用cv2.GC_INIT_with_MASK初始化时,它工作正常(请忽略红色方块)。然而,它肯定会忽略rect,因为有时它包含了rect边界之外的估计前景(在本例中没有显示)。在

enter image description here

我存错了吗?不是x,y,w,h吗?指定一个rect实际上会使它更快还是应该裁剪图像?在


Tags: theinrect图像imagenpzerosmask
2条回答

我可以看出这是一个老问题,但我已经做了几天,似乎有一个错误的矩形定义。我把我的参数定义为(x,y,hw),它对我来说效果很好。在

希望有帮助。在

我不确定我是否理解正确,但是当你在Grabcut中使用“GC_Init_with_Rect”时,最好初始化整个掩码并将其设置为“可能的背景”:

mask = Mat::ones(image.size(), CV_8UC1) * GC_PR_BGD; //GC_PR_BGD
它的C++,但我想你明白了。在

更新1: 我不认为这是更快的,但当你使用你的MOG信息在你的投资回报率周围画一个更大的矩形,你可以把矩形的外部设置为GC BGD。这应该更快。在

相关问题 更多 >

    热门问题