python - 在Python中以二进制图像在多个对象周围绘制边界矩形

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

我正在尝试在python中编写一些简单的代码以在二进制图像中的对象周围生成边界矩形,其中可能有1个或多个对象。使用cv2.boundingRect为单个对象或在2个对象周围绘制单个矩形相当容易实现,但是似乎无法处理多个单独的对象。例如,请参见下图:
enter image description here
我想得到2个边界框,分别为每个对象定义x / y / width / height(或x1 / x2 / y1 / y2)。有谁知道如何做到这一点?谢谢!

最佳答案

在Python / OpenCV中执行此操作的最简单方法是获取轮廓。然后在每个轮廓上循环并获得其边界框,并将其绘制在图像上并打印。
输入:
enter image description here

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()

边界框图片:
enter image description here
性结果:
x,y,w,h: 262 267 37 45
x,y,w,h: 212 143 97 55

关于python - 在Python中以二进制图像在多个对象周围绘制边界矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63923800/

相关文章:

python - 如何解决这个 "pip install pypcap"错误(在 Windows 和 Ubuntu Linux 中)

python - 在另一个类中调用一个类的方法

javascript - 我可以使 src 属性从服务器或调整服务器获取 base64 数据吗?

Python Opencv 在大图像的轮廓上叠加图像

c++ - openCV 'cvPoint' 和 'CV_FONT_HERSHEY_SIMPLEX' 未在此范围内声明

opencv - 问题理解 OpenCV Convert Mat to BufferedImage

python - urlopen 在第二次调用中非常慢

python - 使用 MariaDB 10.2 安装 mysqlclient 时出错

c++ - OpenCV皮肤检测色彩空间?

java - 如何将图片添加到 JTabbedPane - 在空面板布局上?