main.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import cv2
  2. import zmq
  3. import numpy as np
  4. cv2.namedWindow("Image", cv2.WINDOW_GUI_NORMAL)
  5. cv2.namedWindow("Mask", cv2.WINDOW_GUI_NORMAL)
  6. context = zmq.Context()
  7. socket = context.socket(zmq.SUB)
  8. socket.setsockopt(zmq.SUBSCRIBE, b"")
  9. port = 5055
  10. socket.connect(f"tcp://192.168.0.113:{port}")
  11. n = 0
  12. while True:
  13. bts = socket.recv()
  14. n += 1
  15. arr = np.frombuffer(bts, np.uint8)
  16. image = cv2.imdecode(arr, cv2.IMREAD_COLOR)
  17. hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
  18. _, thresh = cv2.threshold(hsv[:, :, 1], 70, 255, cv2.THRESH_BINARY)
  19. distance_map = cv2.distanceTransform(thresh, cv2.DIST_L2, 5)
  20. ret, dist_tresh = cv2.threshold(
  21. distance_map, 0.6 * np.max(distance_map), 255, cv2.THRESH_BINARY
  22. )
  23. confuse = cv2.subtract(thresh, dist_tresh.astype("uint8"))
  24. ret, markers = cv2.connectedComponents(dist_tresh.astype("uint8"))
  25. markers += 1
  26. markers[confuse == 255] = 0
  27. segments = cv2.watershed(image, markers)
  28. cnts, hierrachy = cv2.findContours(
  29. segments, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE
  30. )
  31. n_circ = 0
  32. n_rect = 0
  33. for i in range(len(cnts)):
  34. if hierrachy[0][i][3] == -1:
  35. rect = cv2.minAreaRect(cnts[i])
  36. box = cv2.boxPoints(rect)
  37. box = np.int0(box)
  38. width, height = rect[1]
  39. if abs(width - height) < 10:
  40. n_circ += 1
  41. else:
  42. n_rect += 1
  43. cv2.drawContours(image, [box], 0, (0, 255, 0), 10)
  44. cv2.putText(
  45. image,
  46. f"Circles: {n_circ}",
  47. (10, 20),
  48. cv2.FONT_HERSHEY_SIMPLEX,
  49. 0.5,
  50. (0, 0, 255),
  51. 2,
  52. )
  53. cv2.putText(
  54. image,
  55. f"Rects: {n_rect}",
  56. (10, 40),
  57. cv2.FONT_HERSHEY_SIMPLEX,
  58. 0.5,
  59. (0, 0, 255),
  60. 2,
  61. )
  62. key = cv2.waitKey(10)
  63. if key == ord("q"):
  64. break
  65. cv2.imshow("Image", image)
  66. cv2.imshow("Mask", confuse)
  67. cv2.destroyAllWindows()