opencv图像代数运算代码
时间: 2024-10-18 13:00:36 浏览: 40
在OpenCV中,你可以使用图像代数运算来进行各种复杂的图像处理操作。以下是一些基本的图像数学运算的例子:
1. **加法**(Adding images):
```python
import cv2
import numpy as np
img1 = cv2.imread('image1.jpg', 0) # 读取灰度图像
img2 = cv2.imread('image2.jpg', 0)
result = cv2.add(img1, img2)
cv2.imshow('Addition', result)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
2. **减法**(Subtracting images):
```python
result = cv2.subtract(img1, img2)
cv2.imshow('Subtraction', result)
```
3. **相乘**(Multiplying images):
```python
result = cv2.multiply(img1, img2)
cv2.imshow('Multiplication', result)
```
4. **位运算**(如按位与 `&`, 按位或 `|`, 按位异或 `^`):
```python
mask = np.uint8([[[128, 128, 128]]])
result = cv2.bitwise_and(img1, img2, mask=mask)
cv2.imshow('Bitwise AND', result)
```
5. **阈值操作**(如二值化 `cv2.threshold()`):
```python
ret, thresh = cv2.threshold(img1, 127, 255, cv2.THRESH_BINARY)
cv2.imshow('Threshold Binary', thresh)
```
阅读全文