需要python环境并 安装库:
pip install opencv-python Pillow
[Python] 纯文本查看 复制代码 import cv2
import os
from tkinter import *
from tkinter import filedialog
from PIL import Image, ImageTk
class VideoFrameExtractor:
def __init__(self, master):
self.master = master
self.master.title("视频逐帧截取")
self.video_path = ""
self.cap = None
self.current_frame = 0
self.frames = []
self.label = Label(master)
self.label.pack()
self.btn_load = Button(master, text="加载视频", command=self.load_video)
self.btn_load.pack()
self.btn_next = Button(master, text="下一帧", command=self.next_frame)
self.btn_next.pack()
self.btn_save = Button(master, text="保存当前帧", command=self.save_frame)
self.btn_save.pack()
self.btn_extract = Button(master, text="提取所有帧", command=self.extract_frames)
self.btn_extract.pack()
def load_video(self):
self.video_path = filedialog.askopenfilename(title="选择视频文件", filetypes=[("Video Files", "*.mp4;*.avi;*.mov")])
if self.video_path:
self.cap = cv2.VideoCapture(self.video_path)
self.current_frame = 0
self.frames = []
self.show_frame()
def show_frame(self):
if self.cap is not None:
self.cap.set(cv2.CAP_PROP_POS_FRAMES, self.current_frame)
ret, frame = self.cap.read()
if ret:
self.frames.append(frame)
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
img = Image.fromarray(frame)
img = ImageTk.PhotoImage(img)
self.label.config(image=img)
self.label.image = img
def next_frame(self):
self.current_frame += 1
self.show_frame()
def save_frame(self):
if self.frames:
frame_to_save = self.frames[self.current_frame]
filename = f"frame_{self.current_frame}.jpg"
cv2.imwrite(filename, frame_to_save)
print(f"保存帧: {filename}")
def extract_frames(self):
if self.cap is not None:
frame_count = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
for i in range(frame_count):
self.cap.set(cv2.CAP_PROP_POS_FRAMES, i)
ret, frame = self.cap.read()
if ret:
cv2.imwrite(f"frame_{i}.jpg", frame)
print("所有帧已提取")
if __name__ == "__main__":
root = Tk()
app = VideoFrameExtractor(root)
root.mainloop()
|