action_recognition.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
  2. import argparse
  3. import time
  4. from collections import defaultdict
  5. from typing import List, Optional, Tuple
  6. from urllib.parse import urlparse
  7. import cv2
  8. import numpy as np
  9. import torch
  10. from transformers import AutoModel, AutoProcessor
  11. from ultralytics import YOLO
  12. from ultralytics.data.loaders import get_best_youtube_url
  13. from ultralytics.utils.plotting import Annotator
  14. from ultralytics.utils.torch_utils import select_device
  15. class TorchVisionVideoClassifier:
  16. """Classifies videos using pretrained TorchVision models; see https://pytorch.org/vision/stable/."""
  17. from torchvision.models.video import (
  18. MViT_V1_B_Weights,
  19. MViT_V2_S_Weights,
  20. R3D_18_Weights,
  21. S3D_Weights,
  22. Swin3D_B_Weights,
  23. Swin3D_T_Weights,
  24. mvit_v1_b,
  25. mvit_v2_s,
  26. r3d_18,
  27. s3d,
  28. swin3d_b,
  29. swin3d_t,
  30. )
  31. model_name_to_model_and_weights = {
  32. "s3d": (s3d, S3D_Weights.DEFAULT),
  33. "r3d_18": (r3d_18, R3D_18_Weights.DEFAULT),
  34. "swin3d_t": (swin3d_t, Swin3D_T_Weights.DEFAULT),
  35. "swin3d_b": (swin3d_b, Swin3D_B_Weights.DEFAULT),
  36. "mvit_v1_b": (mvit_v1_b, MViT_V1_B_Weights.DEFAULT),
  37. "mvit_v2_s": (mvit_v2_s, MViT_V2_S_Weights.DEFAULT),
  38. }
  39. def __init__(self, model_name: str, device: str or torch.device = ""):
  40. """
  41. Initialize the VideoClassifier with the specified model name and device.
  42. Args:
  43. model_name (str): The name of the model to use.
  44. device (str or torch.device, optional): The device to run the model on. Defaults to "".
  45. Raises:
  46. ValueError: If an invalid model name is provided.
  47. """
  48. if model_name not in self.model_name_to_model_and_weights:
  49. raise ValueError(f"Invalid model name '{model_name}'. Available models: {self.available_model_names()}")
  50. model, self.weights = self.model_name_to_model_and_weights[model_name]
  51. self.device = select_device(device)
  52. self.model = model(weights=self.weights).to(self.device).eval()
  53. @staticmethod
  54. def available_model_names() -> List[str]:
  55. """
  56. Get the list of available model names.
  57. Returns:
  58. list: List of available model names.
  59. """
  60. return list(TorchVisionVideoClassifier.model_name_to_model_and_weights.keys())
  61. def preprocess_crops_for_video_cls(self, crops: List[np.ndarray], input_size: list = None) -> torch.Tensor:
  62. """
  63. Preprocess a list of crops for video classification.
  64. Args:
  65. crops (List[np.ndarray]): List of crops to preprocess. Each crop should have dimensions (H, W, C)
  66. input_size (tuple, optional): The target input size for the model. Defaults to (224, 224).
  67. Returns:
  68. torch.Tensor: Preprocessed crops as a tensor with dimensions (1, T, C, H, W).
  69. """
  70. if input_size is None:
  71. input_size = [224, 224]
  72. from torchvision.transforms import v2
  73. transform = v2.Compose(
  74. [
  75. v2.ToDtype(torch.float32, scale=True),
  76. v2.Resize(input_size, antialias=True),
  77. v2.Normalize(mean=self.weights.transforms().mean, std=self.weights.transforms().std),
  78. ]
  79. )
  80. processed_crops = [transform(torch.from_numpy(crop).permute(2, 0, 1)) for crop in crops]
  81. return torch.stack(processed_crops).unsqueeze(0).permute(0, 2, 1, 3, 4).to(self.device)
  82. def __call__(self, sequences: torch.Tensor):
  83. """
  84. Perform inference on the given sequences.
  85. Args:
  86. sequences (torch.Tensor): The input sequences for the model. The expected input dimensions are
  87. (B, T, C, H, W) for batched video frames or (T, C, H, W) for single video frames.
  88. Returns:
  89. torch.Tensor: The model's output.
  90. """
  91. with torch.inference_mode():
  92. return self.model(sequences)
  93. def postprocess(self, outputs: torch.Tensor) -> Tuple[List[str], List[float]]:
  94. """
  95. Postprocess the model's batch output.
  96. Args:
  97. outputs (torch.Tensor): The model's output.
  98. Returns:
  99. List[str]: The predicted labels.
  100. List[float]: The predicted confidences.
  101. """
  102. pred_labels = []
  103. pred_confs = []
  104. for output in outputs:
  105. pred_class = output.argmax(0).item()
  106. pred_label = self.weights.meta["categories"][pred_class]
  107. pred_labels.append(pred_label)
  108. pred_conf = output.softmax(0)[pred_class].item()
  109. pred_confs.append(pred_conf)
  110. return pred_labels, pred_confs
  111. class HuggingFaceVideoClassifier:
  112. """Zero-shot video classifier using Hugging Face models for various devices."""
  113. def __init__(
  114. self,
  115. labels: List[str],
  116. model_name: str = "microsoft/xclip-base-patch16-zero-shot",
  117. device: str or torch.device = "",
  118. fp16: bool = False,
  119. ):
  120. """
  121. Initialize the HuggingFaceVideoClassifier with the specified model name.
  122. Args:
  123. labels (List[str]): List of labels for zero-shot classification.
  124. model_name (str): The name of the model to use. Defaults to "microsoft/xclip-base-patch16-zero-shot".
  125. device (str or torch.device, optional): The device to run the model on. Defaults to "".
  126. fp16 (bool, optional): Whether to use FP16 for inference. Defaults to False.
  127. """
  128. self.fp16 = fp16
  129. self.labels = labels
  130. self.device = select_device(device)
  131. self.processor = AutoProcessor.from_pretrained(model_name)
  132. model = AutoModel.from_pretrained(model_name).to(self.device)
  133. if fp16:
  134. model = model.half()
  135. self.model = model.eval()
  136. def preprocess_crops_for_video_cls(self, crops: List[np.ndarray], input_size: list = None) -> torch.Tensor:
  137. """
  138. Preprocess a list of crops for video classification.
  139. Args:
  140. crops (List[np.ndarray]): List of crops to preprocess. Each crop should have dimensions (H, W, C)
  141. input_size (tuple, optional): The target input size for the model. Defaults to (224, 224).
  142. Returns:
  143. torch.Tensor: Preprocessed crops as a tensor (1, T, C, H, W).
  144. """
  145. if input_size is None:
  146. input_size = [224, 224]
  147. from torchvision import transforms
  148. transform = transforms.Compose(
  149. [
  150. transforms.Lambda(lambda x: x.float() / 255.0),
  151. transforms.Resize(input_size),
  152. transforms.Normalize(
  153. mean=self.processor.image_processor.image_mean, std=self.processor.image_processor.image_std
  154. ),
  155. ]
  156. )
  157. processed_crops = [transform(torch.from_numpy(crop).permute(2, 0, 1)) for crop in crops] # (T, C, H, W)
  158. output = torch.stack(processed_crops).unsqueeze(0).to(self.device) # (1, T, C, H, W)
  159. if self.fp16:
  160. output = output.half()
  161. return output
  162. def __call__(self, sequences: torch.Tensor) -> torch.Tensor:
  163. """
  164. Perform inference on the given sequences.
  165. Args:
  166. sequences (torch.Tensor): The input sequences for the model. Batched video frames with shape (B, T, H, W, C).
  167. Returns:
  168. torch.Tensor: The model's output.
  169. """
  170. input_ids = self.processor(text=self.labels, return_tensors="pt", padding=True)["input_ids"].to(self.device)
  171. inputs = {"pixel_values": sequences, "input_ids": input_ids}
  172. with torch.inference_mode():
  173. outputs = self.model(**inputs)
  174. return outputs.logits_per_video
  175. def postprocess(self, outputs: torch.Tensor) -> Tuple[List[List[str]], List[List[float]]]:
  176. """
  177. Postprocess the model's batch output.
  178. Args:
  179. outputs (torch.Tensor): The model's output.
  180. Returns:
  181. List[List[str]]: The predicted top3 labels.
  182. List[List[float]]: The predicted top3 confidences.
  183. """
  184. pred_labels = []
  185. pred_confs = []
  186. with torch.no_grad():
  187. logits_per_video = outputs # Assuming outputs is already the logits tensor
  188. probs = logits_per_video.softmax(dim=-1) # Use softmax to convert logits to probabilities
  189. for prob in probs:
  190. top2_indices = prob.topk(2).indices.tolist()
  191. top2_labels = [self.labels[idx] for idx in top2_indices]
  192. top2_confs = prob[top2_indices].tolist()
  193. pred_labels.append(top2_labels)
  194. pred_confs.append(top2_confs)
  195. return pred_labels, pred_confs
  196. def crop_and_pad(frame, box, margin_percent):
  197. """Crop box with margin and take square crop from frame."""
  198. x1, y1, x2, y2 = map(int, box)
  199. w, h = x2 - x1, y2 - y1
  200. # Add margin
  201. margin_x, margin_y = int(w * margin_percent / 100), int(h * margin_percent / 100)
  202. x1, y1 = max(0, x1 - margin_x), max(0, y1 - margin_y)
  203. x2, y2 = min(frame.shape[1], x2 + margin_x), min(frame.shape[0], y2 + margin_y)
  204. # Take square crop from frame
  205. size = max(y2 - y1, x2 - x1)
  206. center_y, center_x = (y1 + y2) // 2, (x1 + x2) // 2
  207. half_size = size // 2
  208. square_crop = frame[
  209. max(0, center_y - half_size) : min(frame.shape[0], center_y + half_size),
  210. max(0, center_x - half_size) : min(frame.shape[1], center_x + half_size),
  211. ]
  212. return cv2.resize(square_crop, (224, 224), interpolation=cv2.INTER_LINEAR)
  213. def run(
  214. weights: str = "yolo11n.pt",
  215. device: str = "",
  216. source: str = "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
  217. output_path: Optional[str] = None,
  218. crop_margin_percentage: int = 10,
  219. num_video_sequence_samples: int = 8,
  220. skip_frame: int = 2,
  221. video_cls_overlap_ratio: float = 0.25,
  222. fp16: bool = False,
  223. video_classifier_model: str = "microsoft/xclip-base-patch32",
  224. labels: List[str] = None,
  225. ) -> None:
  226. """
  227. Run action recognition on a video source using YOLO for object detection and a video classifier.
  228. Args:
  229. weights (str): Path to the YOLO model weights. Defaults to "yolo11n.pt".
  230. device (str): Device to run the model on. Use 'cuda' for NVIDIA GPU, 'mps' for Apple Silicon, or 'cpu'. Defaults to auto-detection.
  231. source (str): Path to mp4 video file or YouTube URL. Defaults to a sample YouTube video.
  232. output_path (Optional[str], optional): Path to save the output video. Defaults to None.
  233. crop_margin_percentage (int, optional): Percentage of margin to add around detected objects. Defaults to 10.
  234. num_video_sequence_samples (int, optional): Number of video frames to use for classification. Defaults to 8.
  235. skip_frame (int, optional): Number of frames to skip between detections. Defaults to 4.
  236. video_cls_overlap_ratio (float, optional): Overlap ratio between video sequences. Defaults to 0.25.
  237. fp16 (bool, optional): Whether to use half-precision floating point. Defaults to False.
  238. video_classifier_model (str, optional): Name or path of the video classifier model. Defaults to "microsoft/xclip-base-patch32".
  239. labels (List[str], optional): List of labels for zero-shot classification. Defaults to predefined list.
  240. Returns:
  241. None</edit>
  242. """
  243. if labels is None:
  244. labels = [
  245. "walking",
  246. "running",
  247. "brushing teeth",
  248. "looking into phone",
  249. "weight lifting",
  250. "cooking",
  251. "sitting",
  252. ]
  253. # Initialize models and device
  254. device = select_device(device)
  255. yolo_model = YOLO(weights).to(device)
  256. if video_classifier_model in TorchVisionVideoClassifier.available_model_names():
  257. print("'fp16' is not supported for TorchVisionVideoClassifier. Setting fp16 to False.")
  258. print(
  259. "'labels' is not used for TorchVisionVideoClassifier. Ignoring the provided labels and using Kinetics-400 labels."
  260. )
  261. video_classifier = TorchVisionVideoClassifier(video_classifier_model, device=device)
  262. else:
  263. video_classifier = HuggingFaceVideoClassifier(
  264. labels, model_name=video_classifier_model, device=device, fp16=fp16
  265. )
  266. # Initialize video capture
  267. if source.startswith("http") and urlparse(source).hostname in {"www.youtube.com", "youtube.com", "youtu.be"}:
  268. source = get_best_youtube_url(source)
  269. elif not source.endswith(".mp4"):
  270. raise ValueError("Invalid source. Supported sources are YouTube URLs and MP4 files.")
  271. cap = cv2.VideoCapture(source)
  272. # Get video properties
  273. frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
  274. frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
  275. fps = cap.get(cv2.CAP_PROP_FPS)
  276. # Initialize VideoWriter
  277. if output_path is not None:
  278. fourcc = cv2.VideoWriter_fourcc(*"mp4v")
  279. out = cv2.VideoWriter(output_path, fourcc, fps, (frame_width, frame_height))
  280. # Initialize track history
  281. track_history = defaultdict(list)
  282. frame_counter = 0
  283. track_ids_to_infer = []
  284. crops_to_infer = []
  285. pred_labels = []
  286. pred_confs = []
  287. while cap.isOpened():
  288. success, frame = cap.read()
  289. if not success:
  290. break
  291. frame_counter += 1
  292. # Run YOLO tracking
  293. results = yolo_model.track(frame, persist=True, classes=[0]) # Track only person class
  294. if results[0].boxes.id is not None:
  295. boxes = results[0].boxes.xyxy.cpu().numpy()
  296. track_ids = results[0].boxes.id.cpu().numpy()
  297. # Visualize prediction
  298. annotator = Annotator(frame, line_width=3, font_size=10, pil=False)
  299. if frame_counter % skip_frame == 0:
  300. crops_to_infer = []
  301. track_ids_to_infer = []
  302. for box, track_id in zip(boxes, track_ids):
  303. if frame_counter % skip_frame == 0:
  304. crop = crop_and_pad(frame, box, crop_margin_percentage)
  305. track_history[track_id].append(crop)
  306. if len(track_history[track_id]) > num_video_sequence_samples:
  307. track_history[track_id].pop(0)
  308. if len(track_history[track_id]) == num_video_sequence_samples and frame_counter % skip_frame == 0:
  309. start_time = time.time()
  310. crops = video_classifier.preprocess_crops_for_video_cls(track_history[track_id])
  311. end_time = time.time()
  312. preprocess_time = end_time - start_time
  313. print(f"video cls preprocess time: {preprocess_time:.4f} seconds")
  314. crops_to_infer.append(crops)
  315. track_ids_to_infer.append(track_id)
  316. if crops_to_infer and (
  317. not pred_labels
  318. or frame_counter % int(num_video_sequence_samples * skip_frame * (1 - video_cls_overlap_ratio)) == 0
  319. ):
  320. crops_batch = torch.cat(crops_to_infer, dim=0)
  321. start_inference_time = time.time()
  322. output_batch = video_classifier(crops_batch)
  323. end_inference_time = time.time()
  324. inference_time = end_inference_time - start_inference_time
  325. print(f"video cls inference time: {inference_time:.4f} seconds")
  326. pred_labels, pred_confs = video_classifier.postprocess(output_batch)
  327. if track_ids_to_infer and crops_to_infer:
  328. for box, track_id, pred_label, pred_conf in zip(boxes, track_ids_to_infer, pred_labels, pred_confs):
  329. top2_preds = sorted(zip(pred_label, pred_conf), key=lambda x: x[1], reverse=True)
  330. label_text = " | ".join([f"{label} ({conf:.2f})" for label, conf in top2_preds])
  331. annotator.box_label(box, label_text, color=(0, 0, 255))
  332. # Write the annotated frame to the output video
  333. if output_path is not None:
  334. out.write(frame)
  335. # Display the annotated frame
  336. cv2.imshow("YOLOv8 Tracking with S3D Classification", frame)
  337. if cv2.waitKey(1) & 0xFF == ord("q"):
  338. break
  339. cap.release()
  340. if output_path is not None:
  341. out.release()
  342. cv2.destroyAllWindows()
  343. def parse_opt():
  344. """Parse command line arguments."""
  345. parser = argparse.ArgumentParser()
  346. parser.add_argument("--weights", type=str, default="yolo11n.pt", help="ultralytics detector model path")
  347. parser.add_argument("--device", default="", help='cuda device, i.e. 0 or 0,1,2,3 or cpu/mps, "" for auto-detection')
  348. parser.add_argument(
  349. "--source",
  350. type=str,
  351. default="https://www.youtube.com/watch?v=dQw4w9WgXcQ",
  352. help="video file path or youtube URL",
  353. )
  354. parser.add_argument("--output-path", type=str, default="output_video.mp4", help="output video file path")
  355. parser.add_argument(
  356. "--crop-margin-percentage", type=int, default=10, help="percentage of margin to add around detected objects"
  357. )
  358. parser.add_argument(
  359. "--num-video-sequence-samples", type=int, default=8, help="number of video frames to use for classification"
  360. )
  361. parser.add_argument("--skip-frame", type=int, default=2, help="number of frames to skip between detections")
  362. parser.add_argument(
  363. "--video-cls-overlap-ratio", type=float, default=0.25, help="overlap ratio between video sequences"
  364. )
  365. parser.add_argument("--fp16", action="store_true", help="use FP16 for inference")
  366. parser.add_argument(
  367. "--video-classifier-model", type=str, default="microsoft/xclip-base-patch32", help="video classifier model name"
  368. )
  369. parser.add_argument(
  370. "--labels",
  371. nargs="+",
  372. type=str,
  373. default=["dancing", "singing a song"],
  374. help="labels for zero-shot video classification",
  375. )
  376. return parser.parse_args()
  377. def main(opt):
  378. """Main function."""
  379. run(**vars(opt))
  380. if __name__ == "__main__":
  381. opt = parse_opt()
  382. main(opt)