前言:之前跟着星瞳科技Openmv的官方教程,查找色块识别颜色必须要事先确定好颜色的阈值。但若是在没有确定好查找颜色的前提下,想要随机跟踪一个色块该如何去操作。当我学习到了统计信息这一部分内容后,写出此代码来解决问题。
一:对摄像头进行初始化,并且导入头文件
# Untitled - By: 烧杯大师 - 周三 11月 1 2023
import sensor, image, time
#【第一步:对Openmv进行初始化】
sensor.reset() # 初始化感光元件
sensor.set_pixformat(sensor.RGB565) # 设置像素模式 彩色 每个像素 16bit
sensor.set_framesize(sensor.QQVGA) # 分辨率 160*120
#sensor.set_framesize(sensor.QVGA) # 分辨率 320*240 帧率过低太卡
sensor.set_auto_gain(False) # 关闭自动增益
sensor.set_auto_whitebal(False) # 关闭白平衡
sensor.skip_frames(time = 2000) # 等待感光元件变稳定
Range = (0,0,160,120) # QQVGA 设置感兴趣区 roi
#Range = (0,0,320,240) # QVGA 设置感兴趣区 roi
二:通过感兴趣区域确定识别的颜色
#【第二步:确定识别的颜色(感兴趣区间)】
for i in range(200):
img = sensor.snapshot()
img.draw_rectangle((70,50,20,20), color=(255,0,0))
# x y w h 画框颜色
Statistics = img.get_statistics(roi=(70,50,20,20))
Threshold = [Statistics.l_min(),Statistics.l_max(), #从统计信息中得到色块阙值
Statistics.a_min(),Statistics.a_max(),
Statistics.b_min(),Statistics.b_max()]
#print(Threshold)
三:寻找色块与图形
#【第三步:寻找色块】
while(True):
img = sensor.snapshot().lens_corr(1.8)
for c in img.find_circles(roi = Range, threshold = 3500, x_margin = 10, y_margin = 10, r_margin = 10, r_min = 2, r_max = 100, r_step = 2):
area = (c.x()-c.r(), c.y()-c.r(), 2*c.r(), 2*c.r())
#area【起始X(圆心-半径),起始Y(圆心-半径),宽度2R,长度2R】
#area为识别到的圆的区域,即圆的外接矩形框
statistics = img.get_statistics(roi=area)#像素颜色统计
#print(statistics)
#(0,100,0,120,0,120)是红色的阈值,所以当区域内的众数(也就是最多的颜色),范围在这个阈值内,就说明是红色的圆。
#l_mode(),a_mode(),b_mode()是L通道,A通道,B通道的众数。
if Threshold[0]<statistics.l_mode()< Threshold[1] and Threshold[2]<statistics.a_mode()< Threshold[3] and Threshold[4]<statistics.b_mode()< Threshold[5]:
#if the circle is red
img.draw_circle(c.x(), c.y(), c.r(), color = (255, 0, 0))
img.draw_cross(c.x(), c.y()) #画十字
print(c.x(), c.y())
#识别到的红色圆形用红色的圆框出来
else:
img.draw_rectangle(area, color = (255, 255, 255))
#将非红色的圆用白色的矩形框出来