# 2.2. 图像的算术运算¶

## 2.2.1. 目标¶

• 学习一些图像上的算术运算，如加法、减法、按位运算等。

## 2.2.2. 图像加法¶

Note

OpenCV加法和Numpy加法有区别。OpenCV加法是饱和运算，Numpy加法是模运算。

>>> import cv2
>>> import numpy as np
>>>
>>> x = np.uint8([250])
>>> y = np.uint8([10])

>>> cv2.add(x,y) # 250+10 = 260 => 255

array([[255]], dtype=uint8)

>>> x+y          # 250+10 = 260 % 256 = 4

array([4], dtype=uint8)


## 2.2.3. 图像混合¶

$g（x）=（1-alpha）f{0}（x）+alpha f{1}（x）$

$dst=alphacdot img1+betacdot img2+gamma$

>>> img1 = cv2.imread('/cvdata/ml.png')

>>> img2 = cv2.imread('/cvdata/opencv_logo.png')

>>> import cv2 as cv

>>> img1 = cv.imread('/cvdata/ml.png')

>>> img1.shape

(380, 308, 3)

>>> img2.shape

(739, 600, 3)

>>> dst = cv.addWeighted(img1,0.3,img1,0.3,0)

>>> %matplotlib inline
>>>
>>> import  matplotlib.pyplot as plt
>>> plt.imshow(dst)

<matplotlib.image.AxesImage at 0x7ff98cf73748>

>>> # dst = cv2.addWeighted(img1,0.3,img2,0.3,8)

>>> # plt.imshow(dst)

>>> # cv2.imshow('dst',dst)
>>> # cv2.waitKey(0)
>>> # cv2.destroyAllWindows()


## 2.2.4. 按位运算¶

>>> # Load two images
>>>
>>>
>>>
>>>
>>> # 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, 10, 255, cv2.THRESH_BINARY)
>>>
>>> # Now black-out the area of logo in ROI
>>>
>>> # Take only region of logo from logo image.
>>>
>>> # Put logo in ROI and modify the main image
>>> img1[0:rows, 0:cols ] = dst

>>> plt.imshow(img1)

<matplotlib.image.AxesImage at 0x7ff98cf0fbe0>

>>> cv2.imwrite('xx_a.jpg', img1)

True


>>> from IPython.display import Image

>>> Image('/cvdata/opencv-logo-white.png')

>>> # cv2.imshow('res',img1)
>>> # cv2.waitKey(0)
>>> # cv2.destroyAllWindows()


## 2.2.6. 练习¶

1. 使用 cv2.addWeighted 函数在文件夹中创建图像的幻灯片放映