Closed. This question does not meet
size of each ball is 1cm, so i should detect them, calculate it's size in pixels and find scale. Then i will calculate distance between each two balls. We can't use manual marking, because of large number of photos. So I want to write python script that does it automatically. Сan you advice me on python libraries or frameworks that can solve my problem. Maybe there are some ready-made solutions for detection geometric figures on contrast background.
CodePudding user response:
The Python package opencv-python
is a great fit for this task.
Image segmentation based on color should work fine, you can couple it with edge detection as the balls are edges are well defined.
There are a lot of Stack Overflow questions about segmentation of things that could inspire you:
import cv2
import numpy as np
img = cv2.imread('beads.jpg')
hue = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)[:,:,0]
thresh = cv2.threshold(hue, 165, 255, cv2.THRESH_BINARY)[1]
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))
morph = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (6,6))
morph = cv2.morphologyEx(morph, cv2.MORPH_CLOSE, kernel)
contours = cv2.findContours(morph, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
circles = img.copy()
num_circles = len(contours)
ave = 0
for cntr in contours:
center, radius = cv2.minEnclosingCircle(cntr)
cx = int(round(center[0]))
cy = int(round(center[1]))
rr = int(round(radius))
cv2.circle(circles, (cx,cy), rr, (0, 255, 0), 2)
ave = ave radius
ave_radius = ave / num_circles
print("average radius:", ave_radius)
print ("number of circles:", num_circles)
cv2.imwrite('beads_thresh.jpg', thresh)
cv2.imwrite('beads_morph.jpg', morph)
cv2.imwrite('beads_circles.jpg', circles)
cv2.imshow('thresh', thresh)
cv2.imshow('morph', morph)
cv2.imshow('circles', circles)
cv2.waitKey(0)
cv2.destroyAllWindows()
Thresholded Image:
Morphology Cleaned Image:
Circles on Input:
Average Radius and Count:
average radius: 13.95605175635394
number of circles: 34