Skip to content

Instantly share code, notes, and snippets.

@Laurence-Cullen
Created April 8, 2017 22:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Laurence-Cullen/d97dd1e73911cd28c31f03119b6a0a5f to your computer and use it in GitHub Desktop.
Save Laurence-Cullen/d97dd1e73911cd28c31f03119b6a0a5f to your computer and use it in GitHub Desktop.
Open CV example for finding the number of circles in an image
# Tuned to find the number of balls/circles in this image https://i.redd.it/z092hx3k89qy.jpg
import cv2
import cv2.cv as cv
import numpy as np
img = cv2.imread('circles.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
circles = cv2.HoughCircles(gray, cv2.cv.CV_HOUGH_GRADIENT, 1, 3,
param1=170, #this controls the edge detection thresholds - 170-200 produces reasonable results all in that 20k-30k range
param2=10,
minRadius=2,
maxRadius=30)
print len(circles[0,:]) #this is the answer we care about
circles = np.uint16(np.around(circles))
for i in circles[0,:]:
cv2.circle(img,(i[0],i[1]),2,(0,0,255),3)
cv2.imshow('detected circles',img) #show the image with all found circles highlighted as a sanity check
cv2.waitKey(0)
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment