From 76610168780da38d0e9570bd3fd8113b5d2dfe2a Mon Sep 17 00:00:00 2001 From: phks20 <phks20@inf.ufpr.br> Date: Tue, 13 Jun 2023 18:18:45 -0300 Subject: [PATCH] [add]: motion vectors Signed-off-by: phks20 <phks20@inf.ufpr.br> --- OpenCV Video.ipynb | 67 +++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 64 insertions(+), 3 deletions(-) diff --git a/OpenCV Video.ipynb b/OpenCV Video.ipynb index 1126c4c..8d9ab41 100644 --- a/OpenCV Video.ipynb +++ b/OpenCV Video.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "code", - "execution_count": 2, + "execution_count": 1, "id": "08cba0ce", "metadata": {}, "outputs": [], @@ -220,7 +220,7 @@ }, { "cell_type": "code", - "execution_count": 10, + "execution_count": 5, "id": "2cb380ab", "metadata": {}, "outputs": [], @@ -278,10 +278,71 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 10, "id": "8b3f6f9b", "metadata": {}, "outputs": [], + "source": [ + "import cv2\n", + "import numpy as np\n", + "\n", + "\n", + "cap = cv2.VideoCapture(\"videoplayback.mp4\")\n", + "ret, frame1 = cap.read()\n", + "prvs = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY)\n", + "\n", + "# Define the output video settings\n", + "output_video = cv2.VideoWriter('output_video.mp4',\n", + " cv2.VideoWriter_fourcc(*'mp4v'),\n", + " cap.get(cv2.CAP_PROP_FPS),\n", + " (frame1.shape[1], frame1.shape[0]))\n", + "\n", + "while True:\n", + " ret, frame2 = cap.read()\n", + " if not ret:\n", + " break\n", + "\n", + " next_frame = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY)\n", + "\n", + " flow = cv2.calcOpticalFlowFarneback(prvs, next_frame, None, 0.5, 3, 15, 3, 5, 1.2, 0)\n", + "\n", + " # Compute the magnitude and angle of the optical flow vectors\n", + " mag, ang = cv2.cartToPolar(flow[..., 0], flow[..., 1])\n", + " # Handle NaN or Inf values in mag array\n", + " if np.isnan(mag).any() or np.isinf(mag).any():\n", + " mag = np.nan_to_num(mag)\n", + " # Create a mask image to draw the motion vectors\n", + " mask = np.zeros_like(frame2)\n", + "\n", + " # Set the motion vector display parameters\n", + " arrow_scale = 5\n", + " arrow_color = (0, 255, 0) # Green color\n", + "\n", + " # Draw the motion vectors as arrows on the mask image\n", + " for y in range(0, frame2.shape[0], 10):\n", + " for x in range(0, frame2.shape[1], 10):\n", + " dx = int(flow[y, x, 0])\n", + " dy = int(flow[y, x, 1])\n", + " cv2.arrowedLine(mask, (x, y), (x + dx, y + dy), arrow_color, thickness=1, tipLength=0.5)\n", + "\n", + " # Combine the original frame with the motion vectors mask\n", + " output_frame = cv2.add(frame2, mask)\n", + "\n", + " output_video.write(output_frame)\n", + "\n", + " prvs = next_frame\n", + "\n", + "cap.release()\n", + "output_video.release()\n", + "cv2.destroyAllWindows()\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "26c63bc3", + "metadata": {}, + "outputs": [], "source": [] } ], -- GitLab