opencv python 识别图片中有几种颜色
时间: 2023-07-30 07:09:19 浏览: 102
要识别一张图片中有几种颜色,可以使用OpenCV和Python。以下是一种实现方法:
1. 读取图像并将其转换为HSV颜色空间。
```python
import cv2
img = cv2.imread('image.jpg')
hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
```
2. 定义颜色范围。在HSV颜色空间中,每种颜色都有一个特定的H(色调),S(饱和度)和V(明度)值。通过调整这些值,可以定义特定颜色的范围。
```python
# 颜色范围
# 红色
lower_red = np.array([0, 100, 100])
upper_red = np.array([10, 255, 255])
lower_red2 = np.array([160, 100, 100])
upper_red2 = np.array([179, 255, 255])
# 绿色
lower_green = np.array([35, 43, 46])
upper_green = np.array([77, 255, 255])
# 蓝色
lower_blue = np.array([100, 43, 46])
upper_blue = np.array([124, 255, 255])
```
3. 使用cv2.inRange()函数将图像中的像素值限制在指定的颜色范围内。这将创建一个蒙版,其中包含指定颜色的像素为白色,其他像素为黑色。
```python
# 红色
mask_red = cv2.inRange(hsv_img, lower_red, upper_red)
mask_red2 = cv2.inRange(hsv_img, lower_red2, upper_red2)
mask_red = cv2.addWeighted(mask_red, 1.0, mask_red2, 1.0, 0.0)
# 绿色
mask_green = cv2.inRange(hsv_img, lower_green, upper_green)
# 蓝色
mask_blue = cv2.inRange(hsv_img, lower_blue, upper_blue)
```
4. 对蒙版应用cv2.bitwise_or()函数,以便将所有颜色的像素组合到一个图像中。
```python
# 通过位或操作将三个蒙版合并成一个图像
mask = cv2.bitwise_or(mask_red, mask_green, mask_blue)
```
5. 使用cv2.findContours()函数查找图像中的轮廓。在此步骤中,可以通过指定轮廓面积的最小值来过滤掉不需要的轮廓。
```python
# 查找轮廓
contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 过滤掉面积较小的轮廓
min_area = 50
contours = [c for c in contours if cv2.contourArea(c) > min_area]
```
6. 最后,可以通过len()函数计算检测到的颜色数量。
```python
# 计算颜色数量
num_colors = len(contours)
print(f'图像中检测到了{num_colors}种颜色。')
```
这就是用OpenCV和Python识别一张图片中有几种颜色的方法。