main.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import zmq
  2. import cv2
  3. import numpy as np
  4. context = zmq.Context()
  5. socket = context.socket(zmq.SUB)
  6. socket.setsockopt(zmq.SUBSCRIBE, b"")
  7. port = 5055
  8. socket.connect(f"tcp://192.168.0.113:{port}")
  9. n = 0
  10. cv2.namedWindow('Image', cv2.WINDOW_GUI_NORMAL)
  11. cv2.namedWindow('Debug', cv2.WINDOW_GUI_NORMAL)
  12. lower = 100
  13. upper = 200
  14. def lower_update(value):
  15. global lower
  16. lower = value
  17. def upper_update(value):
  18. global upper
  19. upper = value
  20. cv2.createTrackbar("Lower", "Debug", lower, 255, lower_update)
  21. cv2.createTrackbar("Upper", "Debug", upper, 255, upper_update)
  22. while True:
  23. bts = socket.recv()
  24. n += 1
  25. arr = np.frombuffer(bts, np.uint8)
  26. image = cv2.imdecode(arr, cv2.IMREAD_COLOR)
  27. gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  28. gray = cv2.GaussianBlur(gray, (7,7), 0)
  29. mask = cv2.Canny(gray, lower, upper)
  30. cnts, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
  31. rect = cv2.minAreaRect(cnts[0])
  32. box = cv2.boxPoints(rect)
  33. box = np.intp(box)
  34. approx = cv2.approxPolyDP(box, 0.3, True)
  35. A4_shape = np.float32([[0,870], [0, 0], [620,0], [620,877]])
  36. A4 = np.zeros((870, 620))
  37. mask = cv2.getPerspectiveTransform(approx[:, 0, :].astype('float32'), A4_shape)
  38. only_list = cv2.warpPerspective(image, mask, (640, 480))
  39. cv2.putText(only_list, "Hello world", (10, 60), cv2.FONT_HERSHEY_SIMPLEX,
  40. 0.7, (127, 255, 255))
  41. mask = cv2.getPerspectiveTransform(A4_shape, approx[:, 0, :].astype('float32'))
  42. listText = cv2.warpPerspective(only_list, mask, (640, 480))
  43. listText[np.all(listText < 150, axis=2)] = image[np.all(listText < 150, axis=2)]
  44. for pos in approx:
  45. cv2.circle(image, pos[0], 2, (0, 255, 0), 10)
  46. cv2.imshow('Image', listText)
  47. key = cv2.waitKey(10)
  48. if key == ord('q'):
  49. break