图片间的数学运算,如相加、按位运算等
OpenCV函数:cv2.add(), cv2.addWeighted(), cv2.bitwise_and()
图片相加(简单相加,超出就用最大值)
add(src1, src2, dst=None, mask=None, dtype=None)
图像混合(会改变图片的透明度)
addWeighted(src1, alpha, src2, beta, gamma, dst=None, dtype=None)
res = cv2.addWeighted(img, 0.6, img2, 0.4, 0)
dst = α*img1 + β*img2 + γ
alpha:α
beta:β
gamma:γ
α和β都等于1时,就相当于图片相加
按位与
bitwise_and(src1, src2, dst=None, mask=None)
按位或
bitwise_or(src1, src2, dst=None, mask=None)
按位非
bitwise_not(src, dst=None, mask=None)
按位异或
bitwise_xor(src1, src2, dst=None, mask=None)
按位异或加掩膜(掩膜就是得到的结果与掩膜进行位与)
imggray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, mask = cv2.threshold(imggray, 127, 255, cv2.THRESH_BINARY)
res = cv2.bitwise_xor(img,img2,mask=mask)
res2 = cv2.bitwise_xor(img, img2)
mask_inv = cv2.bitwise_not(mask)
# -*-encoding:utf-8-*- import pytesseract from PIL import Image from PIL import ImageFilter from PIL import ImageFont from PIL import ImageDraw import numpy as np from PIL import Image import cv2 def main(): # 颜色空间转换 img = cv2.imread("learn.jpg") img2 = cv2.imread("learn2.jpg") # =================================图片相加(简单相加,超出就用最大值) res = cv2.add(img,img2) # =================================图像混合(会改变图片的透明度) # addWeighted(src1, alpha, src2, beta, gamma, dst=None, dtype=None) # dst = α * img1 + β * img2 + γ # alpha: α # beta: β # gamma: γ # α和β都等于1时,就相当于图片相加 res = cv2.addWeighted(img, 0.6, img2, 0.4, 0) # =================================按位与 # bitwise_and(src1, src2, dst=None, mask=None) res = cv2.bitwise_and(img,img2) # =================================按位或 # bitwise_or(src1, src2, dst=None, mask=None) res = cv2.bitwise_or(img, img2) # =================================按位非 # bitwise_not(src, dst=None, mask=None) res = cv2.bitwise_not(img) # =================================按位异或 # bitwise_xor(src1, src2, dst=None, mask=None) res = cv2.bitwise_xor(img,img2) # =================================按位异或加掩膜(掩膜就是得到的结果与掩膜进行位与) imggray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret, mask = cv2.threshold(imggray, 127, 255, cv2.THRESH_BINARY) res = cv2.bitwise_xor(img,img2,mask=mask) res2 = cv2.bitwise_xor(img, img2) mask_inv = cv2.bitwise_not(mask) cv2.imshow('imggray', imggray) cv2.imshow('mask', mask) cv2.imshow('res', res) cv2.imshow('res2', res2) cv2.imshow('mask_inv', mask_inv) cv2.waitKey(0) if __name__ == '__main__': main()