OpenCV水印保持纵横比不提供相同的输入/输出结果

2024-10-03 19:20:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图水印的图像宽度的百分比的图像,它是部分工作。你知道吗

这是水印在web浏览器和opencv中的外观: enter image description here

你可以看到它去掉了黑色的边框。。。你知道吗

在我的代码中:

  • w代表水印
  • wHwWwD分别代表水印的高度、宽度和深度
  • i代表图像
  • iHiWiD分别代表图像的高度、宽度和深度
  • nwW表示新的水印宽度
  • nwH表示新的水印高度
  • nwD表示新的水印维度

实际代码:

import cv2
import imutils
import numpy as np

# Reading the watermark
w = cv2.imread('input/watermark.png', cv2.IMREAD_UNCHANGED)

# If not doing this hack the watermark loses the alpha channel
(B, G, R, A) = cv2.split(w)
B = cv2.bitwise_and(B, B, mask=A)
G = cv2.bitwise_and(G, G, mask=A)
R = cv2.bitwise_and(R, R, mask=A)
w = cv2.merge([B, G, R, A])

# Getting the width, height, depth for the watermark
(wH, wW, wD) = w.shape

# Reading the image
i = cv2.imread('input/image1920.png')
# Getting the width, height, depth for the image
(iH, iW, iD) = i.shape
# I've read that I had to add a new dimension (I don't know why)
i = np.dstack([i, np.ones((iH, wW), dtype="uint8") * 255])

# 80% of the image Width should be the new widt for the Watermark
nwW = 80 * int(iW) / 100
# Calculating the ratio
ratio = nwW / iW
# Calculating the new watermakr Height based on the ratio
nwH = wH * ratio
# Tuple with the new watermak dimensions
nwD = (int(nwW), int(nwH))
# Resizing the watermark to its new dimensions
resized_w = cv2.resize(w, nwD)

# Creating an overlay
overlay = np.zeros((iH, iW, 4), dtype="uint8")
overlay[iH - int(nwH) - 10:iH - 10, iW - int(nwW) - 10:iW - 10] = resized_w

# Blending the two images
output = i.copy()
cv2.addWeighted(overlay, 1, output, 1, 0, output)

# Showing the results
cv2.imshow("watermark test", resized_w)
cv2.waitKey(0)

Tags: the图像new宽度np代表cv2int