|
| 1 | +import cv2 |
| 2 | +import numpy as np |
| 3 | + |
| 4 | +def add_watermark(input_video_path, output_video_path, watermark_path, position=(10, 10)): |
| 5 | + video_capture = cv2.VideoCapture(input_video_path) |
| 6 | + watermark = cv2.imread(watermark_path, cv2.IMREAD_UNCHANGED) |
| 7 | + watermark_height, watermark_width, _ = watermark.shape |
| 8 | + frame_width = int(video_capture.get(3)) |
| 9 | + frame_height = int(video_capture.get(4)) |
| 10 | + fourcc = cv2.VideoWriter_fourcc(*'XVID') |
| 11 | + output_video = cv2.VideoWriter(output_video_path, fourcc, 30.0, (frame_width, frame_height)) |
| 12 | + |
| 13 | + while True: |
| 14 | + ret, frame = video_capture.read() |
| 15 | + |
| 16 | + if not ret: |
| 17 | + break |
| 18 | + |
| 19 | + resized_watermark = cv2.resize(watermark, (frame_width // 4, frame_height // 4)) |
| 20 | + roi = frame[position[1]:position[1] + resized_watermark.shape[0], position[0]:position[0] + resized_watermark.shape[1]] |
| 21 | + |
| 22 | + if watermark.shape[2] == 4: |
| 23 | + mask = resized_watermark[:, :, 3] |
| 24 | + mask_inv = cv2.bitwise_not(mask) |
| 25 | + img_bg = cv2.bitwise_and(roi, roi, mask=mask_inv) |
| 26 | + img_fg = cv2.bitwise_and(resized_watermark[:, :, :3], resized_watermark[:, :, :3], mask=mask) |
| 27 | + dst = cv2.add(img_bg, img_fg) |
| 28 | + frame[position[1]:position[1] + resized_watermark.shape[0], position[0]:position[0] + resized_watermark.shape[1]] = dst |
| 29 | + |
| 30 | + else: |
| 31 | + frame[position[1]:position[1] + resized_watermark.shape[0], position[0]:position[0] + resized_watermark.shape[1]] = resized_watermark[:, :, :3] |
| 32 | + |
| 33 | + output_video.write(frame) |
| 34 | + |
| 35 | + video_capture.release() |
| 36 | + output_video.release() |
| 37 | + |
| 38 | + print("Watermark added successfully!") |
| 39 | + |
| 40 | + |
| 41 | +add_watermark('input_video.mp4', 'output_video_with_watermark.mp4', 'watermark.png') |
0 commit comments