OpenCV图像合成

OpenCV图像合成

  • 前言
  • 实现步骤
  • 运行结果

前言

这一章节主要讲OpenCV的几个核心操作之图像的算术运算中的图像合成(Image blending)这部分,由于我电脑中opencv是3.4.1的,而程序是在pycharm中安装的4.1.1的package,可能4.4.1的sample运行官网的这个例子可能没有问题,但我这种情况,运行后遇到报错:
dst = cv.addWeighted(img1,0.7,img2,0.3,0)
cv2.error: OpenCV(4.1.1) C:\projects\opencv-python\opencv\modules\core\src\arithm.cpp:663: error: (-209:Sizes of input arguments do not match) The operation is neither ‘array op array’ (where arrays have the same size and the same number of channels), nor ‘array op scalar’, nor ‘scalar op array’ in function ‘cv::arithm_op’
大体意思是输入参数不匹配,图片的像素矩阵需要有同样的尺寸和通道数。所以是用于合成的两张图片的尺寸不一样导致的问题。
因此,此篇博客可以作为自己的经验总结,也可以跟其他遇到同样问题的小伙伴交流,共同进步。
本节官网教程链接

实现步骤

  1. 读入两张图片。这里是根据官网例程导入ml.png和opencv-logo.png。
img1 = cv.imread('ml.png')
img2 = cv.imread('opencv-logo.png')
  1. 打印两张图的shape,并剪裁成一样大小。其实首先需要考虑的就是两张图片的尺寸和通道数是否一致。
print(img1.shape)
print(img2.shape)
img22 = cv.resize(img2,(308,380),interpolation=cv.INTER_CUBIC)
print(img22.shape)

反馈的shape确实不一样。
(380,308,3)
(739,600,3)
把图2的尺寸缩放到跟图1一样。

  1. **完成图片合成,显示结果 **。
dst = cv.addWeighted(img1,0.7,img22,0.3,0)
cv.imshow('dst',dst)
cv.waitKey(0)
cv.destroyAllWindows()

运行结果

OpenCV图像合成_第1张图片

效果实现啦!哈哈!!!

你可能感兴趣的:(OpenCV)