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 = 0
x, y, w, h = cv2.boundingRect(contour)
# eliminating not ovals by approx lenght
if (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 = w
self.bubbleHeightAvr = h
self.bubbleWidthAvr = self.bubbleWidthAvr / len(ovalContours)
self.bubbleHeightAvr = self.bubbleHeightAvr / len(ovalContours)
return ovalContours
CodePudding user response:
This snippet tries to detect small circles by using the heuristic rule. You can tune the value a bit to get the number you want. And you should look in the other methods for circle detection as well (for example
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) = circle
x = 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:
number of circles: 320