You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

main.py 6.6 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. import argparse
  2. import os
  3. import cv2
  4. import numpy as np
  5. import pyarrow as pa
  6. from dora import Node
  7. RUNNER_CI = True if os.getenv("CI") == "true" else False
  8. class Plot:
  9. frame: np.array = np.array([])
  10. bboxes: dict = {
  11. "bbox": np.array([]),
  12. "conf": np.array([]),
  13. "labels": np.array([]),
  14. }
  15. text: str = ""
  16. width: np.uint32 = None
  17. height: np.uint32 = None
  18. def plot_frame(plot):
  19. for bbox in zip(plot.bboxes["bbox"], plot.bboxes["conf"], plot.bboxes["labels"]):
  20. [
  21. [min_x, min_y, max_x, max_y],
  22. confidence,
  23. label,
  24. ] = bbox
  25. cv2.rectangle(
  26. plot.frame,
  27. (int(min_x), int(min_y)),
  28. (int(max_x), int(max_y)),
  29. (0, 255, 0),
  30. 2,
  31. )
  32. cv2.putText(
  33. plot.frame,
  34. f"{label}, {confidence:0.2f}",
  35. (int(max_x) - 120, int(max_y) - 10),
  36. cv2.FONT_HERSHEY_SIMPLEX,
  37. 0.5,
  38. (0, 255, 0),
  39. 1,
  40. 1,
  41. )
  42. cv2.putText(
  43. plot.frame,
  44. plot.text,
  45. (20, 20),
  46. cv2.FONT_HERSHEY_SIMPLEX,
  47. 0.5,
  48. (255, 255, 255),
  49. 1,
  50. 1,
  51. )
  52. if plot.width is not None and plot.height is not None:
  53. plot.frame = cv2.resize(plot.frame, (plot.width, plot.height))
  54. if not RUNNER_CI:
  55. if len(plot.frame.shape) >= 3:
  56. cv2.imshow("Dora Node: opencv-plot", plot.frame)
  57. def yuv420p_to_bgr_opencv(yuv_array, width, height):
  58. yuv = yuv_array.reshape((height * 3 // 2, width))
  59. return cv2.cvtColor(yuv, cv2.COLOR_YUV420p2RGB)
  60. def main():
  61. # Handle dynamic nodes, ask for the name of the node in the dataflow, and the same values as the ENV variables.
  62. parser = argparse.ArgumentParser(
  63. description="OpenCV Plotter: This node is used to plot text and bounding boxes on an image."
  64. )
  65. parser.add_argument(
  66. "--name",
  67. type=str,
  68. required=False,
  69. help="The name of the node in the dataflow.",
  70. default="opencv-plot",
  71. )
  72. parser.add_argument(
  73. "--plot-width",
  74. type=int,
  75. required=False,
  76. help="The width of the plot.",
  77. default=None,
  78. )
  79. parser.add_argument(
  80. "--plot-height",
  81. type=int,
  82. required=False,
  83. help="The height of the plot.",
  84. default=None,
  85. )
  86. args = parser.parse_args()
  87. plot_width = os.getenv("PLOT_WIDTH", args.plot_width)
  88. plot_height = os.getenv("PLOT_HEIGHT", args.plot_height)
  89. if plot_width is not None:
  90. if isinstance(plot_width, str) and plot_width.isnumeric():
  91. plot_width = int(plot_width)
  92. if plot_height is not None:
  93. if isinstance(plot_height, str) and plot_height.isnumeric():
  94. plot_height = int(plot_height)
  95. node = Node(
  96. args.name
  97. ) # provide the name to connect to the dataflow if dynamic node
  98. plot = Plot()
  99. plot.width = plot_width
  100. plot.height = plot_height
  101. pa.array([]) # initialize pyarrow array
  102. for event in node:
  103. event_type = event["type"]
  104. if event_type == "INPUT":
  105. event_id = event["id"]
  106. if event_id == "image":
  107. storage = event["value"]
  108. metadata = event["metadata"]
  109. encoding = metadata["encoding"]
  110. width = metadata["width"]
  111. height = metadata["height"]
  112. if encoding == "bgr8":
  113. channels = 3
  114. storage_type = np.uint8
  115. plot.frame = (
  116. storage.to_numpy()
  117. .astype(storage_type)
  118. .reshape((height, width, channels))
  119. .copy() # Copy So that we can add annotation on the image
  120. )
  121. elif encoding == "rgb8":
  122. channels = 3
  123. storage_type = np.uint8
  124. frame = (
  125. storage.to_numpy()
  126. .astype(storage_type)
  127. .reshape((height, width, channels))
  128. )
  129. plot.frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
  130. elif encoding in ["jpeg", "jpg", "jpe", "bmp", "webp", "png"]:
  131. channels = 3
  132. storage_type = np.uint8
  133. storage = storage.to_numpy()
  134. plot.frame = cv2.imdecode(storage, cv2.IMREAD_COLOR)
  135. elif encoding == "yuv420":
  136. storage = storage.to_numpy()
  137. # Convert back to BGR results in more saturated image.
  138. channels = 3
  139. storage_type = np.uint8
  140. img_bgr_restored = yuv420p_to_bgr_opencv(storage, width, height)
  141. plot.frame = img_bgr_restored
  142. else:
  143. raise RuntimeError(f"Unsupported image encoding: {encoding}")
  144. plot_frame(plot)
  145. if not RUNNER_CI:
  146. if cv2.waitKey(1) & 0xFF == ord("q"):
  147. break
  148. elif event_id == "bbox":
  149. arrow_bbox = event["value"][0]
  150. bbox_format = event["metadata"]["format"]
  151. if bbox_format == "xyxy":
  152. bbox = arrow_bbox["bbox"].values.to_numpy().reshape(-1, 4)
  153. elif bbox_format == "xywh":
  154. original_bbox = arrow_bbox["bbox"].values.to_numpy().reshape(-1, 4)
  155. bbox = np.array(
  156. [
  157. (
  158. x - w / 2,
  159. y - h / 2,
  160. x + w / 2,
  161. y + h / 2,
  162. )
  163. for [x, y, w, h] in original_bbox
  164. ]
  165. )
  166. else:
  167. raise RuntimeError(f"Unsupported bbox format: {bbox_format}")
  168. plot.bboxes = {
  169. "bbox": bbox,
  170. "conf": arrow_bbox["conf"].values.to_numpy(),
  171. "labels": arrow_bbox["labels"].values.to_numpy(
  172. zero_copy_only=False
  173. ),
  174. }
  175. elif event_id == "text":
  176. plot.text = event["value"][0].as_py()
  177. elif event_type == "ERROR":
  178. raise RuntimeError(event["error"])
  179. if __name__ == "__main__":
  180. main()