Sure, I can help you create a Jupyter Notebook for video object tracking using OpenCV that will:
- Load a video from a URL.
- Capture the first frame.
- Display it so you can specify the point to track manually in the code (since Kaggle does not support interactive input).
- Track that selected point using an optical flow or tracking method.
- Center the video frame around the tracked point.
- Fill missing parts (due to shifting) with a gray value (127).
- Create an accompanying mask where:
- White (
255) indicates missing (filled area).
- Black (
0) indicates original content.
✅ Step-by-step plan:
Step 1: Download the video from a given URL (e.g., using requests or gdown).
Step 2: Load the video using OpenCV.
Step 3: Extract the first frame, and show it so the user can pick coordinates.
Step 4: Add variables for the selected point (x, y) manually in code.
Step 5: Use optical flow (Lucas-Kanade) or tracker (like cv2.TrackerKCF_create) to follow the point.
Step 6: Shift the frame so that the tracked point ends up in the center.
Step 7: Fill the borders created by the shift with 127 and generate a binary mask.
🧪 Sample Notebook Content (for Kaggle)
Here's a minimal runnable demo that you can paste into a Kaggle notebook.
(Note: Use a direct video URL or upload the file to Kaggle.)
🚀 Upload/Download Video First
# If using a direct URL to the video:
import requests
video_url = "https://example.com/path_to_video.mp4" # replace this
video_path = "video.mp4"
# Download the video
with open(video_path, 'wb') as f:
f.write(requests.get(video_url).content)
📤 Load the First Frame and Pick Tracking Point
import cv2
import matplotlib.pyplot as plt
# Load video
cap = cv2.VideoCapture("video.mp4")
ret, first_frame = cap.read()
cap.release()
if not ret:
raise ValueError("Cannot read video file")
# Convert to RGB for display in matplotlib
frame_rgb = cv2.cvtColor(first_frame, cv2.COLOR_BGR2RGB)
plt.figure(figsize=(10, 6))
plt.imshow(frame_rgb)
plt.title("Manually choose a point to track and update (x, y) in code")
plt.axis('on')
plt.show()
# ==== USER INPUT HERE ====
# Replace this with the coordinates you choose from the plot
tracking_point = (250, 200) # <-- You must update this based on the above image
print(f"Tracking starting point: {tracking_point}")
🧭 Track and Center Point Across Frames
import numpy as np
import cv2
import os
# Reload the video
cap = cv2.VideoCapture("video.mp4")
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
center = (width // 2, height // 2)
# Lucas-Kanade optical flow setup
lk_params = dict(winSize=(15, 15), maxLevel=2,
criteria=(cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))
# Convert first frame to gray and set the initial point
ret, old_frame = cap.read()
old_gray = cv2.cvtColor(old_frame, cv2.COLOR_BGR2GRAY)
p0 = np.array([[tracking_point]], dtype=np.float32)
# Outputs
output_frames = []
mask_frames = []
while True:
ret, frame = cap.read()
if not ret:
break
frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Calculate optical flow
p1, st, err = cv2.calcOpticalFlowPyrLK(old_gray, frame_gray, p0, None, **lk_params)
if st[0][0] != 1: # tracking failed
break
tracked_point = p1[0][0]
dx = int(center[0] - tracked_point[0])
dy = int(center[1] - tracked_point[1])
# Apply affine transform for shifting
M = np.float32([[1, 0, dx], [0, 1, dy]])
shifted_frame = cv2.warpAffine(frame, M, (width, height), borderValue=(127, 127, 127))
# Generate mask: 0 where original image exists, 255 where padding happened
original_mask = np.ones((height, width), dtype=np.uint8) * 255
shifted_mask = cv2.warpAffine(original_mask, M, (width, height), borderValue=0)
output_frames.append(shifted_frame)
mask_frames.append(shifted_mask)
old_gray = frame_gray.copy()
p0 = p1.reshape(-1, 1, 2)
💾 Save Output Video and Mask
# Optional: write video and mask output
out_video = cv2.VideoWriter("tracked_output.mp4",
cv2.VideoWriter_fourcc(*'mp4v'), 30, (width, height))
mask_video = cv2.VideoWriter("mask_output.mp4",
cv2.VideoWriter_fourcc(*'mp4v'), 30, (width, height), isColor=False)
for f, m in zip(output_frames, mask_frames):
out_video.write(f)
mask_video.write(m)
out_video.release()
mask_video.release()
cap.release()
print("Output videos saved.")
✅ Result
Uploaded output:
tracked_output.mp4: Your original video with the tracked point always centered.
mask_output.mp4: A binary mask where the filled parts are white.
▶️ Summary
- Replace the URL with your video.
- Choose a coordinate in the first displayed frame.
- Update
tracking_point = (x, y) in the notebook manually.
- The script performs tracking and produces centered frames with filled edges and masks.
Would you like me to pack this as a .ipynb file for upload directly to Kaggle?