Drawing bounding rectangles around multiple objects in binary image in python

2024/9/26 0:32:14

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: enter image description here

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!

Answer

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.

Input:

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

Bounding boxes image:

enter image description here

Texual results:

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

https://en.xdnf.cn/q/71519.html

Related Q&A

Replicating YEARFRAC() function from Excel in Python

So I am using python in order to automate some repetitive tasks I must do in excel. One of the calculations I need to do requires the use of yearfrac(). Has this been replicated in python?I found this…

creating a pandas dataframe from a database query that uses bind variables

Im working with an Oracle database. I can do this much:import pandas as pdimport pandas.io.sql as psqlimport cx_Oracle as odbconn = odb.connect(_user +/+ _pass +@+ _dbenv)sqlStr = "SELECT * FROM c…

Is there a docstring autocompletion tool for jupyter notebook?

I am looking for a tool/extension that helps you writing python docstrings in jupyter notebook. I normally use VS code where you have the autodocstring extension that automatically generates templates …

Long to wide data. Pandas

Im trying to take my dataframe from a long format in which I have a column with a categorical variable, into a wide format in which each category has its own price column. Currently, my data looks like…

How to wrap text in Django admin(set column width)

I have a model Itemclass Item(models.Model):id = models.IntegerField(primary_key=True)title = models.CharField(max_length=140, blank=True)description = models.TextField(blank=True)price = models.Decima…

Problems compiling mod_wsgi in virtualenv

Im trying to compile mod_wsgi (version 3.3), Python 2.6, on a CentOS server - but under virtualenv, with no success. Im getting the error:/usr/bin/ld:/home/python26/lib/libpython2.6.a(node.o):relocatio…

Python - Multiprocessing Error cannot start a process twice

I try to develop an algorithm using multiprocessing package in Python, i learn some tutorial from internet and try to develop an algorithm with this package. After looking around and try my hello world…

Printing unicode number of chars in a string (Python)

This should be simple, but I cant crack it. I have a string of Arabic symbols between u\u0600 - u\u06FF and u\uFB50 - u\uFEFF. For example غينيا واستمر العصبة ضرب قد. How do I pri…

Pandas report top-n in group and pivot

I am trying to summarise a dataframe by grouping along a single dimension d1 and reporting summary statistics for each element of d1. In particular I am interested in the top n (index and values) for …

virtualenv --no-site-packages is not working for me

virtualenv --no-site-packages v1cd v1\Scriptsactivate.batpython -c "import django" # - no problem hereWhy does it see the Django package??? It should give me an import error, right?