圖片上添加標誌水印

我想把 OpenCV 的標誌放到另一幅圖像上。如果我使用加法,顏色會改變,如果使用混合,會得到透明效果,但是我不想要透明。如果他是矩形我可以象上一章那樣使用 ROI。但是他不是矩形。但是我們可以通過下面的按位運算實現:

# -*- coding: utf-8 -*-
"""
Created on Sun Jan 5 20:34:30 2014
@author: duan
"""
import cv2
import numpy as np
# 加載圖像
img1 = cv2.imread('roi.jpg')
img2 = cv2.imread('opencv_logo.png')
# I want to put logo on top-left corner, So I create a ROI
rows,cols,channels = img2.shape
roi = img1[0:rows, 0:cols ]
# Now create a mask of logo and create its inverse mask also
img2gray = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY)
ret, mask = cv2.threshold(img2gray, 175, 255, cv2.THRESH_BINARY)
mask_inv = cv2.bitwise_not(mask)
# Now black-out the area of logo in ROI
# 取 roi 中與 mask 中不爲零的值對應的像素的值,其他值爲 0
# 注意這裏必須有 mask=mask 或者 mask=mask_inv, 其中的 mask= 不能忽略
img1_bg = cv2.bitwise_and(roi,roi,mask = mask)
# 取 roi 中與 mask_inv 中不爲零的值對應的像素的值,其他值爲 0。
# Take only region of logo from logo image.
img2_fg = cv2.bitwise_and(img2,img2,mask = mask_inv)
# Put logo in ROI and modify the main image
dst = cv2.add(img1_bg,img2_fg)
img1[0:rows, 0:cols ] = dst
cv2.imshow('res',img1)
cv2.waitKey(0)
cv2.destroyAllWindows()

這裏寫圖片描述



參考文獻:

OpenCV-Python Tutorials

發佈了37 篇原創文章 · 獲贊 36 · 訪問量 17萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章