在python中围绕二进制图像中的多个对象绘制边界矩形 [英] Drawing bounding rectangles around multiple objects in binary image in python

查看:72
本文介绍了在python中围绕二进制图像中的多个对象绘制边界矩形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to write some easy code in python to produce bounding rectangles around objects in a binary image, where there may be 1 or more objects. This is fairly easy to achieve with cv2.boundingRect for a single object, or to draw a single rectangle around 2 objects, but it does not seem to handle the multiple separate objects case. For example see the image below:

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

I would like to get 2 bounding boxes that define the x/y/width/height (or alternatively x1/x2/y1/y2) for EACH object separately. Does anyone know how to do this? Thanks!

推荐答案

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

The simplest way to do that in Python/OpenCV is to get the contours. Then loop over each contour and get its bounding box and draw it on the image and print it.

输入:

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

这篇关于在python中围绕二进制图像中的多个对象绘制边界矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆