要黑白蓝青绿黄红的占比
时间: 2023-08-03 18:08:40 浏览: 136
好的,以下是一段用于统计图像黑白蓝青绿黄红颜色占比的 OpenCV 代码,具体注释已经在代码中标明:
```python
import cv2
import numpy as np
# 读入图像
img = cv2.imread("your_image_path")
# 将图像转换为 HSV 颜色空间
hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# 定义颜色范围
lower_black = np.array([0, 0, 0])
upper_black = np.array([180, 255, 46])
lower_white = np.array([0, 0, 221])
upper_white = np.array([180, 30, 255])
lower_blue = np.array([100, 50, 50])
upper_blue = np.array([130, 255, 255])
lower_cyan = np.array([80, 50, 50])
upper_cyan = np.array([100, 255, 255])
lower_green = np.array([35, 50, 50])
upper_green = np.array([77, 255, 255])
lower_yellow = np.array([26, 43, 46])
upper_yellow = np.array([34, 255, 255])
lower_red1 = np.array([0, 43, 46])
upper_red1 = np.array([10, 255, 255])
lower_red2 = np.array([156, 43, 46])
upper_red2 = np.array([180, 255, 255])
# 获取颜色区域掩膜
mask_black = cv2.inRange(hsv_img, lower_black, upper_black)
mask_white = cv2.inRange(hsv_img, lower_white, upper_white)
mask_blue = cv2.inRange(hsv_img, lower_blue, upper_blue)
mask_cyan = cv2.inRange(hsv_img, lower_cyan, upper_cyan)
mask_green = cv2.inRange(hsv_img, lower_green, upper_green)
mask_yellow = cv2.inRange(hsv_img, lower_yellow, upper_yellow)
mask_red1 = cv2.inRange(hsv_img, lower_red1, upper_red1)
mask_red2 = cv2.inRange(hsv_img, lower_red2, upper_red2)
mask_red = cv2.bitwise_or(mask_red1, mask_red2)
# 统计颜色像素占比
total_pixels = mask_black.shape[0] * mask_black.shape[1]
black_pixels = np.sum(mask_black == 255)
white_pixels = np.sum(mask_white == 255)
blue_pixels = np.sum(mask_blue == 255)
cyan_pixels = np.sum(mask_cyan == 255)
green_pixels = np.sum(mask_green == 255)
yellow_pixels = np.sum(mask_yellow == 255)
red_pixels = np.sum(mask_red == 255)
black_ratio = black_pixels / total_pixels
white_ratio = white_pixels / total_pixels
blue_ratio = blue_pixels / total_pixels
cyan_ratio = cyan_pixels / total_pixels
green_ratio = green_pixels / total_pixels
yellow_ratio = yellow_pixels / total_pixels
red_ratio = red_pixels / total_pixels
# 输出结果
print("Black Ratio:", black_ratio)
print("White Ratio:", white_ratio)
print("Blue Ratio:", blue_ratio)
print("Cyan Ratio:", cyan_ratio)
print("Green Ratio:", green_ratio)
print("Yellow Ratio:", yellow_ratio)
print("Red Ratio:", red_ratio)
```
需要注意的是,上述代码中的颜色范围是根据颜色在 HSV 颜色空间中的范围定义的,如果需要统计其他颜色,需要调整对应的颜色范围。
阅读全文