如何使用 OpenCV Python 在图像上创建水印?
opencvpythonserver side programmingprogramming
要向图像添加水印,我们将使用 OpenCV 中的 cv2.addWeighted() 函数。您可以使用以下步骤在输入图像上创建水印 -
导入所需的库。在以下所有 Python 示例中,所需的 Python 库都是 OpenCV。确保您已经安装了它。
import cv2
读取我们要应用水印的输入图像并读取水印图像。
img = cv2.imread("panda.jpg") wm = cv2.imread("watermark.jpg")
访问输入图像的高度和宽度,以及水印图像的高度和宽度。
h_img, w_img = img.shape[:2] h_wm, w_wm = wm.shape[:2]
计算图像中心的坐标。我们将把水印放在中心。
center_x = int(w_img/2) center_y = int(h_img/2)
从顶部、底部、右侧和左侧计算 roi。
top_y = center_y - int(h_wm/2) left_x = center_x - int(w_wm/2) bottom_y = top_y + h_wm right_x = left_x + w_wm
将水印添加到输入图像。
roi = img[top_y:bottom_y, left_x:right_x] result = cv2.addWeighted(roi, 1, wm, 0.3, 0) img[top_y:bottom_y, left_x:right_x] = result
显示带水印的图片。为了显示图像,我们使用 cv2.imshow() 函数。
cv2.imshow("Watermarked Image", img) cv2.waitKey(0) cv2.destroyAllWindows()
为了更好地理解,让我们看看下面的例子。
我们将使用以下图像作为此程序中的输入文件 -
示例
在此 Python 程序中,我们为输入图像添加了水印。
# import required libraries import cv2 # Read the image on which we are going to apply watermark img = cv2.imread("panda.jpg") # Read the watermark image wm = cv2.imread("watermark.jpg") # height and width of the watermark image h_wm, w_wm = wm.shape[:2] # height and width of the image h_img, w_img = img.shape[:2] # calculate coordinates of center of image center_x = int(w_img/2) center_y = int(h_img/2) # calculate rio from top, bottom, right and left top_y = center_y - int(h_wm/2) left_x = center_x - int(w_wm/2) bottom_y = top_y + h_wm right_x = left_x + w_wm # add watermark to the image roi = img[top_y:bottom_y, left_x:right_x] result = cv2.addWeighted(roi, 1, wm, 0.3, 0) img[top_y:bottom_y, left_x:right_x] = result # display watermarked image cv2.imshow("Watermarked Image", img) cv2.waitKey(0) cv2.destroyAllWindows()
输出
执行上述代码后,将产生以下输出窗口。