Skip to content

Instantly share code, notes, and snippets.

@tin2tin
Created November 17, 2023 12:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tin2tin/a8c699b0ed13b1862cf49d888798cd7f to your computer and use it in GitHub Desktop.
Save tin2tin/a8c699b0ed13b1862cf49d888798cd7f to your computer and use it in GitHub Desktop.
find frame in video
import cv2
import numpy as np
def find_image_in_video(video_path, image_path):
# Load the video clip
cap = cv2.VideoCapture(video_path)
# Load the image template
template = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
# Get the width and height of the template
template_w, template_h = template.shape[::-1]
frame_number = 0
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
# Convert the frame to grayscale
gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Use template matching to find the image
result = cv2.matchTemplate(gray_frame, template, cv2.TM_CCOEFF_NORMED)
# Set a threshold for template matching results
threshold = 0.8
loc = np.where(result >= threshold)
# Check if a match is found
if loc[0].size > 0:
# The image is found in the current frame
frame_number = int(cap.get(cv2.CAP_PROP_POS_FRAMES))
break
cap.release()
cv2.destroyAllWindows()
return frame_number
# Example usage
video_path = 'your_video.mp4'
image_path = 'your_image_template.png'
frame_number = find_image_in_video(video_path, image_path)
if frame_number:
print(f"The image is first found in frame number: {frame_number}")
else:
print("The image is not found in the video.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment