Skip to content

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

TypeScript

add video saving and mediapipe updates

Endurance Idehendc3e777de614
diff --git a/.gitignore b/.gitignore
index f0a21633..395f7738 100644
--- a/.gitignore
+++ b/.gitignore
@@ -142,3 +142,7 @@ freemocap/fmc_startup/user_preferences.yaml
.obsidian/
data/
+
+*.avi
+*.mp4
+*.divx
\ No newline at end of file
diff --git a/src/__init__.py b/src/__init__.py
index 6a6ca888..3be04a42 100644
--- a/src/__init__.py
+++ b/src/__init__.py
@@ -1,3 +1,3 @@
-from src.config import configure_logging
+from src.log.config import configure_logging
configure_logging()
diff --git a/src/cameras/dto.py b/src/cameras/dto.py
index 3358757c..6dccab36 100644
--- a/src/cameras/dto.py
+++ b/src/cameras/dto.py
@@ -15,10 +15,6 @@ class FindAvailableResponse(BaseModel):
class FramePayload(NamedTuple):
- webcam_id: int
+ success: bool
image: np.ndarray
timestamp: int
-
-
-class ImagePayload(NamedTuple):
- frames: List[FramePayload] = None
diff --git a/src/cameras/opencv_camera.py b/src/cameras/opencv_camera.py
index f9854503..636c45ad 100644
--- a/src/cameras/opencv_camera.py
+++ b/src/cameras/opencv_camera.py
@@ -1,15 +1,21 @@
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 collections import deque
+
+from src.cameras.dto import FramePayload
logger = logging.getLogger(__name__)
+current_working_dir = os.getcwd()
+
class OpenCVCamera(BaseModel):
"""
@@ -26,10 +32,10 @@ class OpenCVCamera(BaseModel):
_is_capturing_frames: bool = PrivateAttr(False)
_running_thread = PrivateAttr(None)
_last_100_frames: deque = PrivateAttr(deque(maxlen=100))
- _fps: float = PrivateAttr(0)
_num_frames_processed: int = PrivateAttr(0)
- _frame: tuple = PrivateAttr(None)
+ _frame: FramePayload = PrivateAttr(None)
_elapsed: float = PrivateAttr(0)
+ _writer_location: str = PrivateAttr()
class Config:
arbitrary_types_allowed = True
@@ -81,8 +87,10 @@ class OpenCVCamera(BaseModel):
print("FPS of webcam hardware/input stream: {}".format(fps_input_stream))
return success
- def start_frame_capture(self):
- t = threading.Thread(target=self._start_frame_loop, daemon=True)
+ def start_frame_capture(self, save_video=False):
+ t = threading.Thread(
+ target=self._start_frame_loop, daemon=True, args=(save_video,)
+ )
t.start()
self._running_thread = t
@@ -94,15 +102,38 @@ class OpenCVCamera(BaseModel):
return False, None, None
return self._frame
- def _start_frame_loop(self):
+ 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()
- while self._is_capturing_frames:
- success, image, timestamp = self.get_next_frame()
- self._frame = (success, image, timestamp)
- self._last_100_frames.append((success, image, timestamp))
- self._num_frames_processed += 1
- self._elapsed = time.time() - start
+ 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()
def get_next_frame(self):
timestamp_ns_pre_grab = time.time_ns()
@@ -121,6 +152,9 @@ class OpenCVCamera(BaseModel):
return False, None, None
+ def read_next_frame(self):
+ return self.opencv_video_capture_object.read()
+
def close(self):
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 0023d94c..24670cd9 100644
--- a/src/core_processor/board_detection/board_detection.py
+++ b/src/core_processor/board_detection/board_detection.py
@@ -17,11 +17,12 @@ class BoardDetection:
cv_cams = create_opencv_cams()
for cv_cam in cv_cams:
- cv_cam.start_frame_capture()
+ cv_cam.start_frame_capture(save_video=True)
while True:
exit_key = cv2.waitKey(1)
if exit_key == 27:
+ cv2.destroyAllWindows()
break
for cv_cam in cv_cams:
success, frame, timestamp = cv_cam.latest_frame()
@@ -50,9 +51,6 @@ class BoardDetection:
)
self.apply_fps(frame, cv_cam.current_fps)
cv2.imshow(cv_cam.webcam_id_as_str, frame)
- exit_key = cv2.waitKey(1)
- if exit_key == 27:
- break
def apply_fps(self, image, fps_number):
cv2.putText(
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 7ea94f7c..a70f4d25 100644
--- a/src/core_processor/mediapipe_skeleton_detection/mediapipe_skeleton_detection.py
+++ b/src/core_processor/mediapipe_skeleton_detection/mediapipe_skeleton_detection.py
@@ -1,3 +1,4 @@
+import asyncio
import logging
import cv2
@@ -5,6 +6,8 @@ import mediapipe as mp
from src.cameras.cam_factory import create_opencv_cams
+mp_holistic = mp.solutions.holistic
+
class MediapipeSkeletonDetection:
async def process(self):
@@ -14,27 +17,29 @@ class MediapipeSkeletonDetection:
for cv_cam in cv_cams:
cv_cam.start_frame_capture()
- while True:
- exit_key = cv2.waitKey(1)
- 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
- print(
- f"got image of shape {frame.shape} from camera at port {cv_cam.webcam_id}"
- )
+ with mp_holistic.Holistic(
+ min_detection_confidence=0.5,
+ min_tracking_confidence=0.5,
+ model_complexity=0,
+ ) as holistic:
+ while True:
+ exit_key = cv2.waitKey(1)
+ 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(frame)
+ image = self.detect_mediapipe_skeleton(holistic, frame)
- cv2.imshow(cv_cam.webcam_id_as_str, image)
+ cv2.imshow(cv_cam.webcam_id_as_str, image)
- def detect_mediapipe_skeleton(self, image):
+ def detect_mediapipe_skeleton(self, holistic, image):
# adapted from 'webcam' part of demo code here -
# https://google.github.io/mediapipe/solutions/holistic.html
@@ -43,34 +48,30 @@ class MediapipeSkeletonDetection:
mp_holistic = mp.solutions.holistic
# For webcam input:
- with mp_holistic.Holistic(
- min_detection_confidence=0.5,
- min_tracking_confidence=0.5,
- model_complexity=0,
- ) as holistic:
- # To improve performance, optionally mark the image as not writeable to
- # pass by reference.
- image.flags.writeable = False
- image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
- results = holistic.process(image)
+ # To improve performance, optionally mark the image as not writeable to
+ # pass by reference.
+ image.flags.writeable = False
+ image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
+ results = holistic.process(image)
+
+ # Draw landmark annotation on the image.
+ image.flags.writeable = True
+ image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
+ mp_drawing.draw_landmarks(
+ image,
+ results.face_landmarks,
+ mp_holistic.FACEMESH_CONTOURS,
+ landmark_drawing_spec=None,
+ connection_drawing_spec=mp_drawing_styles.get_default_face_mesh_contours_style(),
+ )
+ mp_drawing.draw_landmarks(
+ image,
+ results.pose_landmarks,
+ mp_holistic.POSE_CONNECTIONS,
+ landmark_drawing_spec=mp_drawing_styles.get_default_pose_landmarks_style(),
+ )
+ return image
- # Draw landmark annotation on the image.
- image.flags.writeable = True
- image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
- mp_drawing.draw_landmarks(
- image,
- results.face_landmarks,
- mp_holistic.FACEMESH_CONTOURS,
- landmark_drawing_spec=None,
- connection_drawing_spec=mp_drawing_styles.get_default_face_mesh_contours_style(),
- )
- mp_drawing.draw_landmarks(
- image,
- results.pose_landmarks,
- mp_holistic.POSE_CONNECTIONS,
- landmark_drawing_spec=mp_drawing_styles.get_default_pose_landmarks_style(),
- )
- # Flip the image horizontally for a selfie-view display.
- # cv2.imshow('MediaPipe Holistic', cv2.flip(image, 1))
- return image
+if __name__ == "__main__":
+ asyncio.run(MediapipeSkeletonDetection().process())
diff --git a/src/config.py b/src/log/config.py
similarity index 100%
rename from src/config.py
rename to src/log/config.py
diff --git a/src/tests/mediapipe_testing.py b/src/tests/mediapipe_testing.py
new file mode 100644
index 00000000..b5d9f1a6
--- /dev/null
+++ b/src/tests/mediapipe_testing.py
@@ -0,0 +1,47 @@
+import cv2
+import mediapipe as mp
+
+mp_drawing = mp.solutions.drawing_utils
+mp_drawing_styles = mp.solutions.drawing_styles
+mp_holistic = mp.solutions.holistic
+
+# For webcam input:
+cap = cv2.VideoCapture(0)
+with mp_holistic.Holistic(
+ min_detection_confidence=0.5, min_tracking_confidence=0.5
+) as holistic:
+ while cap.isOpened():
+ success, image = cap.read()
+ if not success:
+ print("Ignoring empty camera frame.")
+ # If loading a video, use 'break' instead of 'continue'.
+ continue
+
+ # To improve performance, optionally mark the image as not writeable to
+ # pass by reference.
+ image.flags.writeable = False
+ image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
+ results = holistic.process(image)
+
+ # Draw landmark annotation on the image.
+ image.flags.writeable = True
+ image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
+ mp_drawing.draw_landmarks(
+ image,
+ results.face_landmarks,
+ mp_holistic.FACEMESH_CONTOURS,
+ landmark_drawing_spec=None,
+ connection_drawing_spec=mp_drawing_styles.get_default_face_mesh_contours_style(),
+ )
+ mp_drawing.draw_landmarks(
+ image,
+ results.pose_landmarks,
+ mp_holistic.POSE_CONNECTIONS,
+ landmark_drawing_spec=mp_drawing_styles.get_default_pose_landmarks_style(),
+ )
+ # Flip the image horizontally for a selfie-view display.
+ cv2.imshow("MediaPipe Holistic", cv2.flip(image, 1))
+ if cv2.waitKey(5) & 0xFF == 27:
+ break
+
+cap.release()