Created
March 7, 2025 17:24
-
-
Save Alexandro1112/59f0f7c647e2ec806b60c1578d3c6f76 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import AVFoundation | |
from Cocoa import NSImage, NSData, NSBitmapImageRep, NSBitmapImageFileTypeJPEG | |
import warnings | |
def extract_frames(video_path, output_dir, frame_rate): | |
if not os.path.exists(output_dir): | |
os.makedirs(output_dir) | |
url = AVFoundation.NSURL.fileURLWithPath_(video_path) | |
asset = AVFoundation.AVAsset.assetWithURL_(url) | |
image_generator = AVFoundation.AVAssetImageGenerator.alloc().initWithAsset_(asset) | |
duration = asset.duration() | |
total_seconds = round(duration.value / duration.timescale) | |
times = [AVFoundation.CMTimeMakeWithSeconds(i, 1) for i in range(0, total_seconds, frame_rate)] | |
for i, time in enumerate(times): | |
warnings.simplefilter('ignore', Warning) | |
img_ref, actual_time = image_generator.copyCGImageAtTime_actualTime_error_(time, None, None) | |
ns_image = NSImage.alloc().initWithCGImage_size_(img_ref, (0, 0)) | |
output_file_path = os.path.join(output_dir, f"frame_{i:03d}.jpg") | |
image_data = ns_image.TIFFRepresentation() | |
jpeg_data = NSBitmapImageRep.imageRepWithData_(image_data).representationUsingType_properties_( | |
NSBitmapImageFileTypeJPEG, None | |
) | |
with open(output_file_path, 'wb+') as f: | |
f.write(jpeg_data.bytes()) | |
if __name__ == "__main__": | |
video_file_path = "/Users/aleksandr/Downloads/doc_2025-03-07_20-15-30.mp4" | |
output_directory = "output_frames_from_video" | |
extract_frames(video_file_path, output_directory, frame_rate=1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment