如何使用 OpenCV Python 在影像上建立水印?
要向影像新增水印,我們將使用來自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()
輸出
執行上述程式碼後,它將生成以下輸出視窗。
廣告