HSV色彩空间颜色提取
2021 年 05 月 25 日 243 137 字 暂无评论

根据HSV分量模型,各种颜色范围分布如下:

  • Hue(色调、色相)
  • Saturation(饱和度、色彩纯净度)
  • Value(明度)

红色的范围为:[0,43,46]~[10,255,255]∪[156,43,46]~[180,255,255]

以下为我代码示例

import cv2
import numpy as np

ball_color1 = 'red'  # 提取的颜色
ball_color2 = 'red2'

color_dist = {'red': {'Lower': np.array([156, 43, 46]), 'Upper': np.array([180, 255, 255])},
              'red2': {'Lower': np.array([0, 43, 46]), 'Upper': np.array([10, 255, 255])},
              'blue': {'Lower': np.array([100, 80, 46]), 'Upper': np.array([124, 255, 255])},
              'green': {'Lower': np.array([35, 43, 35]), 'Upper': np.array([90, 255, 255])},
              }

cap = cv2.VideoCapture(r".\mark\GH010362.mp4")
cv2.namedWindow('camera', cv2.WINDOW_AUTOSIZE)

i = 0;

while cap.isOpened():
    ret, frame = cap.read()
    if ret:
        if frame is not None:
            gs_frame = cv2.GaussianBlur(frame, (5, 5), 0)                     # 高斯模糊
            hsv = cv2.cvtColor(gs_frame, cv2.COLOR_BGR2HSV)                 # 转化成HSV图像
            erode_hsv = cv2.erode(hsv, None, iterations=2)                   # 腐蚀 粗的变细
            mask0 = cv2.inRange(erode_hsv, color_dist[ball_color1]['Lower'], color_dist[ball_color1]['Upper'])
            cv2.imshow('mask0', mask0)
            cv2.imwrite("mask0" + str(i) + ".jpg", mask0)
            mask1 = cv2.inRange(erode_hsv, color_dist[ball_color2]['Lower'], color_dist[ball_color2]['Upper'])
            cv2.imshow('mask1', mask1)
            cv2.imwrite("mask1" + str(i) + ".jpg", mask1)
            inRange_hsv = mask0 + mask1
            cv2.imshow('inRange_hsv', inRange_hsv)
            cv2.imwrite("inRange_hsv" + str(i) + ".jpg", inRange_hsv)
            # cnts = cv2.findContours(inRange_hsv.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
            cnts, hierarchy = cv2.findContours(inRange_hsv, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
            print(len(cnts))

            c = max(cnts, key=cv2.contourArea)
            rect = cv2.minAreaRect(c)
            box = cv2.boxPoints(rect)
            cv2.drawContours(frame, [np.int0(box)], -1, (0, 255, 255), 2)

            cv2.imshow('camera', frame)
            # cv2.imwrite("GH" + str(i) + ".jpg", frame)
            i = i+1
            cv2.waitKey(1)
        else:
            print("无画面")
    else:
        print("无法读取摄像头!")
        break

cap.release()
cv2.waitKey(0)
cv2.destroyAllWindows()

原图:

根据第一个HSV颜色区域获取到轮廓图:

根据第二个HSV颜色区域获取到轮廓图:

两个获取区域合并获得完整红色区域的轮廓:

提取其他颜色可以根据HSV表改。


版权属于:zfh

本文链接:http://121.36.166.89/index.php/archives/226/



评论已关闭