Skip to content

Instantly share code, notes, and snippets.

@alucarded
Created January 22, 2016 20:22
Show Gist options
  • Save alucarded/a2944983dd764e5c80d3 to your computer and use it in GitHub Desktop.
Save alucarded/a2944983dd764e5c80d3 to your computer and use it in GitHub Desktop.
import cv2
import cv2.cv as cv
import numpy as np
import cmath
img = cv2.imread('nano.bmp', cv2.CV_LOAD_IMAGE_GRAYSCALE)
# Find particles
img = cv2.medianBlur(img, 3)
circles = cv2.HoughCircles(img, cv.CV_HOUGH_GRADIENT, 4, 10, param1=255, param2=20, minRadius=1, maxRadius=10)
# Round positions to integers
circles = np.uint16(np.around(circles))
# Draw circles
cimg = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
for i in circles[0, :]:
cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2)
# Find clusters
CLUSTER_DELTA = 25
clusters = []
count = []
added = 0
# Iterate through all circles
for i in circles[0, :]:
added = 0
k = 0
# Check distance between a circle and cluster for every cluster, until:
# a) all clusters are checked
# b) some cluster is nearer than CLUSTER_DELTA
for j in clusters[:]:
print j
x = j[0] - i[0]
y = j[1] - i[1]
d = cmath.sqrt(x*x + y*y).real
if d < CLUSTER_DELTA:
# 3. If some cluster is near enough, then:
# a) we add circle to it
# b) increase count (2D array in code) for it
# c) we compute the cluster radius
# d) we terminate looping through clusters
j[0] = (j[0] + i[0])/2
j[1] = (j[1] + i[1])/2
j[2] = max(j[2] + i[2], d/2 + i[2]);
count[k] += 1
added = 1
break
k += 1
if not added:
# 4. If, after terminating looping through clusters,
# no near cluster where discovered,
# then this circle is a new cluster
clusters.append(i)
count.append(1)
# Draw clusters
k = 0
for i in clusters[:]:
if count[k] > 1:
cv2.circle(cimg,(i[0],i[1]),i[2],(255,0,0),2)
k += 1
cv2.imshow('img', img)
cv2.imshow('cimg', cimg)
cv2.waitKey(0)
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment