#主要内容
Learn several arithmetic operations on images like addition, subtraction, bitwise operations etc.
You will learn these functions : cv2.add(), cv2.addWeighted() etc.
#图像相加
##Image Addition
You can add two images by OpenCV function, cv2.add()
or simply by numpy operation, res = img1 + img2
. Both images should be of same depth and type, or second image can just be a scalar value.
警告 There is a difference between OpenCV addition and Numpy addition. OpenCV addition is a
saturated operation
while Numpy addition is amodulo operation
.
For example, consider below sample:
#图像混合
##Image Blending
This is also image addition, but different weights are given to images so that it gives a feeling of blending or transparency.
##带权加法cv2.addWeighted()
用法
cv2.addWeighted(img1,alpha,img2,beta,gamma)
计算公式
dst = alpha img1 + beta img2 + gamma
alpha: img1的权重
beta: img2的权重
|
|
#按位运算
##Bitwise Operations
This includes bitwise AND, OR, NOT and XOR operations. They will be highly useful while extracting any part of the image (as we will see in coming chapters), defining and working with non-rectangular ROI etc. Below we will see an example on how to change a particular region of an image.
直接看例子吧
I want to put OpenCV logo above an image. If I add two images, it will change color. If I blend it, I get an transparent effect. But I want it to be opaque. If it was a rectangular region, I could use ROI as we did in last chapter. But OpenCV logo is a not a rectangular shape. So you can do it with bitwise operations as below:
##代码原理简介
先将opencv_logo的图像灰度化
再选取一个合适的阈值,用二值化区分出前景与后景,即区分出logo与白色背景,得到mask。
此时logo部分变为黑色(灰度值为0,二进制00000000),背景为白色(灰度值为255,二进制11111111)。
关于二值化可以参考cv2.threshold
desert.jpeg的ROI区域做与操作,整体效果类似于 roi AND roi AND mask
roi AND roi 就是原背景,再AND mask,就是将desert roi中与mask为0处位置一致的像素值置为0。
接下来将mask各像素的颜色值按位取反,原先黑白色做一个调换。利用类似上面的方法将opencv_logo中的白色背景的像素值置为0。
之后将两部分图像合并即可。
|
|
以下分别是mask,前景和后景。
结果
##错误日志
推测是越界
opencv_logo宽度比覆盖图片的宽度大
#参考资料
[1] OpenCV-Python Tutorial:Arithmetic Operations on Images