c# - 图像中 Blob 的边界框

标签 c# opencv bounding-box

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

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, 0, 255), 2)
# Display the output image
plt.imshow(cv2.cvtColor(output, cv2.COLOR_BGR2RGB))

output image with rectangles around non-zero objects

关于c# - 图像中 Blob 的边界框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65395239/

相关文章:

javascript - 带键盘输入的全屏 Silverlight

c# - 异步 EntityFramework 操作

c# - 如何使用c#审查字符串中的前10个字符

c# - 如何同时使用字符串插值和逐字字符串来创建 JSON 字符串文字?

c++ - OpenGL 中的像素操作

android - 尽管已正确保存,但文件没有出现在 SD 卡上;出现在设备上的文件资源管理器中

python - 等效于 Python OpenCv 的 MATLAB imshow(I,[ ]);

Tensorflow 对象检测 API 数据增强边界框

python - 聚类边界框并在其上画线(OpenCV、Python)

algorithm - BVH 的线性化和 SAH 的桶数是什么意思?