Advertisement
dan-masek

Untitled

Dec 1st, 2022
575
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.94 KB | None | 0 0
  1. import cv2
  2. import numpy as np
  3. import math
  4.  
  5. img = cv2.imread('TUP74.jpg', cv2.IMREAD_COLOR)
  6. height, width = img.shape[:2]
  7.  
  8. _, thresh = cv2.threshold(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), 31, 255, cv2.THRESH_BINARY)
  9.  
  10. # Find top/bottom of the circle, to determine radius
  11.  
  12. row_info = cv2.findNonZero(cv2.reduce(thresh, 1, cv2.REDUCE_MAX))
  13. first_y, last_y = row_info[0][0][1], row_info[-1][0][1]
  14.  
  15. diameter = last_y - first_y
  16. radius = int(diameter / 2)
  17. center_y = first_y + radius
  18.  
  19. # Repeat again, just on first column
  20.  
  21. row_info = cv2.findNonZero(thresh[:,0])
  22. first_y, last_y = row_info[0][0][1], row_info[-1][0][1]
  23.  
  24. h = last_y - first_y
  25. center_x = int(math.sqrt(radius**2 - (h/2)**2))
  26.  
  27. cv2.circle(img, (center_x,center_y), radius, (0,0,255), 2)
  28.  
  29. s = int(math.sqrt(radius**2 / 2))
  30.  
  31. tl = (center_x - s, center_y - s)
  32. br = (center_x + s, center_y + s)
  33.  
  34. cv2.rectangle(img, tl, br, (255,0,0), 2)
  35.  
  36. cv2.imshow('', img)
  37. cv2.waitKey()
  38.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement