图像中 blob 的边界框

问题描述

我有一个黑色背景的灰度图像,上面有一些非黑色物体,如下所示:

enter image description here

现在我想找到每个对象的最小(矩形)边界框。如果有帮助,我可以在每个对象中提供一个起点。

由于没有花哨的阈值或任何东西,我想避免像 Canny 这样的东西来找到构造。如果像素不为 0,则它在 blob 中。

解决方法

为了在图像中任何不是完全黑色的区域周围绘制矩形,您可以执行以下操作:

imagefile = '/path/to/your/image'
img = cv2.imread(imagefile)

# Convert you image to grayscale
gray = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)

# Threshold the image to extract only objects that are not black
# You need to use a one channel image,that's why the slice to get the first layer
tv,thresh = cv2.threshold(gray[:,:,0],1,255,cv2.THRESH_BINARY)

# Get the contours from your thresholded image
contours = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[0]

# Create a copy of the original image to display the output rectangles
output = img.copy()

# Loop through your contours calculating the bounding rectangles and plotting them
for c in contours:
    x,y,w,h = cv2.boundingRect(c)
    cv2.rectangle(output,(x,y),(x+w,y+h),(0,255),2)
# Display the output image
plt.imshow(cv2.cvtColor(output,cv2.COLOR_BGR2RGB))

output image with rectangles around non-zero objects

,

不管你使用什么,你仍然需要遍历所有像素。虽然 Bitmap.GetPixel(x,y) 主要使用但它很慢。但是如果你在内存中锁定位并循环遍历字节数组,它会快数百倍。

请查看此 document 以将图像的位锁定在内存中。