opencv不规则掩膜
时间: 2023-11-08 18:03:53 浏览: 70
要在OpenCV中创建不规则掩膜,可以使用以下步骤:
1. 创建一个与要处理的图像大小相同的空白掩膜图像。
2. 使用OpenCV的绘图函数(如`cv2.drawContours`)在掩膜图像上绘制不规则区域。
3. 将掩膜图像转换为灰度图像,并使用二值化函数(如`cv2.threshold`)将其转换为二进制掩膜。
4. 将掩膜应用于原始图像,可以使用`cv2.bitwise_and`函数。
下面是一个示例代码:
```python
import cv2
import numpy as np
# 读取图像
image = cv2.imread('image.jpg')
# 创建空白掩膜图像
mask = np.zeros(image.shape[:2], dtype=np.uint8)
# 绘制多边形作为不规则区域
points = np.array([[100, 100], [300, 100], [200, 400]], dtype=np.int32)
cv2.drawContours(mask, [points], 0, (255), -1)
# 将掩膜转换为二进制形式
_, binary_mask = cv2.threshold(mask, 1, 255, cv2.THRESH_BINARY)
# 应用掩膜到原始图像
result = cv2.bitwise_and(image, image, mask=binary_mask)
# 显示结果
cv2.imshow('Masked Image', result)
cv2.waitKey(0)
cv2.destroyAllWindows()
```