Skip to content

Instantly share code, notes, and snippets.

@framp
Last active October 4, 2023 18:30
Show Gist options
  • Save framp/954917fc59743e949f02d46d8eedfd27 to your computer and use it in GitHub Desktop.
Save framp/954917fc59743e949f02d46d8eedfd27 to your computer and use it in GitHub Desktop.
Detect upperbody and crop a video around it (needs a pass of stabilization afterward, experiment with different classifiers)
import cv2
target_cascade = cv2.CascadeClassifier('haarcascade_upperbody.xml')
video_capture = cv2.VideoCapture('your_video.mp4')
fps = int(video_capture.get(cv2.CAP_PROP_FPS))
output_width, output_height = 400, 300
fourcc = cv2.VideoWriter_fourcc(*'XVID')
output_video = cv2.VideoWriter('output_video2.mp4', fourcc, fps, (output_width, output_height))
counter = 0
last_target = None
while True:
print("Frame: " + str(counter))
ret, frame = video_capture.read()
if not ret:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
targets = target_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
target = None
if len(targets) > 0:
target = min(targets, key=lambda rect: rect[1])
last_target = target
else:
target = last_target
print("SKIPPED but RECOVERED")
(x, y, w, h) = target
center_x = x + w // 2
center_y = y + h // 2
crop_x = max(0, center_x - output_width // 2)
crop_y = max(0, center_y - output_height // 2)
crop_x2 = min(frame.shape[1], crop_x + output_width)
crop_y2 = min(frame.shape[0], crop_y + output_height)
cropped_frame = frame[crop_y:crop_y2, crop_x:crop_x2]
cropped_frame = cv2.resize(cropped_frame, (output_width, output_height))
output_video.write(cropped_frame)
counter = counter + 1
video_capture.release()
output_video.release()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment