#模板匹配完成视频处理 import cv2 as cv from tqdm import tqdm video_path='video.mp4' template_path='template.png' output_path='output.mp4' template = cv.imread(template_path, cv.IMREAD_GRAYSCALE) template_height, template_width = template.shape[:2] cap = cv.VideoCapture(video_path) frame_width = int(cap.get(cv.CAP_PROP_FRAME_WIDTH)) frame_height = int(cap.get(cv.CAP_PROP_FRAME_HEIGHT)) fps = cap.get(cv.CAP_PROP_FPS) total_frames = int(cap.get(cv.CAP_PROP_FRAME_COUNT)) fourcc = cv.VideoWriter_fourcc(*'mp4v') out = cv.VideoWriter(output_path, fourcc, fps, (frame_width, frame_height)) with tqdm(total=total_frames,desc="视频处理中:",unit="帧") as pbar: while True: ret, frame = cap.read() if not ret: break gray_frame = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) result= cv.matchTemplate(gray_frame, template, cv.TM_CCOEFF_NORMED) min_val, max_val, min_loc, max_loc = cv.minMaxLoc(result) threshold = 0.8 if max_val >= threshold: top_left = max_loc bottom_right = (top_left[0] + template_width, top_left[1] + template_height) cv.rectangle(frame, top_left, bottom_right, (0, 0, 255), 2) out.write(frame) pbar.update(1) cap.release() out.release()