【问题标题】:Drawing bounding rectangles around multiple objects in binary image in python在python中的二进制图像中围绕多个对象绘制边界矩形
【发布时间】:2021-01-03 12:09:48
【问题描述】:

我正在尝试在 python 中编写一些简单的代码来生成二进制图像中对象周围的边界矩形,其中可能有 1 个或多个对象。对于单个对象,使用 cv2.boundingRect 或在 2 个对象周围绘制单个矩形很容易实现这一点,但它似乎无法处理多个单独对象的情况。例如看下图:

我想获得 2 个边界框,分别为每个对象定义 x/y/width/height(或 x1/x2/y1/y2)。有谁知道如何做到这一点?谢谢!

【问题讨论】:

  • 如何定义一个对象?它必须是特定的形状吗?它是否必须在像素之间具有连接性?我能想到的解决方案有很多,但如果只是 blob,你可以使用 blob 检测器:learnopencv.com/blob-detection-using-opencv-python-c
  • 它不必是特定的形状,但它们都将大致为圆形/椭圆形,如上图所示。我认为你是对的,我正在寻找的是 blob。所有单个对象将完全连接。但是由于某种原因,blob 检测器无法处理上面的这张图片。图像由 uint8 0 和 1 的 numpy ndarray 组成,此代码:pixels = cv2.imread(seg, 0)detector = cv2.SimpleBlobDetector_create() keypoints =detector.detect(pixels) 返回一个空的 [] for keypoints

标签: python image opencv python-imaging-library bounding-box


【解决方案1】:

在 Python/OpenCV 中最简单的方法是获取轮廓。然后循环遍历每个轮廓并获取其边界框并将其绘制在图像上并打印出来。

输入:

import cv2
import numpy as np

# read image
img = cv2.imread('two_blobs.jpg')

# convert to grayscale
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

# threshold
thresh = cv2.threshold(gray,128,255,cv2.THRESH_BINARY)[1]

# get contours
result = img.copy()
contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
for cntr in contours:
    x,y,w,h = cv2.boundingRect(cntr)
    cv2.rectangle(result, (x, y), (x+w, y+h), (0, 0, 255), 2)
    print("x,y,w,h:",x,y,w,h)
 
# save resulting image
cv2.imwrite('two_blobs_result.jpg',result)      

# show thresh and result    
cv2.imshow("bounding_box", result)
cv2.waitKey(0)
cv2.destroyAllWindows()

边界框图片:

文本结果:

x,y,w,h: 262 267 37 45
x,y,w,h: 212 143 97 55

【讨论】:

    猜你喜欢
    • 2015-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-10
    • 2021-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多