>>> 星瞳科技|OpenMV中国官方网站 <<<

>>> 星瞳科技店铺地址|OpenMV中国官方代理,全球九大代理商之一 <<<

>>> OpenMV3 Cam M7 官方高配版上市啦~戳我戳我戳我~ <<<

>>> 星瞳科技-OpenMV中文教程网 <<<

本例程为 10-Color_Ttracking-blob_detection
本例程的目标是用OpenMV实现多个颜色同时识别,多颜色识别与单颜色识别类似。

# Blob Detection Example
#
# This example shows off how to use the find_blobs function to find color
# blobs in the image. This example in particular looks for dark green objects.

import sensor, image, time

# For color tracking to work really well you should ideally be in a very, very,
# very, controlled enviroment where the lighting is constant...
green_threshold   = (   0,   80,  -70,   -10,   -0,   30)
#设置绿色的阈值,括号里面的数值分别是L A B 的最大值和最小值(minL, maxL, minA,
# maxA, minB, maxB),LAB的值在图像左侧三个坐标图中选取。如果是灰度图,则只需
#设置(min, max)两个数字即可。
red_threshold = ( 15, 50, 40, 80, 20, 60)
#设置红色阈值

# You may need to tweak the above settings for tracking green things...
# Select an area in the Framebuffer to copy the color settings.

sensor.reset() # Initialize the camera sensor.
sensor.set_pixformat(sensor.RGB565) # use RGB565.
sensor.set_framesize(sensor.QQVGA) # use QQVGA for speed.
sensor.skip_frames(10) # Let new settings take affect.
sensor.set_whitebal(False) # turn this off.
#关闭白平衡。白平衡是默认开启的,在颜色识别中,需要关闭白平衡。
clock = time.clock() # Tracks FPS.

while(True):
    clock.tick() # Track elapsed milliseconds between snapshots().
    img = sensor.snapshot() # Take a picture and return the image.

    green_blobs = img.find_blobs([green_threshold])
    #find_blobs(thresholds, invert=False, roi=Auto),thresholds为颜色阈值,是一个元组,需要用括号[ ]括起来。invert=1,反转颜色阈值,invert=False默认不反转。roi设置颜色识别的视野区域,roi是一个元组, roi = (x, y, w, h),代表从左上顶点(x,y)开始的宽为w高为h的矩形区域,roi不设置的话默认为整个图像视野。这个函数返回一个列表,[0]代表识别到的目标颜色区域左上顶点的x坐标,[1]代表左上顶点y坐标,[2]代表目标区域的宽,[3]代表目标区域的高,[4]代表目标区域像素点的个数,[5]代表目标区域的中心点x坐标,[6]代表目标区域中心点y坐标,[7]代表目标颜色区域的旋转角度(是弧度值,浮点型,列表其他元素是整型),[8]代表与此目标区域交叉的目标个数,[9]代表颜色的编号(它可以用来分辨这个区域是用哪个颜色阈值threshold识别出来的)。
    if green_blobs:
    #如果找到了目标颜色
        for b in green_blobs:
        #迭代找到的目标颜色区域
            # Draw a rect around the blob.
            img.draw_rectangle(b[0:4],color=(255,255,255)) # rect
            #用白色矩形标记出目标颜色区域
            img.draw_cross(b[5], b[6]) # cx, cy
            #在目标颜色区域的中心画十字形标记

    #同时识别红色
    red_blobs = img.find_blobs([red_threshold])
    if red_blobs:
        for b in red_blobs:
            # Draw a rect around the blob.
            img.draw_rectangle(b[0:4],color=(0,0,0)) # rect
            #用黑色矩形标记出目标颜色区域
            img.draw_cross(b[5], b[6]) # cx, cy            

    print(clock.fps()) # Note: Your OpenMV Cam runs about half as fast while
    # connected to your computer. The FPS should increase once disconnected.

运行效果如图: