|
- import cv2
- import numpy as np
-
-
- def watermark(src_path, mask_path, alpha=1):
- # 读取原图
- img = src_path
- # 获取原图高和宽度
- h, w = img.shape[0], img.shape[1]
- # 读取LOG
- mask = mask_path
- if w > h:
- rate = int(w * 0.1) / mask.shape[1]
- else:
- rate = int(h * 0.1) / mask.shape[0]
- mask = cv2.resize(mask, None, fx=rate, fy=rate, interpolation=cv2.INTER_NEAREST)
- mask_h, mask_w = mask.shape[0], mask.shape[1]
- mask_channels = cv2.split(mask)
- dst_channels = cv2.split(img)
- b, g, r, a = cv2.split(mask)
-
- # 计算mask在图片的坐标
- ul_points = (int(h * 0.9), int(int(w / 2) - mask_w / 2))
- dr_points = (int(h * 0.9) + mask_h, int(int(w / 2) + mask_w / 2))
- for i in range(3):
- dst_channels[i][ul_points[0]: dr_points[0], ul_points[1]: dr_points[1]] = dst_channels[i][
- ul_points[0]: dr_points[0],
- ul_points[1]: dr_points[1]] * (
- 255.0 - a * alpha) / 255
- dst_channels[i][ul_points[0]: dr_points[0], ul_points[1]: dr_points[1]] += np.array(
- mask_channels[i] * (a * alpha / 255), dtype=np.uint8)
- dst_img = cv2.merge(dst_channels)
- # cv2.imwrite(r'd:\1_1.jpg', dst_img)
- return dst_img
-
- import time
- # 导入我们将要使用的logo
- logo = "logo.png"
- img2 = "a.jpg"
- time11 = time.time()
- a = watermark(img2, logo)
- time12 = time.time()
- print(time12-time11)
- cv2.imshow("Watermarked Image", a)
- cv2.imwrite("watermarked.jpg", a)
- cv2.waitKey(100000)
|