recognizer.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import cv2
  2. cv2.namedWindow("Image", cv2.WINDOW_GUI_NORMAL)
  3. def chose(contour):
  4. sm = cv2.arcLength(contour, True)
  5. approx = cv2.approxPolyDP(contour, sm*0.025, True)
  6. if len(approx) == 4: return 'square'
  7. elif len(approx) == 8: return 'circle'
  8. def recognize(image, n, video=False):
  9. image_hsv = cv2.cvtColor(image.copy(), cv2.COLOR_BGR2HSV)
  10. image_hsv = image_hsv[:,:,1]
  11. _, thres = cv2.threshold(image_hsv.copy(), 50, 255, cv2.THRESH_BINARY)
  12. image_hsv = cv2.dilate(thres, None, iterations=3)
  13. distance_map = cv2.distanceTransform(thres, cv2.DIST_L2, 5)
  14. ret ,dist_thres= cv2.threshold(distance_map, 0.6 * distance_map.max(), 255, cv2.THRESH_BINARY)
  15. confuse = cv2.subtract(thres, dist_thres.astype('uint8'))
  16. ret, markers = cv2.connectedComponents(dist_thres.astype('uint8'))
  17. markers += 1
  18. markers[confuse == 255] = 0
  19. segments = cv2.watershed(image, markers)
  20. cnts, hierrache = cv2.findContours(segments, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
  21. squares = 0
  22. circles = 0
  23. color = 100
  24. for i,contour in enumerate(cnts[:-2]):
  25. x,y = cv2.boundingRect(contour)[0:2]
  26. x2,y2 = cv2.boundingRect(cnts[i+1])[0:2]
  27. if abs(x-x2) < 25 and (y-y2) < 25: continue
  28. cv2.drawContours(image, cnts[:-2], i, (0, color, 0), 10)
  29. clase = chose(contour)
  30. if clase == 'square': squares += 1
  31. elif clase == 'circle': circles += 1
  32. color+=10
  33. cv2.putText(image, f"Circles count = {circles}, quadro count = {squares}", (10, 20), cv2.FONT_HERSHEY_SIMPLEX,
  34. 0.7, (127, 255, 255))
  35. cv2.putText(image, f"Image = {n}", (10, 60), cv2.FONT_HERSHEY_SIMPLEX,
  36. 0.7, (127, 255, 255))
  37. cv2.imshow("Image", image)
  38. while not video and cv2.waitKey(1) != ord('q'): continue
  39. if __name__ == "__main__":
  40. image = cv2.imread('/home/jezvcp/Projects/Volovikov_CV/count_objects/out-fotor-20240514183622.png')
  41. recognize(image, 0)
  42. cv2.destroyAllWindows()