基于Python实现RGB色块分类识别

3 篇文章 0 订阅
2 篇文章 0 订阅

有言在前

是给学弟做工程训练时,我帮着写的色块识别代码,清理库存发现,代码思路很常规的处理,有感兴趣的也别浪费,也算个思路。

Show me the code


import cv2
import numpy as np


def color_classify(srcImg, threshold):
    result = []

    # 定义颜色范围,这里可以根据自己的需求定义
    boundaries = [
         ([0, 43, 46], [10, 255, 255], "Red")
         ([35, 43, 46], [77, 255, 255], "Green"),
         ([100, 43, 46], [124, 255, 255], "Blue")
    ]

    hsv_img = cv2.cvtColor(srcImg, cv2.COLOR_BGR2HSV)  # change to hsv model

    # 遍历颜色范围
    for (lower, upper, color) in boundaries:
        # 由颜色范围创建NumPy数组
        lower = np.array(lower, dtype="uint8")
        upper = np.array(upper, dtype="uint8")

        # get mask
        mask = cv2.inRange(hsv_img, lower, upper)
        mask = cv2.erode(mask, None, iterations=2)
        mask = cv2.dilate(mask, None, iterations=2)
        cv2.imshow('Mask', mask)

        cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
        if len(cnts) > 0:
            c = max(cnts, key=cv2.contourArea)
            ((x, y), radius) = cv2.minEnclosingCircle(c)
            if radius > threshold:
                print("颜色:{0} 半径:{1}".format(color, radius) )
                result.append(color)

    return result


if __name__ == '__main__':

    capture = cv2.VideoCapture(0)  # 0是代表摄像头编号,只有一个的话默认为0

    while True:
        # 调用摄像机
        ref, capframe = capture.read()
        if ref is True:

            #  颜色分类
            color_threshold = 150
            result = color_classify(capframe, color_threshold)
            if len(result) > 0:
                print(result)
                cv2.putText(capframe, result[0], (20, 60), cv2.FONT_HERSHEY_PLAIN, 1, (0, 255, 0))

            cv2.imshow('frame', capframe)
            if cv2.waitKey(15) == 'q':
                break

    capture.release()
    cv2.destroyAllWindows()

 

  • 7
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值