此处参考引用到知乎博文 - python openCV掩膜的通俗理解
https://zhuanlan.zhihu.com/p/36656952
Image Addtion
使用cv2.add()将两幅图像进行加法运算,也可以直接使用numpy,res=img1+img2.两幅图像的大小,类型必须一致,或者第二个图像可以是一个简单的标量值。openCV的加法是一种饱和操作,而numpy的加法是一种模操作。OpenCV的结果会更好,尽量使用OpenCV中的函数
add = cv2.add(img1,img2)
Image Blending
也是加法,不同的是两幅图像的权重不同,这会给人一种混合或者透明的感觉。
weighted = cv2.addWeighted(img1, 0.6, img2, 0.4, 0)
Bitwise Operations
cv2.threshold (src, thresh, maxval, type). First argument is the source image, which should be a grayscale image. Second argument is the threshold value which is used to classify the pixel values. Third argument is the maxVal which represents the value to be given if pixel value is more than (sometimes less than) the threshold value, 填充色. Forth argument is styles of thresholding. They are cv.THRESH_BINARY, cv.THRESH_BINARY_INV, cv.THRESH_TRUNC, cv.THRESH_TOZERO, cv. THRESH_TOZERO_INV
threshold(src, thresh, maxval, type[, dst])->ret,dst
src::灰度图
thresh:阈值
maxval:最大值
type:阈值类型
- key point! The pixel of black area is 0, therefore, add operation wouldn't change color of areas adding with black areas.
import cv2
import numpy as np
img1 = cv2.imread('jiemi.jpg')
img2 = cv2.imread('logo.jpg')
#引入两个图片,第二个是logo
r1,c1,ch1 = img1.shape
r2,c2,ch2 = img2.shape
roi = img1[r1-r2:r1, c1-c2:c1 ]
#设定jiemi图的roi,注意:对roi的操作就是对img1的操作
gray = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY)
#得到灰度图
ret, ma1 = cv2.threshold(gray, 170, 255, cv2.THRESH_BINARY)
fg1 = cv2.bitwise_and(roi,roi,mask=ma1)
#ma1是黑化logo,黑的地方可以通过bitwise_and把其他黑掉,所以ma1是黑roi的
ret, ma2 = cv2.threshold(gray, 170, 255, cv2.THRESH_BINARY_INV)
fg2 = cv2.bitwise_and(img2,img2,mask = ma2)
#ma2是黑化周边,所以ma2是黑logo的
#ma2=cv2.bitwise_not(ma1) 也可以这样对其反转
#roi[:] = cv2.add(fg1, fg2)
#这个写法正确吗?
#这里终于合体了
dst = cv2.add(fg1, fg2)
img1[r1-r2:r1, c1-c2:c1 ] = dst
cv2.imshow('img1',img1)
cv2.waitKey(0)
cv2.destroyAllWindows()