apriltag.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import sys
  2. import argparse
  3. import asyncio
  4. import random
  5. import syndicate
  6. from syndicate import patterns as P, actor, dataspace, turn
  7. import cv2 as cv
  8. import numpy as np
  9. import pyapriltags
  10. from syndicate.schema import sturdy
  11. from preserves.schema import load_schema_file
  12. from pprint import pprint
  13. AprilTagProtocol = load_schema_file('./apriltag.bin').apriltag
  14. AprilTag = AprilTagProtocol.AprilTag
  15. Says = AprilTagProtocol.Says
  16. parser = argparse.ArgumentParser(description='Opens a webcam and tracks any detected Apriltags.',
  17. formatter_class=argparse.ArgumentDefaultsHelpFormatter)
  18. parser.add_argument('--address', metavar='\'<tcp "HOST" PORT>\'',
  19. help='transport address of the server',
  20. default='<ws "ws://localhost:9001/">')
  21. parser.add_argument('--cap', metavar='\'<ref ...>\'',
  22. help='capability for the dataspace on the server',
  23. default='<ref {oid: "syndicate" sig: #[acowDB2/oI+6aSEC3YIxGg==]}>')
  24. args = parser.parse_args()
  25. def getPoints(cap, detector):
  26. red = (0, 0, 255)
  27. if cap.isOpened():
  28. ret, img = cap.read()
  29. gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
  30. detections = detector.detect(gray)
  31. center = None
  32. output = []
  33. for d in detections:
  34. center = np.array(d.center)
  35. center = np.round(center, 0).astype('int')
  36. cv.drawMarker(img, center, red, cv.MARKER_CROSS, thickness=2)
  37. center[1] - 50
  38. cv.putText(img, f'{d.tag_id}', center, cv.FONT_HERSHEY_SIMPLEX, 1.5, red, 2)
  39. output.append([d.tag_id, center[0], center[1]])
  40. cv.imshow('raw', img)
  41. key = cv.waitKey(1)
  42. if key == ord('q'):
  43. return False, output
  44. return True, output
  45. @actor.run_system(name = 'apriltag-emitter', debug = False)
  46. def main():
  47. root_facet = turn.active_facet()
  48. @syndicate.relay.connect(args.address, sturdy.SturdyRef.decode(syndicate.parse(args.cap)))
  49. def on_connected(ds):
  50. turn.on_stop(lambda: turn.stop(root_facet))
  51. cap = cv.VideoCapture(0)
  52. detector = pyapriltags.Detector(families='tagStandard52h13')
  53. @turn.linked_task()
  54. async def accept_input(f):
  55. run = True
  56. tag_handles = {}
  57. while run:
  58. continueRunning, d_list = await asyncio.to_thread(getPoints, cap, detector)
  59. if d_list:
  60. for d in d_list:
  61. tag_id = int(d[0])
  62. x = int(d[1])
  63. y = int(d[2])
  64. turn.external(f, lambda: turn.publish(ds, AprilTag(tag_id, x, y)))
  65. print(f'Publishing: {tag_id}, {x}, {y} !')
  66. run = continueRunning