python中单色图像中对象周围的矩形边界框?

时间:2017-02-23 16:37:27

标签: python opencv scikit-image

我有一组两个单色图像[附加],我想为每个图像中的人物放置矩形边界框。我知道cv2.dilate可能有所帮助,但我看到的大多数例子都集中在检测一个包含最大像素强度的矩形,所以基本上他们在图像中放了一个大矩形。我想有两个单独的矩形。

image1

image2

更新 这是我的尝试:

import numpy as np
import cv2

im = cv2.imread('splinet.png',0)
print im.shape
kernel = np.ones((50,50),np.uint8)
dilate = cv2.dilate(im,kernel,iterations = 10)
ret,thresh = cv2.threshold(im,127,255,0)
im3,contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
plt.imshow(im,cmap='Greys_r')
#plt.imshow(im3,cmap='Greys_r')

for i in range(0, len(contours)):
    if (i % 2 == 0):
       cnt = contours[i]
       #mask = np.zeros(im2.shape,np.uint8)
       #cv2.drawContours(mask,[cnt],0,255,-1)
       x,y,w,h = cv2.boundingRect(cnt)
       cv2.rectangle(im,(x,y),(x+w,y+h),(255,255,0),5)
       plt.imshow(im,cmap='Greys_r')
       cv2.imwrite(str(i)+'.png', im)

cv2.destroyAllWindows()

输出如下:如你所见,正在制作小盒子,它也不是很清晰。

output

1 个答案:

答案 0 :(得分:0)

您问题中的真正问题在于单色图像中 选择最佳阈值

为此,请计算灰度图像的中位数(帖子中的第二张图像)。 阈值级别将设置为高于此中值的 33%阈值以下的任何值都将被二值化。

这就是我得到的:

enter image description here

现在执行形态膨胀,然后进行轮廓操作,您可以使用矩形突出显示您感兴趣的区域。

<强> 注意:

永远不要像您那样设置手动阈值。阈值可能因不同图像而异。因此,请始终根据图片的中位数选择阈值。