Skip to content

Instantly share code, notes, and snippets.

@notune
Created January 10, 2024 02:10
Show Gist options
  • Save notune/ba066a147f4d2e0b3cdd583b6f7b8505 to your computer and use it in GitHub Desktop.
Save notune/ba066a147f4d2e0b3cdd583b6f7b8505 to your computer and use it in GitHub Desktop.
Simple Python script to create a heatmap from a video file
import sys
import cv2
import numpy as np
def preprocess_frame(frame):
# Convert to grayscale and apply Gaussian blur
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (21, 21), 0)
return blurred
movie_path = 'video.mp4'
vidcap = cv2.VideoCapture(movie_path)
success, frame = vidcap.read()
if not success:
print('ERROR: Could not read video file', file=sys.stderr)
sys.exit(1)
total_frames = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
processed_frames = 0
prev_frame = preprocess_frame(frame)
activity_map = np.zeros(prev_frame.shape, dtype=np.float32)
while success:
# Preprocess current frame
curr_frame = preprocess_frame(frame)
# Calculate difference and update activity map
frame_diff = cv2.absdiff(prev_frame, curr_frame)
activity_map += frame_diff.astype(np.float32)
prev_frame = curr_frame
success, frame = vidcap.read()
# Update and print progress
processed_frames += 1
progress = (processed_frames / total_frames) * 100
print(f"Progress: {progress:.2f}%")
# Normalize the activity map
activity_map = cv2.normalize(activity_map, None, 0, 255, cv2.NORM_MINMAX)
# Convert to heatmap using a colormap
heatmap = cv2.applyColorMap(activity_map.astype(np.uint8), cv2.COLORMAP_JET)
# Save or display the heatmap
cv2.imwrite('activity_heatmap.jpg', heatmap)
cv2.imshow('Activity Heatmap', heatmap)
cv2.waitKey(0)
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment