树莓派3B基于python用opencv进行颜色识别

树莓派opencv读取一帧图像

如果你的树莓派还没有安装opencv,请参考我的这篇文章安装树莓派3B安装opencv
用以下命令查看设备,若存在video0,则说明摄像头设备正常

ls /dev/

opencv读取一帧图像demo:

import cv2
import numpy as np
camera=cv2.VideoCapture(0)
while True:
	ret,frame=camera.read()
	if ret: #如果当前帧有效
		#TODO some image process
	else:
		continue
		
	cv2.imshow("frame",frame)
	cv2.waitKey(10)

opencv颜色识别流程

1.将RGB模型转换成HSV模型

RGB模型适合显示,但却并不适合作为颜色识别的模型。
HSV更加符合人眼的感受,将其作为颜色识别的模型会大大提高识别的鲁棒性,因为HSV模型颜色识别大大减少了对环境光的依赖。
opencv提供了将RGB转换到HSV的函数:

hsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

2.opencv中,HSV模型的取值范围

H∈ [0, 180), S ∈ [0, 255], V ∈ [0, 255]

经过实验,蓝色在HSV模型中的取值是:H在100到140之间,S和V都在90到255之间。一些基本的颜色H的取值可以如下设置:

Orange  0-22
Yellow 22- 38
Green 38-75
Blue 75-130
Violet 130-160
Red 160-179

3.对彩色图像进行直方图均衡

#split hsv_img into 3 channels
hsvSplit = cv2.split(hsv_img)
#Hist equalization only on the V channel
cv2.equalizeHist(hsvSplit[2],hsvSplit[2])
#merge hsv_img using the result of V channel hist equalization
cv2.merge(hsvSplit,hsv_img)

4.使用opencvAPI进行颜色阈值检测,得到二值图像

    #yellow parameter  
    iLowH = 10
    iHighH = 55
    iLowS = 40
    iHighS = 255
    iLowV = 20
    iHighV = 255
#using OpenCV API to detect special color we interest
#detect each pixel in hsv_img
#if current pixel HSV value is between the theshold we set before,then set this pixel 255 in the output image
#else,set this pixel 0 in the output image
imgThresholded = cv2.inRange(hsv_img, (iLowH, iLowS, iLowV), (iHighH, iHighS, iHighV))

5.对二值图像进行开操作,删除零星噪点

#perform open opration for imgThresholded, in order to drop some noisy pixels 
element = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
imgThresholded = cv2.morphologyEx(imgThresholded, cv2.MORPH_OPEN, element)

6.再进行闭操作,连接一些连通域

#then perform close opration to connect some separated white small piece
imgThresholded = cv2.morphologyEx(imgThresholded, cv2.MORPH_CLOSE, element)

这样得到的二值图像就是颜色识别后的结果。

opencv颜色识别的完整流程

import cv2
import numpy as np
camera=cv2.VideoCapture(0)

def cam_detection_color_hsv(hsv_img):
    #set H S V threshold
    #red parameter
    '''
    iLowH = 160
    iHighH = 179
    iLowS = 90
    iHighS = 255
    iLowV = 90
    iHighV = 255
    '''
    #yellow parameter  
    iLowH = 10
    iHighH = 55
    iLowS = 40
    iHighS = 255
    iLowV = 20
    iHighV = 255
    '''
    #black parameter
    iLowH = 0
    iHighH = 180
    iLowS = 0
    iHighS = 255
    iLowV = 0
    iHighV = 48
    '''
    
    #对彩色图像做直方图均衡化
    #split hsv_img into 3 channels
    hsvSplit = cv2.split(hsv_img)
    #Hist equalization
    cv2.equalizeHist(hsvSplit[2],hsvSplit[2])
    #merge hsv_img using the result of hist equalization
    cv2.merge(hsvSplit,hsv_img)
    
    #using OpenCV API to detect special color we interest
    #detect each pixel in hsv_img
    #if current pixel HSV value is between the theshold we set before,then set this pixel 255 in the output image
    #else,set this pixel 0 in the output image
    imgThresholded = cv2.inRange(hsv_img, (iLowH, iLowS, iLowV), (iHighH, iHighS, iHighV))
    
    #perform open opration for imgThresholded, in order to drop some noisy pixels 
    element = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
    imgThresholded = cv2.morphologyEx(imgThresholded, cv2.MORPH_OPEN, element)
    #then perform close opration to connect some separated white small piece
    imgThresholded = cv2.morphologyEx(imgThresholded, cv2.MORPH_CLOSE, element)
                                      
    return imgThresholded
  


while(True):
    ret,frame=camera.read()
    if ret: #如果当前帧有效
        hsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    else:
        continue
    
    threshold_img = cam_detection_color_hsv(hsv_frame)
    
    cv2.imshow("threshold_img",threshold_img)
    cv2.imshow("frame",frame)
    cv2.waitKey(10)
### 树莓派颜色识别分拣系统的设计与实现 构建一个基于树莓派颜色识别分拣系统涉及硬件连接、软件编程以及算法实现等多个方面。以下是详细的指导内容。 #### 硬件设计 在硬件部分,需要选择合适的传感器和执行器来完成颜色识别和分拣任务。以下是一个推荐的硬件配置方案: - **主控设备**:树莓派4B(4GB),超频至2.0GHz以提升性能[^3]。 - **视觉传感器**:使用RGB相机(如树莓派摄像头模块)进行颜色识别。 - **深度传感器**(可选):如果需要更精确的空间定位,可以添加Intel RealSense D435i深度相机[^3]。 - **执行器**:使用步进电机或伺服电机控制机械臂或传送带,完成分拣动作。 - **电源管理**:12V锂电池配合降压模块,为所有设备提供稳定电源。 #### 软件架构 软件部分主要分为以下几个模块: - **图像采集与预处理**:通过树莓派摄像头获取实时视频流,并进行必要的预处理操作。 - **颜色识别算法**: - 使用HSV颜色空间过滤技术快速定位目标颜色对象[^3]。 - 可结合形状检测进一步提高识别精度。 - **决策逻辑**:根据识别结果生成分拣指令。 - **执行器控制**:通过GPIO接口驱动步进电机或伺服电机完成分拣动作。 以下是一个简单的代码示例,展示如何使用OpenCV进行颜色识别: ```python import cv2 import numpy as np # 初始化摄像头 cap = cv2.VideoCapture(0) # 定义颜色范围(以红色为例) lower_red = np.array([0, 50, 50]) upper_red = np.array([10, 255, 255]) while True: # 获取帧 ret, frame = cap.read() # 转换到HSV颜色空间 hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # 创建掩膜 mask = cv2.inRange(hsv, lower_red, upper_red) # 寻找轮廓 contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # 绘制边界框 for contour in contours: if cv2.contourArea(contour) > 100: # 过滤小区域 x, y, w, h = cv2.boundingRect(contour) cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) # 显示结果 cv2.imshow('Color Detection', frame) # 按下'q'键退出 if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() ``` #### 数据标注与模型训练 为了提高系统的鲁棒性,可以引入机器学习方法。数据标注是关键步骤之一,工程师可以在产品图像上用软件圈出目标颜色的位置,并打上标签[^1]。随后,利用这些标注好的数据训练一个分类模型,例如使用YOLO算法进行目标检测[^4]。 #### 相关实验与优化 在实际应用中,可能需要对算法进行优化以适应不同光照条件下的颜色变化。此外,还可以尝试语义分割网络(如DeepLab-ResNet)来增强识别效果[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值