树莓派:基于opencv+Python的颜色形状识别(红色、蓝色的圆形、矩形、三角形)

要求 :分辨出一个随机颜色(红色,蓝色)的图形(圆形,矩形,三角形)

思路 : HSV色块识别+轮廓提取+同一高度面积识别

一、HSV模型

HSV(Hue, Saturation, Value)是根据颜色的直观特性由A. R. Smith在1978年创建的一种颜色空间, 也称六角锥体模型(Hexcone Model)。这个模型中颜色的参数分别是:色调(H),饱和度(S),明度(V)。


HSV色彩空间

注意:红色的H空间有两部分,需要将两部分融合后提取轮廓。

二、提取轮廓后,固定高度下分别检测圆形、正方形、三角形的面积阈值。

示例代码如下:

# encoding=utf-8
import cv2 as cv
import numpy as np
import time
import serial


def analysis(frame):
    global red_triangle
    global red_rectangle
    global red_circle
    global blue_triangle
    global blue_rectangle
    global blue_circle

    h,w,ch = frame.shape
    result = np.zeros((h, w, ch), dtype=np.uin
  • 3
    点赞
  • 74
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现形状颜色识别,可以使用OpenCVPython。下面是一个示例代码,可以识别三种形状圆形矩形三角形)和三种颜色红色、绿色和蓝色): ```python import cv2 import numpy as np # 定义颜色范围 lower_red = np.array([0, 100, 100]) upper_red = np.array([10, 255, 255]) lower_green = np.array([50, 100, 100]) upper_green = np.array([70, 255, 255]) lower_blue = np.array([110, 100, 100]) upper_blue = np.array([130, 255, 255]) # 读取图像 img = cv2.imread('shapes.jpg') # 将图像转换为灰度图像 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 对图像进行模糊处理 blur = cv2.GaussianBlur(gray, (5, 5), 0) # 边缘检测 edges = cv2.Canny(blur, 50, 150) # 查找轮廓 contours, hierarchy = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # 定义空列表存储结果 shapes = [] # 遍历每个轮廓 for cnt in contours: # 计算轮廓周长 perimeter = cv2.arcLength(cnt, True) # 进行轮廓近似 approx = cv2.approxPolyDP(cnt, 0.04 * perimeter, True) # 计算轮廓面积 area = cv2.contourArea(cnt) # 计算轮廓的形状 if len(approx) == 3: shape = "triangle" elif len(approx) == 4: x, y, w, h = cv2.boundingRect(cnt) aspect_ratio = float(w) / h if aspect_ratio >= 0.95 and aspect_ratio <= 1.05: shape = "square" else: shape = "rectangle" else: shape = "circle" # 计算轮廓的颜色 mask = np.zeros(img.shape[:2], dtype=np.uint8) cv2.drawContours(mask, [cnt], -1, 255, -1) mean_color = cv2.mean(img, mask=mask)[:3] color = None if mean_color[2] > mean_color[1] and mean_color[2] > mean_color[0]: color = "red" elif mean_color[1] > mean_color[2] and mean_color[1] > mean_color[0]: color = "green" else: color = "blue" # 将结果添加到列表中 shapes.append((shape, color)) # 在图像上绘制识别结果 font = cv2.FONT_HERSHEY_SIMPLEX for i, (shape, color) in enumerate(shapes): x, y = contours[i][0][0] cv2.putText(img, shape + " " + color, (x, y), font, 1, (255, 255, 255), 2, cv2.LINE_AA) cv2.drawContours(img, [contours[i]], -1, (0, 255, 0), 2) # 显示图像 cv2.imshow('image', img) cv2.waitKey(0) cv2.destroyAllWindows() ``` 在这个示例中,我们首先定义了三种颜色的范围,然后读取图像并将其转换为灰度图像。接下来,我们对图像进行模糊处理和边缘检测,并查找轮廓。对于每个轮廓,我们计算其周长和面积,并使用轮廓近似算法确定其形状。我们还使用一个掩膜来计算轮廓的颜色。 最后,我们将识别结果绘制在图像上,并显示结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值