自学内容网 自学内容网

电赛准备(一):视觉模块之OpenMV学习(1)--颜色识别


# 这个例子展示了使用OpenMV Cam的单色RGB565跟踪。
import sensor, image, time, math

threshold_index = 0 # 0 for red, 1 for green, 2 for blue

# 颜色跟踪阈值 (L Min, L Max, A Min, A Max, B Min, B Max)
# 下面的阈值通常跟踪红色/绿色/蓝色的东西。您可能希望调整它们……
#黑色·阈值是这个(0, 30, -22, 23, -128,80),
thresholds = [
              (30, 100, 15, 127, 15, 127), # 通用的红色阈值
              (30, 100, -64, -8, -32, 32), # 通用的绿色阈值
              (0, 30, 0, 64, -128, 0)]     # 通用的蓝色阈值

sensor.reset()                      #重置感光元件,重置摄像机
sensor.set_pixformat(sensor.RGB565) #设置颜色格式为RGB565,彩色,每个像素16bit。
sensor.set_framesize(sensor.QQVGA)   #图像大小为QVGA
sensor.skip_frames(time = 2000)     #跳过n张照片,在更改设置后,跳过一些帧,等待感光元件变稳定。
sensor.set_auto_gain(False)         #颜色识别必须关闭自动增益,会影响颜色识别效果
sensor.set_auto_whitebal(False)     #颜色识别必须关闭白平衡,会影响颜色识别效果,导致颜色的阈值发生改变
clock = time.clock()

# 只有像素大于“pixels_threshold”和面积大于“area_threshold”的区域才会
# 由下面的"find_blobs"返回。如果更改相机分辨率,则更改“pixels_threshold”和
# “area_threshold”。"merge=True"合并图像中所有重叠的斑点。。
flag=0
while(True):
    clock.tick()             # 追踪两个snapshots()之间经过的毫秒数.
    img = sensor.snapshot()  #截取感光元件中的一张图片
    flag=flag+1
    if flag>3:
        flag=1;
    #在img.find_blobs这个函数中,我们进行颜色识别
    #roi是“感兴趣区”,是在画面的中央还是右上方或者哪里进行颜色识别。此处我们没有进行配置,默认整个图像进行识别
    threshold = thresholds[flag-1]
    blobs= img.find_blobs([threshold], pixels_threshold=200, area_threshold=200, merge=True)
    #参数分别是area_threshold (面积阈值),pixels_threshold (像素个数阈值)。如果如果色块被框起来的面积小于area_threshold,或者色块像素数量小于pixels_threshold,会被过滤掉。
    if blobs:
        for blob in blobs:
            img.draw_rectangle(blob.rect())      #用矩形标记出目标颜色区域
            img.draw_cross(blob.cx(), blob.cy()) #在目标颜色区域的中心画十字形标记
             # 注意- blob的旋转是唯一的0-180。
             #img.draw_keypoints([(blob.cx(), blob.cy(), int(math.degrees(blob.rotation())))], size=20)
            if flag==1:
                print("红色")
            elif flag==2:
                print("绿色")
            elif flag==3:
                print("蓝色")

   

详细内容看这篇文章OpenMV的单颜色识别讲解_openmv黑色识别-CSDN博客


原文地址:https://blog.csdn.net/2201_75486799/article/details/140716096

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!