最大类间方差法的应用(一)

基于OpenMV平台:

1.获取图像

2.利用最大类间方差法进行图像二值化

3.对图像中面积大于阈值的物体进行标注

试验结果示意图:

最大类间方差法的应用(一)_第1张图片

试验代码:

import sensor, image, time, math, pyb
 
  
GRAYSCALE_THRESHOLD = [(0, 64)]
ROIS = [0, 0, 160, 120]
most_pixels = 500
led = pyb.LED(3)                          # Red LED = 1, Green LED = 2, Blue LED = 3, IR LEDs = 4.
 
  
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()
    h = Maximum_interclass_variance_method(img);
    GRAYSCALE_THRESHOLD =[(0, h)]
    blobs = img.find_blobs(GRAYSCALE_THRESHOLD, roi=ROIS[0:4], merge=True)
    if blobs:
        for i in range(len(blobs)):
            if blobs[i].pixels() > most_pixels:
                img.draw_rectangle(blobs[i].rect())
 
  

你可能感兴趣的:(OpenMV)