|
| 1 | +import cv2 |
| 2 | +import os |
| 3 | + |
| 4 | +def extract_thumbnail(video_path, frame_size): |
| 5 | + """ |
| 6 | + Extracts a thumbnail frame from a video and saves it as an image file. |
| 7 | +
|
| 8 | + Args: |
| 9 | + video_path (str): The path to the input video file. |
| 10 | + frame_size (tuple): A tuple containing the desired dimensions (width, height) for the thumbnail frame. |
| 11 | +
|
| 12 | + Raises: |
| 13 | + Exception: If the function fails to extract a frame from the video. |
| 14 | +
|
| 15 | + The function opens the specified video file, seeks to the middle frame, |
| 16 | + resizes the frame to the specified dimensions, and saves it as an image |
| 17 | + file with a filename derived from the video's base name. |
| 18 | +
|
| 19 | + Example: |
| 20 | + extract_thumbnail('my_video.mp4', (320, 240)) |
| 21 | + |
| 22 | + Required Packages: |
| 23 | + cv2 (pip install cv2) |
| 24 | + |
| 25 | + This function is useful for generating thumbnail images from videos. |
| 26 | + """ |
| 27 | + video_capture = cv2.VideoCapture(video_path) # Open the video file for reading |
| 28 | + total_frames = int(video_capture.get(cv2.CAP_PROP_FRAME_COUNT)) # Get the total number of frames in the video |
| 29 | + middle_frame_index = total_frames // 2 # Calculate the index of the middle frame |
| 30 | + video_capture.set(cv2.CAP_PROP_POS_FRAMES, middle_frame_index) # Seek to the middle frame |
| 31 | + success, frame = video_capture.read() # Read the middle frame |
| 32 | + video_capture.release() # Release the video capture object |
| 33 | + |
| 34 | + if success: |
| 35 | + frame = cv2.resize(frame, frame_size) # Resize the frame to the specified dimensions |
| 36 | + thumbnail_filename = f"{os.path.basename(video_path)}_thumbnail.jpg" # Create a filename for the thumbnail |
| 37 | + cv2.imwrite(thumbnail_filename, frame) # Save the thumbnail frame as an image |
| 38 | + else: |
| 39 | + raise Exception("Could not extract frame") # Raise an exception if frame extraction fails |
0 commit comments