特征识别-圆和矩形(Identify circles and rectangles)

来源:互联网 发布:显卡温度监控软件 编辑:程序博客网 时间:2024/06/05 20:42

基于OpenMV平台进行开发

识别原理:

定义矩形度的公式:

Rectangularity = area_real/area_external
矩形度 = 图形面积/外接矩形面积

圆和矩形的矩形度值不同

识别结果:


程序代码:

import sensor, image, time, math, pyb
# 全局变量
GRAYSCALE_THRESHOLD = [(0, 100)]
Rectangularity_Threshold = 0.9            # 设定阈值
# 调用硬件
led = pyb.LED(3)                          # Red LED = 1, Green LED = 2, Blue LED = 3, IR LEDs = 4.
clock = time.clock()                      # Tracks FPS.
def senser_init():                         # 摄像头传感器初始化函数
    sensor.reset()                         # Initialize the camera sensor.
    sensor.set_pixformat(sensor.GRAYSCALE) # use grayscale.
    sensor.set_framesize(sensor.QQVGA)     # use QQVGA for speed.
    sensor.skip_frames(30)                 # Let new settings take affect.
    sensor.set_auto_gain(True)             # must be turned off for color tracking
    sensor.set_auto_whitebal(True)         # must be turned off for color tracking
    return;
def hardware_init():
    led.on()            #亮灯
    time.sleep(100)     #延时150ms
    led.off()           #暗灯
    time.sleep(100)
    return;
def Maximum_interclass_variance_method(grayFrame):  # 最大类间方差法
    w = 0
    avgValue = 0
    t = 0
    maxVariance = 0
    statistics_data = grayFrame.get_statistics()
    u = statistics_data.mean()
    histogram_data = grayFrame.get_histogram()      # 获取灰度直方图
    histogram_bins = histogram_data.bins()          # 获取灰度直方图的列表
    for i in range(len(histogram_bins)):
        w += (histogram_bins[i]+0.0000001)
        avgValue  += i * (histogram_bins[i]+0.0000001)
        t = avgValue/w - u
        variance = t * t * w /(1 - w)
        if(variance > maxVariance):
            maxVariance = variance;
            threshold = i;
    return threshold
# 主函数
hardware_init();
senser_init();
while(True):
    img = sensor.snapshot()                                                  # Take a picture and return the image.
    h = Maximum_interclass_variance_method(img);                             # 最大类间方差法计算阈值
    GRAYSCALE_THRESHOLD =[(0, h)]
    blobs = img.find_blobs(GRAYSCALE_THRESHOLD, merge=True) # 图像分割
    if blobs:
        for i in range(len(blobs)):
            area_real = blobs[i].pixels()                                    # 实际面积
            area_external = blobs[i].w() * blobs[i].h()                      # 外接矩形的面积
            Rectangularity = area_real/area_external                         # 计算矩形度
            if Rectangularity > Rectangularity_Threshold:                    # 大于阈值为矩形
                img.draw_rectangle(blobs[i].rect())
            elif Rectangularity < Rectangularity_Threshold:                  # 小于阈值为圆型
                img.draw_circle(blobs[i].x()+int(blobs[i].w()/2), blobs[i].y()+int(blobs[i].w()/2),int(blobs[i].w()/2), color=255)

原创粉丝点击