soares7vinicius

Untitled

May 12th, 2020
715
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.80 KB | None | 0 0
  1. import cv2
  2. import numpy as np
  3.  
  4.  
  5. def points_in_circle_np(radius, x0=0, y0=0, ):
  6.     x_ = np.arange(x0 - radius - 1, x0 + radius + 1, dtype=int)
  7.     y_ = np.arange(y0 - radius - 1, y0 + radius + 1, dtype=int)
  8.     x, y = np.where((x_[:,np.newaxis] - x0)**2 + (y_ - y0)**2 <= radius**2)
  9.     # x, y = np.where((np.hypot((x_-x0)[:,np.newaxis], y_-y0)<= radius)) # alternative implementation
  10.     for x, y in zip(x_[x], y_[y]):
  11.         yield x, y
  12.  
  13. def points_mode_value(img, points):
  14.     values = [img[y, x] for y, x in points]
  15.     mode = max(set(values), key=values.count)
  16.     return mode
  17.  
  18.  
  19. def main():
  20.   img = cv2.imread('image.png',)
  21.   img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  22.   _, img = cv2.threshold(img, 240, 255, cv2.THRESH_BINARY)
  23.  
  24.   circles = cv2.HoughCircles(
  25.       image=img,
  26.       method=cv2.HOUGH_GRADIENT,
  27.       dp=1,
  28.       minDist=22,
  29.       param1=200,
  30.       param2=7,
  31.       minRadius=10,
  32.       maxRadius=12
  33.   )
  34.   print(circles.shape)
  35.  
  36.   circles = np.round(circles[0, :]).astype("int")
  37.   circles = sorted(circles, key=lambda v: [v[0], v[1]])
  38.  
  39.   img_colored = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
  40.  
  41.   if circles is not None:
  42.       circles = np.uint16(np.around(circles))
  43.       for cont, i in enumerate(circles, start=1):
  44.           points = points_in_circle_np(x0=i[1], y0=i[0], radius=i[2])
  45.           mode = points_mode_value(img, points)
  46.  
  47.           if mode == 255:
  48.               cv2.circle(img_colored, (i[0], i[1]), i[2], (0, 0, 255), -1) # cv2.FILLED)
  49.           else:
  50.               cv2.circle(img_colored, (i[0], i[1]), i[2], (0, 255, 0), -1) # cv2.FILLED)
  51.  
  52.           cv2.putText(img_colored, str(cont), (i[0]-i[2], i[1]+i[2]), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0,0,0), 1, cv2.LINE_AA)
  53.  
  54.    cv2.imwrite("out.png", img_colored)
  55.  
  56.  
  57. if __name__ == "__main__":
  58.   main()
Add Comment
Please, Sign In to add comment