Arithmetic Operations on Images
1图像叠加
可以通过OpenCV函数cv.add()
或简单地通过numpy操作添加两个图像,res = img1 + img2.两个图像应该具有相同的深度和类型,或者第二个图像可以是标量值.
NOTE:
- OpenCV添加是饱和操作,也就是有上限值,而Numpy添加是模运算。
- 添加两个图像时, OpenCV功能将提供更好的结果.所以总是更好地坚持OpenCV功能.
代码:
import cv2
import numpy as np
x = np.uint8([250])
y = np.uint8([10])
print( cv2.add(x,y) ) # 250+10 = 260 => 255
print( x+y ) # 250+10 = 260 % 256 = 4
输出:
[[255]]
[4]
2图像融合
这也是图像加法,但是对图像赋予不同的权重(0到1之间),使得它具有混合感或透明感。
代码:
import cv2
import numpy as np
img1 = cv2.imread('img.jpg')
img2 = cv2.imread('img2.jpg')
img2 = cv2.resize(img2,(480,331))#统一图片大小
dst = cv2.addWeighted(img1,0.5,img2,0.5,0)
cv2.imshow('dst',dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
3按位操作
包括按位AND,OR,NOT和XOR运算.
希望将opencv徽标放在图像上方,如果叠加两个图像,它将改变颜色;如果融合两个图像,会得到一个透明的效果. 我希望它不透明,如果它是一个矩形区域,我可以使用ROI按之前描述的操作,但是opencv徽标并不是矩形,可以按位操作完成相关功能.
代码:
import cv2
import numpy as np
img1 = cv2.imread('img.jpg')
img2 = cv2.imread('img1.jpg')
img2 = cv2.resize(img2,(100,100))
# I want to put logo on top-left corner, So I create a ROI
rows,cols,channels = img2.shape
roi = img1[0:rows, 0:cols ]
# Now create a mask of logo and create its inverse mask also
img2gray = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY)
ret, mask = cv2.threshold(img2gray, 200, 255, cv2.THRESH_BINARY)
mask_inv = cv2.bitwise_not(mask)
# Now black-out the area of logo in ROI
img1_bg = cv2.bitwise_and(roi,roi,mask = mask)
# Take only region of logo from logo image.
img2_fg = cv2.bitwise_and(img2,img2,mask = mask_inv)
# Put logo in ROI and modify the main image
dst = cv2.add(img1_bg,img2_fg)
img1[0:rows, 0:cols ] = dst
cv2.imshow('res',img1)
cv2.waitKey(0)
cv2.destroyAllWindows()