python-颜色识别

使用Python来做颜色识别,使用了openCV

import cv2
import numpy as np
import time
class ColorTac(object):
    def colorTacing(self):
        print('-*-COLOR TACKING MODE-*-')
        print('you can input:blue,red,yellow,green,purple.and must input one')
        color = input("Color tracking is ready. Choose one color you want tacking. ")
		#默认识别蓝色
        color_lower = np.array([100, 43, 46])
        color_upper = np.array([124, 255, 255])
        if color == 'blue':
            color_lower = np.array([100, 43, 46])
            color_upper = np.array([124, 255, 255])
        elif color == 'red':
            color_lower = np.array([0, 43, 46])
            color_upper = np.array([10, 255, 255])
        elif color == 'yellow':
            color_lower = np.array([26, 43, 46])
            color_upper = np.array([34, 255, 255])
        elif color == 'green':
            color_lower = np.array([35, 43, 46])
            color_upper = np.array([77, 255, 255])
        elif color == 'purple':
            color_lower = np.array([125, 43, 46])
            color_upper = np.array([155, 255, 255])
        else:
            print("You should input a color to tacking.")
        cap = cv2.VideoCapture(0)
        cap.set(3, 320)
        cap.set(4, 240)
        time_start = time.time()
        while True:
            time_end = time.time()
            if time_end - time_start > 30:
                break
            ret, frame = cap.read()
            frame = cv2.GaussianBlur(frame, (5, 5), 0)
            hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
            mask = cv2.inRange(hsv, color_lower, color_upper)
            # 图像学膨胀腐蚀
            mask = cv2.erode(mask, None, iterations=2)
            mask = cv2.GaussianBlur(mask, (3, 3), 0)
            res = cv2.bitwise_and(frame, frame, mask=mask)
            # 寻找轮廓并绘制轮廓
            cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]

            if len(cnts) > 0:
                # 寻找面积最大的轮廓并画出其最小外接圆
                cnt = max(cnts, key=cv2.contourArea)
                (x, y), radius = cv2.minEnclosingCircle(cnt)
                cv2.circle(frame, (int(x), int(y)), int(radius), (255, 0, 255), 2)
                # 找到物体的位置坐标,获得颜色物体的位置,可以来控制小车的转向
                print(int(x), int(y))
            else:
                pass
            cv2.imshow('frame', frame)
            cv2.imshow('mask', mask)
            cv2.imshow('res', res)
            if cv2.waitKey(5) & 0xFF == 27:
                break
        cap.release()
        cv2.destroyAllWindows()
colortac = ColorTac()
colortac.colorTacing()

测试效果
python-颜色识别_第1张图片
识别绿色
python-颜色识别_第2张图片
输入自己想要识别的颜色即可,也可以拓展颜色就是多添加几个Hsv的色域。

你可能感兴趣的:(OpenCV,Python)