OpenCV学习之图像的叠加与混合详解
双子座断点 人气:0本文是OpenCV图像视觉入门之路的第9篇文章,本文详细的在图像上面进行了图像叠加图像混合等操作。
1.图像叠加
图片叠加一般加入水印用的特别多,比如视频网站、图片素材网等等
import cv2 from PIL import Image, ImageFont, ImageDraw import matplotlib.pyplot as plt import numpy as np from numpy import unicode if __name__ == '__main__': img1 = cv2.imread("D:/Jupyter_Notebooks/0.jpg") # 读取彩色图像(BGR) img2 = cv2.imread("D:/Jupyter_Notebooks/1.3.png") # 读取 CV Logo # 我想把logo放在左上角,所以我创建了ROI rows, cols, channels = img2.shape roi = img1[0:rows, 0:cols] # 现在创建logo的掩码,并同时创建其相反掩码 img2gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY) ret, mask = cv2.threshold(img2gray, 10, 255, cv2.THRESH_BINARY) mask_inv = cv2.bitwise_not(mask) # 现在将ROI中logo的区域涂黑 img1_bg = cv2.bitwise_and(roi, roi, mask=mask_inv) # 仅从logo图像中提取logo区域 img2_fg = cv2.bitwise_and(img2, img2, mask=mask) # 将logo放入ROI并修改主图像 dst = cv2.add(img1_bg, img2_fg) img1[0:rows, 0:cols] = dst cv2.imshow("imgAdd", img1) # 显示叠加图像 imgAdd cv2.waitKey(0) cv2.destroyAllWindows()
2.图像混合
图像的混合:将两幅图像按照不同的比例进行混合 cv2.addWeighted()
import cv2 from PIL import Image, ImageFont, ImageDraw import matplotlib.pyplot as plt import numpy as np from numpy import unicode if __name__ == '__main__': img1 = cv2.imread("D:/Jupyter_Notebooks/1.2.png") # 读取彩色图像(BGR) img2 = cv2.imread("D:/Jupyter_Notebooks/1.3.png") # 读取 CV Logo # 混合后的图片 dst = cv2.addWeighted(img1, 0.7, img2, 0.3, 0) # 图片img1所占比重0.7;图片img2所占比重0.3 cv2.imshow("imgAdd", dst) # 显示叠加图像 dst cv2.waitKey(0) cv2.destroyAllWindows()
需要注意:两张图片尺寸需要一致否则会出异常
加载全部内容