---
# System prepended metadata

title: OpenCV 基礎篇-惡搞Lena part2
tags: [OpenCV, 影像相加]

---

###### tags: `OpenCV`,`影像相加`
# OpenCV 基礎篇-惡搞Lena part2
**影像加法運算-加號運算子**

![](https://i.imgur.com/njfwLXy.png)

```python=
#圖片相加
import numpy as np
#a+b,a+b<=255
#mod(a+b,256),a+b>255 相加大餘256會計算除256的餘數 
img1=np.random.randint(0,256,size=[3,3],dtype=np.uint8)
#2的8次方=256,無法改成(0,512)
img2=np.random.randint(0,256,size=[3,3],dtype=np.uint8)
print("img1=\n",img1)
print("img2=\n",img2)
print("img1+img2=\n",img1+img2)
```
img1=
 [[229  62 238]
 [184  22  51]
 [ 30 222 116]]
img2=
 [[189 117 119]
 [117 144  47]
 [ 35 193 178]]
img1+img2=
 [[162 179 101]
 [ 45 166  98]
 [ 65 159  38]]
 
 **影像加法運算-cv2.add()**
 
 ![](https://i.imgur.com/4C8rDub.png)
```python=
#cv2.add(像素a,像素b)
#a+b,a+b<=255
#255,a+b>255 如果超過255,只show 255
import numpy as np
img1=np.random.randint(0,256,size=[3,3],dtype=np.uint8)
img2=np.random.randint(0,256,size=[3,3],dtype=np.uint8)
print("img1=\n",img1)
print("img2=\n",img2)
img3=cv2.add(img1,img2)
print("cv2.add(img1,img2)=\n",img3)
```
img1=
 [[136 151 124]
 [113 171 237]
 [107 221 141]]
img2=
 [[ 33 122 251]
 [  1   4  70]
 [ 91 228 178]]
cv2.add(img1,img2)=
 [[169 255 255]
 [114 175 255]
 [198 255 255]]
 
```python=
import cv2
a=cv2.imread("lena.bmp",0)#3通道設0,代表灰階圖片(0-255)
b=a
#兩張相同lena做影像相加
result1=a+b
result2=cv2.add(a,b)
cv2.imshow("original",a)
cv2.imshow("a+b",result1)
cv2.imshow("cv2.add",result2)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
![](https://i.imgur.com/jhVFtkm.png)

**影像加權和**
dst = cv2.addWeighted(src1,alpha,src2,beta,gamma)
dst = saturate(src1xalpha+src2xbeta+gamma)
src1必須跟src2大小、類型相同
```python=
import cv2
import numpy as np
img1=np.ones((3,4),dtype=np.uint8)*100
img2=np.ones((3,4),dtype=np.uint8)*10
gamma=3
img3=cv2.addWeighted(img1,0.6,img2,5,gamma) #alpha=0.6,beta=5
##100*0.6+10*5+3
print("img1=\n",img1)
print("img2=\n",img2)
print("img3=\n",img3)
```
img1=
 [[100 100 100 100]
 [100 100 100 100]
 [100 100 100 100]]
img2=
 [[10 10 10 10]
 [10 10 10 10]
 [10 10 10 10]]
img3=
 [[113 113 113 113]
 [113 113 113 113]
 [113 113 113 113]]
 
**影像加權和-lena+boat**
```python=
#幽靈照片
import cv2
a=cv2.imread("boat.bmp")
b=cv2.imread("lena512.bmp")
result=cv2.addWeighted(a,0.6,b,0.4,0)
cv2.imshow("boat",a)
cv2.imshow("lena",b)
cv2.imshow("ghostboat",result)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
![](https://i.imgur.com/EDqbpGR.png)


