Skip to content

Free Motion Capture for Everyone πŸ’€βœ¨

TypeScript

show it in the frontend

Endurance Idehenb1298b686ec5
diff --git a/freemocap-ui/src/layout/Navigator.tsx b/freemocap-ui/src/layout/Navigator.tsx
index 1d68f622..fce12a44 100644
--- a/freemocap-ui/src/layout/Navigator.tsx
+++ b/freemocap-ui/src/layout/Navigator.tsx
@@ -8,7 +8,6 @@ import ListItemButton from '@mui/material/ListItemButton';
import ListItemIcon from '@mui/material/ListItemIcon';
import ListItemText from '@mui/material/ListItemText';
import HomeIcon from '@mui/icons-material/Home';
-import PeopleIcon from '@mui/icons-material/People';
import {useNavigate} from "react-router";
const categories = [
@@ -17,27 +16,18 @@ const categories = [
children: [
{
id: 'Show Cameras',
- icon: <PeopleIcon />,
- active: true,
+ route: "/show_cameras"
},
- // { id: 'Database', icon: <DnsRoundedIcon /> },
- // { id: 'Storage', icon: <PermMediaOutlinedIcon /> },
- // { id: 'Hosting', icon: <PublicIcon /> },
- // { id: 'Functions', icon: <SettingsEthernetIcon /> },
- // {
- // id: 'Machine learning',
- // icon: <SettingsInputComponentIcon />,
- // },
+ {
+ id: "Board Detection",
+ route: "/board_detection"
+ },
+ {
+ id: "Skeleton Detection",
+ route: "/skeleton_detection"
+ }
],
},
- // {
- // id: 'Quality',
- // children: [
- // { id: 'Analytics', icon: <SettingsIcon /> },
- // { id: 'Performance', icon: <TimerIcon /> },
- // { id: 'Test Lab', icon: <PhonelinkSetupIcon /> },
- // ],
- // },
];
const item = {
@@ -75,12 +65,12 @@ export const Navigator = function (props: DrawerProps) {
<ListItem sx={{py: 2, px: 3}}>
<ListItemText sx={{color: '#fff'}}>{id}</ListItemText>
</ListItem>
- {children.map(({id: childId, icon, active}) => (
+ {children.map(({id: childId, route}) => (
<ListItem disablePadding key={childId}>
- <ListItemButton selected={active} sx={item} onClick={() => {
- navigate("/show_cameras")
+ <ListItemButton selected={false} sx={item} onClick={() => {
+ navigate(route)
}}>
- <ListItemIcon>{icon}</ListItemIcon>
+ {/*<ListItemIcon>{icon}</ListItemIcon>*/}
<ListItemText>{childId}</ListItemText>
</ListItemButton>
</ListItem>
diff --git a/freemocap-ui/src/layout/routing/router.tsx b/freemocap-ui/src/layout/routing/router.tsx
index 6c5fd598..64f5d377 100644
--- a/freemocap-ui/src/layout/routing/router.tsx
+++ b/freemocap-ui/src/layout/routing/router.tsx
@@ -4,6 +4,8 @@ import {WebcamStreamCapture} from "../../views/Capture";
import {ConfigView} from "../../views/Config";
import {WebcamJonTest} from "../../views/WebcamJonTest";
import {PythonToJsTest} from "../../views/PythonToJsTest";
+import {BoardDetection} from "../../views/BoardDetection";
+import {SkeletonDetection} from "../../views/SkeletonDetection";
export const Router = () => {
return (
@@ -13,6 +15,8 @@ export const Router = () => {
<Route path={'/config'} element={<ConfigView />} />
<Route path={'/jontestplayground'} element={<WebcamJonTest />} />
<Route path={'/pythonToJs'} element={<PythonToJsTest />} />
+ <Route path={'/board_detection'} element={<BoardDetection />} />
+ <Route path={'/skeleton_detection'} element={<SkeletonDetection />} />
</Routes>
)
}
\ No newline at end of file
diff --git a/freemocap-ui/src/views/BoardDetection.tsx b/freemocap-ui/src/views/BoardDetection.tsx
new file mode 100644
index 00000000..74cb2b38
--- /dev/null
+++ b/freemocap-ui/src/views/BoardDetection.tsx
@@ -0,0 +1,30 @@
+import React from "react";
+import {Box} from "@mui/material";
+import {useAsync} from "react-use";
+
+export const BoardDetection = () => {
+ const [data, setData] = React.useState<string>("");
+
+ useAsync(async () => {
+ // const socket = new WebSocket(`ws://localhost:8080/ws/skeleton_detection`);
+ const socket = new WebSocket(`ws://localhost:8080/ws/board_detection`);
+ window.onbeforeunload = function() {
+ socket.onclose = function () {}; // disable onclose handler first
+ socket.close();
+ };
+ socket.onmessage = async (ev: MessageEvent<Blob>) => {
+ const byteData = await ev.data.text();
+ setData(byteData)
+ }
+ }, []);
+
+ if (!data) {
+ return null;
+ }
+
+ return (
+ <Box>
+ {data && <img src={`data:image/png;base64,${data}`} alt={"video capture"}/>}
+ </Box>
+ )
+}
\ No newline at end of file
diff --git a/freemocap-ui/src/views/SkeletonDetection.tsx b/freemocap-ui/src/views/SkeletonDetection.tsx
new file mode 100644
index 00000000..23a4e221
--- /dev/null
+++ b/freemocap-ui/src/views/SkeletonDetection.tsx
@@ -0,0 +1,29 @@
+import React from "react";
+import {Box} from "@mui/material";
+import {useAsync} from "react-use";
+
+export const SkeletonDetection = () => {
+ const [data, setData] = React.useState<string>("");
+
+ useAsync(async () => {
+ const socket = new WebSocket(`ws://localhost:8080/ws/skeleton_detection`);
+ window.onbeforeunload = function() {
+ socket.onclose = function () {}; // disable onclose handler first
+ socket.close();
+ };
+ socket.onmessage = async (ev: MessageEvent<Blob>) => {
+ const byteData = await ev.data.text();
+ setData(byteData)
+ }
+ }, []);
+
+ if (!data) {
+ return null;
+ }
+
+ return (
+ <Box>
+ {data && <img src={`data:image/png;base64,${data}`} alt={"video capture"}/>}
+ </Box>
+ )
+}
\ No newline at end of file
diff --git a/src/api/routes/camera/cam_data_ws.py b/src/api/routes/camera/cam_data_ws.py
index 1f2c60dd..f279f96a 100644
--- a/src/api/routes/camera/cam_data_ws.py
+++ b/src/api/routes/camera/cam_data_ws.py
@@ -1,12 +1,14 @@
+import base64
import logging
from time import perf_counter
+import cv2
import orjson
from fastapi import APIRouter, WebSocket
from src.api.services.board_detect_service import BoardDetectService
from src.api.services.mediapipe_detect_service import MediapipeSkeletonDetectionService
-from src.cameras.opencv_camera import OpenCVCamera
+from src.cameras.opencv_camera import OpenCVCamera, WebcamConfig
logger = logging.getLogger(__name__)
@@ -24,6 +26,30 @@ async def begin_board_detection():
await service.run()
+@cam_ws_router.websocket("/ws/board_detection")
+async def board_detection_as_ws(web_socket: WebSocket):
+ await web_socket.accept()
+
+ async def websocket_send(input_image, webcam_id):
+ success, frame = cv2.imencode(".png", input_image)
+ if success:
+ await web_socket.send_bytes(base64.b64encode(frame.tobytes()))
+
+ await BoardDetectService().run_as_loop(cb=websocket_send)
+
+
+@cam_ws_router.websocket("/ws/skeleton_detection")
+async def skeleton_detection_as_ws(web_socket: WebSocket):
+ await web_socket.accept()
+
+ async def websocket_send(input_image, webcam_id):
+ success, frame = cv2.imencode(".png", input_image)
+ if success:
+ await web_socket.send_bytes(base64.b64encode(frame.tobytes()))
+
+ await MediapipeSkeletonDetectionService().run_as_loop(cb=websocket_send)
+
+
@cam_ws_router.get("/begin_mediapipe_skeleton_detection")
async def begin_mediapipe_skeleton_detection(model_complexity=2):
"""
@@ -39,7 +65,7 @@ async def websocket_endpoint(websocket: WebSocket, webcam_id: str):
await websocket.accept()
# TODO: Consider Spawning a new Process here - alleviate main thread issues
# We could spawn a new Process here directly
- cam = OpenCVCamera(webcam_id=webcam_id)
+ cam = OpenCVCamera(WebcamConfig(webcam_id=webcam_id))
cam.connect()
try:
while True:
@@ -53,7 +79,6 @@ async def websocket_endpoint(websocket: WebSocket, webcam_id: str):
if not success:
continue
d = {
- "frameData": str(image.tobytes()),
# "frameData": base64.b64encode(frame.tobytes()),
"timestamp": timestamp,
}
diff --git a/src/api/routes/camera/camera_route.py b/src/api/routes/camera/camera_route.py
index bc761fbc..7a1eba5e 100644
--- a/src/api/routes/camera/camera_route.py
+++ b/src/api/routes/camera/camera_route.py
@@ -1,25 +1,13 @@
-import uuid
-
-import numpy as np
from fastapi import APIRouter
-from starlette.requests import Request
from src.cameras.cam_singleton import get_or_create_cams
camera_router = APIRouter()
-@camera_router.post("/camera/upload")
-async def stream_camera_bytes(request: Request):
- body = b""
- with open(f"{uuid.uuid4().hex}.webm", "wb") as fd:
- async for chunk in request.stream():
- body += chunk
- fd.write(chunk)
-
- # convert into numpy array
- camera_data = np.frombuffer(body, dtype=np.uint8)
- return camera_data
+@camera_router.post("/camera/config/{webcam_id}")
+async def config_cam(webcam_id: str):
+ pass
@camera_router.get("/camera/detect")
diff --git a/src/api/services/board_detect_service.py b/src/api/services/board_detect_service.py
index c5fed6d1..b3a35d00 100644
--- a/src/api/services/board_detect_service.py
+++ b/src/api/services/board_detect_service.py
@@ -1,6 +1,16 @@
+from typing import NamedTuple
+
from src.core_processor.board_detection.board_detection import BoardDetection
+class ImageResponse(NamedTuple):
+ image: bytes
+ webcam_id: str
+
+
class BoardDetectService:
async def run(self):
await BoardDetection().process()
+
+ async def run_as_loop(self, cb=None):
+ await BoardDetection().process_as_frame_loop(cb)
diff --git a/src/api/services/mediapipe_detect_service.py b/src/api/services/mediapipe_detect_service.py
index af79c61a..ab2dd553 100644
--- a/src/api/services/mediapipe_detect_service.py
+++ b/src/api/services/mediapipe_detect_service.py
@@ -9,3 +9,6 @@ class MediapipeSkeletonDetectionService:
async def run(self):
await MediapipeSkeletonDetection().process()
+
+ async def run_as_loop(self, cb):
+ await MediapipeSkeletonDetection().process_as_frame_loop(cb)
diff --git a/src/cameras/cam_factory.py b/src/cameras/cam_factory.py
index 1d14ff56..905eced7 100644
--- a/src/cameras/cam_factory.py
+++ b/src/cameras/cam_factory.py
@@ -1,12 +1,16 @@
from src.cameras.cam_singleton import get_or_create_cams
-from src.cameras.opencv_camera import OpenCVCamera
+from src.cameras.opencv_camera import OpenCVCamera, WebcamConfig
def create_opencv_cams():
cams = get_or_create_cams()
raw_webcam_obj = cams.cams_to_use
cv_cams = [
- OpenCVCamera(webcam_id=webcam.webcam_id)
+ OpenCVCamera(
+ config=WebcamConfig(
+ webcam_id=webcam.webcam_id,
+ )
+ )
for webcam in raw_webcam_obj
if int(webcam.webcam_id) < 3
]
diff --git a/src/cameras/dto.py b/src/cameras/dto.py
index 6dccab36..c4dae48c 100644
--- a/src/cameras/dto.py
+++ b/src/cameras/dto.py
@@ -1,4 +1,4 @@
-from typing import List, NamedTuple
+from typing import List, NamedTuple, Union
import numpy as np
from pydantic import BaseModel
@@ -15,6 +15,6 @@ class FindAvailableResponse(BaseModel):
class FramePayload(NamedTuple):
- success: bool
- image: np.ndarray
- timestamp: int
+ success: bool = False
+ image: np.ndarray = None
+ timestamp: Union[int, float] = None
diff --git a/src/cameras/frame_grabber.py b/src/cameras/frame_grabber.py
new file mode 100644
index 00000000..06240152
--- /dev/null
+++ b/src/cameras/frame_grabber.py
@@ -0,0 +1,58 @@
+import logging
+import math
+import threading
+import time
+import traceback
+
+import cv2
+
+from src.cameras.dto import FramePayload
+
+logger = logging.getLogger(__name__)
+
+
+class FrameThread(threading.Thread):
+ def __init__(self, get_next_frame, writer: cv2.VideoWriter, save_video=False):
+ super().__init__()
+ self._save_video = save_video
+ self._is_capturing_frames = False
+ self._get_next_frame = get_next_frame
+ self._num_frames_processed = 0
+ self._elapsed = 0
+ self._frame: FramePayload = FramePayload()
+ if save_video:
+ self._writer = writer
+
+ @property
+ def current_fps(self):
+ if self._elapsed <= 0:
+ return 0
+ if self._num_frames_processed <= 0:
+ return 0
+ return int(math.ceil(self._num_frames_processed / self._elapsed))
+
+ @property
+ def latest_frame(self):
+ return self._frame
+
+ def stop(self):
+ self._is_capturing_frames = False
+
+ def run(self):
+ self._start_frame_loop(self._save_video)
+
+ def _start_frame_loop(self, save_video=False):
+ self._is_capturing_frames = True
+ start = time.time()
+ try:
+ while self._is_capturing_frames:
+ success, image, timestamp = self._get_next_frame()
+ if save_video:
+ self._writer.write(image)
+ self._frame = FramePayload(success, image, timestamp)
+ self._num_frames_processed += 1
+ self._elapsed = time.time() - start
+ except:
+ logger.error("Frame loop thread exited")
+ traceback.print_exc()
+ self._writer.release()
diff --git a/src/cameras/open_cv_cam_writer.py b/src/cameras/open_cv_cam_writer.py
new file mode 100644
index 00000000..b1fe01b1
--- /dev/null
+++ b/src/cameras/open_cv_cam_writer.py
@@ -0,0 +1,20 @@
+import os
+import time
+from pathlib import Path
+
+import cv2
+
+
+class OpenCVCamWriter:
+ def create_writer(self, video_capture_obj):
+ frame_width = int(video_capture_obj.get(3))
+ frame_height = int(video_capture_obj.get(4))
+ fps = int(video_capture_obj.get(5))
+ timestr = time.strftime("%Y%m%d_%H%M%S")
+ p = Path().joinpath(os.getcwd(), f"{timestr}.avi").resolve()
+ return cv2.VideoWriter(
+ "outfile.avi",
+ cv2.VideoWriter_fourcc("M", "J", "P", "G"),
+ fps,
+ (frame_width, frame_height),
+ )
diff --git a/src/cameras/opencv_camera.py b/src/cameras/opencv_camera.py
index 636c45ad..30ffa8c7 100644
--- a/src/cameras/opencv_camera.py
+++ b/src/cameras/opencv_camera.py
@@ -1,56 +1,43 @@
import logging
-import math
-import os
import platform
-import threading
import time
-from collections import deque
-from pathlib import Path
import cv2
from pydantic import BaseModel, PrivateAttr
from src.cameras.dto import FramePayload
+from src.cameras.frame_grabber import FrameThread
+from src.cameras.open_cv_cam_writer import OpenCVCamWriter
logger = logging.getLogger(__name__)
-current_working_dir = os.getcwd()
-
-
-class OpenCVCamera(BaseModel):
- """
- Performant implementation of video capture against webcams
- """
+class WebcamConfig(BaseModel):
webcam_id: int = 0
- name: str = f"Camera {webcam_id}"
exposure: int = -6
resolution_width: int = 800
resolution_height: int = 600
- opencv_video_capture_object: cv2.VideoCapture = None
- _is_capturing_frames: bool = PrivateAttr(False)
+
+class OpenCVCamera:
+ """
+ Performant implementation of video capture against webcams
+ """
+
+ _opencv_video_capture_object: cv2.VideoCapture = None
_running_thread = PrivateAttr(None)
- _last_100_frames: deque = PrivateAttr(deque(maxlen=100))
- _num_frames_processed: int = PrivateAttr(0)
- _frame: FramePayload = PrivateAttr(None)
- _elapsed: float = PrivateAttr(0)
- _writer_location: str = PrivateAttr()
- class Config:
- arbitrary_types_allowed = True
+ def __init__(self, config: WebcamConfig):
+ self._config = config
+ self._name = f"Camera {self._config.webcam_id}"
@property
def webcam_id_as_str(self):
- return str(self.webcam_id)
+ return str(self._config.webcam_id)
@property
def current_fps(self):
- if self._elapsed <= 0:
- return 0
- if self._num_frames_processed <= 0:
- return 0
- return int(math.ceil(self._num_frames_processed / self._elapsed))
+ return self._running_thread.current_fps
def connect(self):
if platform.system() == "Windows":
@@ -58,103 +45,69 @@ class OpenCVCamera(BaseModel):
else:
cap_backend = cv2.CAP_ANY
- self.opencv_video_capture_object = cv2.VideoCapture(self.webcam_id, cap_backend)
- success, image = self.opencv_video_capture_object.read()
+ self._opencv_video_capture_object = cv2.VideoCapture(
+ self._config.webcam_id, cap_backend
+ )
+ success, image = self._opencv_video_capture_object.read()
if not success:
logger.error(
- "Could not connect to a camera at port# {}".format(self.webcam_id)
+ "Could not connect to a camera at port# {}".format(
+ self._config.webcam_id
+ )
)
return success
# set camera stream parameters
- # self.opencv_video_capture_object.set(cv2.CAP_PROP_EXPOSURE, self.exposure)
+ # self.opencv_video_capture_object.set(cv2.CAP_PROP_EXPOSURE, self._config.exposure)
# self.opencv_video_capture_object.set(
- # cv2.CAP_PROP_FRAME_WIDTH, self.resolution_width
+ # cv2.CAP_PROP_FRAME_WIDTH, self._config.resolution_width
# )
# self.opencv_video_capture_object.set(
- # cv2.CAP_PROP_FRAME_HEIGHT, self.resolution_height
+ # cv2.CAP_PROP_FRAME_HEIGHT, self._config.resolution_height
# )
- self.opencv_video_capture_object.set(
+ self._opencv_video_capture_object.set(
cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc("M", "J", "P", "G")
)
if success:
- logger.debug(f"Camera found at port number {self.webcam_id}")
- self.name = f"Camera {self.webcam_id}"
- fps_input_stream = int(self.opencv_video_capture_object.get(5))
+ logger.debug(f"Camera found at port number {self._config.webcam_id}")
+
+ fps_input_stream = int(self._opencv_video_capture_object.get(5))
print("FPS of webcam hardware/input stream: {}".format(fps_input_stream))
return success
def start_frame_capture(self, save_video=False):
- t = threading.Thread(
- target=self._start_frame_loop, daemon=True, args=(save_video,)
+ self._running_thread = FrameThread(
+ get_next_frame=self.get_next_frame,
+ writer=OpenCVCamWriter().create_writer(self._opencv_video_capture_object),
+ save_video=save_video,
)
- t.start()
- self._running_thread = t
+ self._running_thread.start()
def stop_frame_capture(self):
- self._is_capturing_frames = False
+ self._running_thread.stop()
+ @property
def latest_frame(self):
- if not self._frame:
- return False, None, None
- return self._frame
-
- def _prepare_writer(self):
- frame_width = int(self.opencv_video_capture_object.get(3))
- frame_height = int(self.opencv_video_capture_object.get(4))
- fps = int(self.opencv_video_capture_object.get(5))
- timestr = time.strftime("%Y%m%d_%H%M%S")
- p = Path().joinpath(current_working_dir, f"{timestr}.avi").resolve()
- return cv2.VideoWriter(
- "outfile.avi",
- cv2.VideoWriter_fourcc("M", "J", "P", "G"),
- # cv2.VideoWriter_fourcc('A', 'V', 'C', '1'),
- fps,
- (frame_width, frame_height),
- )
-
- def _start_frame_loop(self, save_video=False):
- self._is_capturing_frames = True
- start = time.time()
- writer = None
- if save_video:
- writer = self._prepare_writer()
- try:
- while self._is_capturing_frames:
- success, image, timestamp = self.get_next_frame()
- # will this slow us down?
- if save_video:
- writer.write(image)
- self._frame = FramePayload(success, image, timestamp)
- self._last_100_frames.append((success, image, timestamp))
- self._num_frames_processed += 1
- self._elapsed = time.time() - start
- except:
- writer.release()
+ return self._running_thread.latest_frame
def get_next_frame(self):
timestamp_ns_pre_grab = time.time_ns()
# Why grab not read? see ->
# https://stackoverflow.com/questions/57716962/difference-between-video-capture-read-and
# -grab
- grab_success = self.opencv_video_capture_object.grab()
+ grab_success = self._opencv_video_capture_object.grab()
timestamp_ns_post_grab = time.time_ns()
timestamp_ns = (timestamp_ns_pre_grab + timestamp_ns_post_grab) / 2
if grab_success:
- success, image = self.opencv_video_capture_object.retrieve()
- # logger.info('{} successfully grabbed a frame at timestamp {}'.format(self.name,
- # timestamp_ns/1e9))
- return success, image, timestamp_ns
-
- return False, None, None
+ success, image = self._opencv_video_capture_object.retrieve()
+ return FramePayload(success, image, timestamp_ns)
- def read_next_frame(self):
- return self.opencv_video_capture_object.read()
+ return FramePayload(False, None, None)
def close(self):
- self.opencv_video_capture_object.release()
- logger.info("Closed camera {}".format(self.name))
+ self._opencv_video_capture_object.release()
+ logger.info("Closed camera {}".format(self._name))
diff --git a/src/core_processor/board_detection/board_detection.py b/src/core_processor/board_detection/board_detection.py
index b2c5e8b7..9bb09f34 100644
--- a/src/core_processor/board_detection/board_detection.py
+++ b/src/core_processor/board_detection/board_detection.py
@@ -1,5 +1,6 @@
-import asyncio
import logging
+import traceback
+from queue import Queue
import cv2
import numpy as np
@@ -9,11 +10,31 @@ from src.core_processor.board_detection.base_pose_estimation import detect_charu
from src.core_processor.board_detection.charuco_image_annotator import (
annotate_image_with_charuco_data,
)
+from src.core_processor.utils.image_fps_writer import write_fps_to_image
+
+logger = logging.getLogger(__name__)
class BoardDetection:
+ async def process_as_frame_loop(self, cb):
+ cv_cams = create_opencv_cams()
+ for cv_cam in cv_cams:
+ cv_cam.start_frame_capture(save_video=True)
+
+ while True:
+ try:
+ for cv_cam in cv_cams:
+ image = self._process_single_cam_frame(cv_cam)
+ if cb:
+ await cb(image, cv_cam.webcam_id_as_str)
+ except:
+ traceback.print_exc()
+
async def process(self):
- logger = logging.getLogger(__name__)
+ """
+ Opens Camera using OpenCV and begins image processing for charuco board
+ If return images is true, the images are returned to the caller
+ """
cv_cams = create_opencv_cams()
for cv_cam in cv_cams:
@@ -23,44 +44,39 @@ class BoardDetection:
exit_key = cv2.waitKey(1)
if exit_key == 27:
cv2.destroyAllWindows()
+ for cv_cam in cv_cams:
+ cv_cam.close()
break
for cv_cam in cv_cams:
- success, frame, timestamp = cv_cam.latest_frame()
- if not success:
- logger.error("CV2 failed to grab a frame")
- continue
- if frame is None:
- logger.error("Frame is empty")
- continue
- (
- charuco_corners,
- charuco_ids,
- aruco_square_corners,
- aruco_square_ids,
- ) = detect_charuco_board(frame)
- # TODO - Pull out timestamps per frame and calculate fps to display on image
- success_bool = annotate_image_with_charuco_data(
- frame, cv_cam.webcam_id_as_str, charuco_corners, charuco_ids
- )
-
- cv2.polylines(
- frame, np.int32([charuco_corners]), True, (0, 100, 255), 2
- )
- self.apply_fps(frame, cv_cam.current_fps)
- cv2.imshow(cv_cam.webcam_id_as_str, frame)
+ frame = self._process_single_cam_frame(cv_cam)
+ if frame is not None:
+ cv2.imshow(cv_cam.webcam_id_as_str, frame)
- def apply_fps(self, image, fps_number):
- cv2.putText(
- image,
- f"FPS: {str(fps_number)}",
- (10, 15),
- cv2.FONT_HERSHEY_SIMPLEX,
- 0.5,
- (209, 180, 0, 255),
- 1,
+ def _process_single_cam_frame(self, cv_cam):
+ success, frame, timestamp = cv_cam.latest_frame
+ if not success:
+ logger.error("CV2 failed to grab a frame")
+ return
+ if frame is None:
+ logger.error("Frame is empty")
+ return
+ (
+ charuco_corners,
+ charuco_ids,
+ aruco_square_corners,
+ aruco_square_ids,
+ ) = detect_charuco_board(frame)
+ # TODO - Pull out timestamps per frame and calculate fps to display on image
+ success_bool = annotate_image_with_charuco_data(
+ frame, cv_cam.webcam_id_as_str, charuco_corners, charuco_ids
)
+ cv2.polylines(frame, np.int32([charuco_corners]), True, (0, 100, 255), 2)
+ write_fps_to_image(frame, cv_cam.current_fps)
+ return frame
if __name__ == "__main__":
## Jon, Run me to easily start a charuco board detect run
- asyncio.run(BoardDetection().process())
+ # asyncio.run(BoardDetection().process())
+ q = Queue()
+ BoardDetection().process_as_frame_loop(q)
diff --git a/src/tests/mediapipe_testing.py b/src/core_processor/experiments/mediapipe_testing.py
similarity index 100%
rename from src/tests/mediapipe_testing.py
rename to src/core_processor/experiments/mediapipe_testing.py
diff --git a/src/core_processor/experiments/nested_thread_queue.py b/src/core_processor/experiments/nested_thread_queue.py
new file mode 100644
index 00000000..f7fc350c
--- /dev/null
+++ b/src/core_processor/experiments/nested_thread_queue.py
@@ -0,0 +1,28 @@
+import base64
+import threading
+import traceback
+from queue import Queue
+
+import orjson
+
+from src.api.services.board_detect_service import BoardDetectService
+
+
+def tryit():
+ service = BoardDetectService()
+ output_queue = Queue()
+ t = threading.Thread(target=service.run_as_loop, args=(output_queue,), daemon=True)
+ t.start()
+
+ while True:
+ try:
+ # success, frame = cv2.imencode('.png', image)
+ image, webcam_id = output_queue.get(timeout=1)
+ if image is not None:
+ d = orjson.dumps({"frame": str(base64.b64encode(image.tobytes()))})
+ except:
+ traceback.print_exc()
+
+
+if __name__ == "__main__":
+ tryit()
diff --git a/src/core_processor/testing/threading_single_cam.py b/src/core_processor/experiments/threading_single_cam.py
similarity index 86%
rename from src/core_processor/testing/threading_single_cam.py
rename to src/core_processor/experiments/threading_single_cam.py
index 39b3fbec..f9eca6c2 100644
--- a/src/core_processor/testing/threading_single_cam.py
+++ b/src/core_processor/experiments/threading_single_cam.py
@@ -19,7 +19,7 @@ class WebcamStream:
# reading a single frame from vcap stream for initializing
self.grabbed, self.frame = self.vcap.read()
if self.grabbed is False:
- print('[Exiting] No more frames to read')
+ print("[Exiting] No more frames to read")
exit(0)
# self.stopped is set to False when frames are being read from self.vcap stream
@@ -27,7 +27,9 @@ class WebcamStream:
# reference to the thread for reading next available frame from input stream
self.t = Thread(target=self.update, args=())
- self.t.daemon = True # daemon threads keep running in the background while the program
+ self.t.daemon = (
+ True # daemon threads keep running in the background while the program
+ )
# is executing
# method for starting the thread for grabbing next available frame in input stream
@@ -43,7 +45,7 @@ class WebcamStream:
break
self.grabbed, self.frame = self.vcap.read()
if self.grabbed is False:
- print('[Exiting] No more frames to read')
+ print("[Exiting] No more frames to read")
self.stopped = True
break
self.vcap.release()
@@ -81,10 +83,10 @@ while True:
time.sleep(delay)
num_frames_processed += 1
- cv2.imshow('frame1', frame1)
- cv2.imshow('frame2', frame2)
+ cv2.imshow("frame1", frame1)
+ cv2.imshow("frame2", frame2)
key = cv2.waitKey(1)
- if key == ord('q'):
+ if key == ord("q"):
break
end = time.time()
webcam_stream1.stop() # stop the webcam stream
@@ -94,7 +96,10 @@ webcam_stream2.stop() # stop the webcam stream
elapsed = end - start
fps = num_frames_processed / elapsed
print(
- "FPS: {} , Elapsed Time: {} , Frames Processed: {}".format(fps, elapsed, num_frames_processed))
+ "FPS: {} , Elapsed Time: {} , Frames Processed: {}".format(
+ fps, elapsed, num_frames_processed
+ )
+)
# closing all windows
cv2.destroyAllWindows()
diff --git a/src/core_processor/mediapipe_skeleton_detection/mediapipe_skeleton_detection.py b/src/core_processor/mediapipe_skeleton_detection/mediapipe_skeleton_detection.py
index d49a8acb..84d17742 100644
--- a/src/core_processor/mediapipe_skeleton_detection/mediapipe_skeleton_detection.py
+++ b/src/core_processor/mediapipe_skeleton_detection/mediapipe_skeleton_detection.py
@@ -1,19 +1,41 @@
import asyncio
import logging
+import traceback
import cv2
import mediapipe as mp
from src.cameras.cam_factory import create_opencv_cams
+from src.core_processor.utils.image_fps_writer import write_fps_to_image
mp_holistic = mp.solutions.holistic
mp_drawing = mp.solutions.drawing_utils
mp_drawing_styles = mp.solutions.drawing_styles
+logger = logging.getLogger(__name__)
+
class MediapipeSkeletonDetection:
+ async def process_as_frame_loop(self, cb):
+ cv_cams = create_opencv_cams()
+ for cv_cam in cv_cams:
+ cv_cam.start_frame_capture(save_video=True)
+
+ with mp_holistic.Holistic(
+ min_detection_confidence=0.5,
+ min_tracking_confidence=0.5,
+ model_complexity=0,
+ ) as holistic:
+ while True:
+ try:
+ for cv_cam in cv_cams:
+ image = self._process_single_cam_frame(holistic, cv_cam)
+ if cb:
+ await cb(image, cv_cam.webcam_id_as_str)
+ except:
+ traceback.print_exc()
+
async def process(self):
- logger = logging.getLogger(__name__)
cv_cams = create_opencv_cams()
for cv_cam in cv_cams:
@@ -29,18 +51,22 @@ class MediapipeSkeletonDetection:
if exit_key == 27:
break
for cv_cam in cv_cams:
- success, frame, timestamp = cv_cam.latest_frame()
- if not success:
- logger.error("CV2 failed to grab a frame")
- continue
- if frame is None:
- logger.error("Frame is empty")
- continue
-
- image = self.detect_mediapipe_skeleton(holistic, frame)
- self.apply_fps(image, cv_cam.current_fps)
+ image = self._process_single_cam_frame(holistic, cv_cam)
cv2.imshow(cv_cam.webcam_id_as_str, image)
+ def _process_single_cam_frame(self, holistic, cv_cam):
+ success, frame, timestamp = cv_cam.latest_frame
+ if not success:
+ logger.error("CV2 failed to grab a frame")
+ return
+ if frame is None:
+ logger.error("Frame is empty")
+ return
+
+ image = self.detect_mediapipe_skeleton(holistic, frame)
+ write_fps_to_image(image, cv_cam.current_fps)
+ return image
+
def detect_mediapipe_skeleton(self, holistic, image):
# adapted from 'webcam' part of demo code here -
# https://google.github.io/mediapipe/solutions/holistic.html
@@ -70,17 +96,6 @@ class MediapipeSkeletonDetection:
)
return image
- def apply_fps(self, image, fps_number):
- cv2.putText(
- image,
- f"FPS: {str(fps_number)}",
- (10, 15),
- cv2.FONT_HERSHEY_SIMPLEX,
- 0.5,
- (209, 180, 0, 255),
- 1,
- )
-
if __name__ == "__main__":
asyncio.run(MediapipeSkeletonDetection().process())
diff --git a/src/core_processor/utils/image_fps_writer.py b/src/core_processor/utils/image_fps_writer.py
new file mode 100644
index 00000000..35542a4b
--- /dev/null
+++ b/src/core_processor/utils/image_fps_writer.py
@@ -0,0 +1,13 @@
+import cv2
+
+
+def write_fps_to_image(image, fps_number):
+ cv2.putText(
+ image,
+ f"FPS: {str(fps_number)}",
+ (10, 15),
+ cv2.FONT_HERSHEY_SIMPLEX,
+ 0.5,
+ (209, 180, 0, 255),
+ 1,
+ )