how to aproximate shapes height and width for image detection using opencv and python

2024/10/5 15:41:35

i was following a tutorial about shapes detection using opencv ,numpy and python ,and it was this function i know the reason from it but i do not know how to modify it so i can use it as i want the total bubble's number are 320 but the function detect 303 only i tried to modify this line but the max i get is 303 (len(approx) > 8 and w / h <= 1.1 and w / h >= 0.8) i want someone to explain to me this function please

this is the code

    def getOvalContours(self, adaptiveFrame):contours, hierarchy = cv2.findContours(adaptiveFrame, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)ovalContours = []for contour in contours:approx = cv2.approxPolyDP(contour, 0, True)ret = 0x, y, w, h = cv2.boundingRect(contour)# eliminating not ovals by approx lenghtif (len(approx) > 8 and w / h <= 1.1 and w / h >= 0.8):mask = np.zeros(adaptiveFrame.shape, dtype="uint8")cv2.drawContours(mask, [contour], -1, 255, -1)ret = cv2.matchShapes(mask, contour, 1, 0.0)if (ret < 1):ovalContours.append(contour)self.bubbleWidthAvr += wself.bubbleHeightAvr += hself.bubbleWidthAvr = self.bubbleWidthAvr / len(ovalContours)self.bubbleHeightAvr = self.bubbleHeightAvr / len(ovalContours)return ovalContours

this is the image enter image description here

Answer

Here is one way to do that using Hough Circles in Python/OpenCV.

Input

enter image description here

import cv2
import numpy as np# Read image
img = cv2.imread('multichoice_test.jpg')
hh, ww = img.shape[:2]# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)# get Hough circles
min_dist = 30
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, minDist=min_dist, param1=150, param2=20, minRadius=10, maxRadius=15)
print("circles:", circles)
print("")# draw circles
img_circle = img.copy()
count = 0
for circle in circles[0]:# draw the circle in the output image, then draw a rectangle# corresponding to the center of the circle(x,y,r) = circlex = int(x)y = int(y)r = int(r)cv2.circle(img_circle, (x, y), r, (0, 0, 255), 1)count = count + 1# print number of circles
print("number of circles:", count)# save results
cv2.imwrite('multichoice_test_circles.jpg', img_circle)# show images
cv2.imshow('circles', img_circle)
cv2.waitKey(0)
cv2.destroyAllWindows()

Result:

enter image description here

number of circles: 320
https://en.xdnf.cn/q/119957.html

Related Q&A

Using str.replace in a for loop

I am working on an assignment that is asking me to change the below code so that line 4 uses str.isalnum and lines 5-7 become uses only one line using str.replace.s = p55w-r@d result = for c in s:if(c…

extract all vertical slices from numpy array

I want to extract a complete slice from a 3D numpy array using ndeumerate or something similar. arr = np.random.rand(4, 3, 3)I want to extract all possible arr[:, x, y] where x, y range from 0 to 2

Output an OrderedDict to CSV

I read a CSV file and use the usaddress library to parse an address field. How do I write the resulting OrderedDicts to another CSV file?import usaddress import csvwith open(output.csv) as csvfile:re…

min() arg is an empty sequence

I created a function that consumes a list of values and produces the average. However it only works when I use integer values. I get the following error when I make the values into floats:min() arg is …

Removing last words in each row in pandas dataframe

A dataframe contains a column named full_name and the rows look like this: full_name Peter Eli Smith Vanessa Mary Ellen Raul Gonzales Kristine S Lee How do I remove the last words and add an additi…

Object of type function has no len() in python

I have been searching for a solution for this error for a while but the solutions that have helped others have not been much help for me.Here is the code that Ive wrote.def main():while True:userInput(…

My If condition within a while loop doesnt break the loop

Struggling to get my code for the final room to finish the text-based game assigned to me. I essentially want the player to be forced to get all 6 items prior to entry. Any help is greatly appreciated.…

Adding strings, first, first + second, etc

Program has to be able adding strings from the list and output them in sequence but in the way: 1 string 1 + 2 string 1 + 2 + 3 string ...def spacey(array):passe = ""i = ""m = []for…

Store Variables in Lists python

So I have tried to do this, and I think its clear what I want, I want to store the message variables that I have made in a List and then use this for printing, I wonder why does this not work?items = …

How can I kill the explorer.exe process?

Im writing a script which is meant to kill explorer.exe. I searched a bit about it and the best answer Ive seen uses the taskkill command. I tried it, but when I run it on my computer it says it worked…