main.py -- put your code here!
import sensor, image, time
from pyb import UART
sensor.reset() #摄像头初始化
sensor.set_pixformat(sensor.RGB565) #设置为彩色模式
sensor.set_framesize(sensor.QQVGA) #画幅为QQVGA即分辨率为160*120
sensor.set_auto_whitebal(False) #关闭白平衡
clock = time.clock()
#根据测量设备小球颜色,并把LAB色值存储到集合中
红色阈值
red_threshold =(49, 60, 53, 84, 0, 70)
绿色阈值
green_threshold = (39, 93, -71, -28, -22, 67)
蓝色阈值
blue_threshold =(52, 94, -11, 9, -13, -65)
黄色阈值
yellow_threshold = (83, 96, 53, 3, 34, 9)
#定义大数组包含着x,y坐标、z距离、颜色和小球数量,初始化值分别是x, y, z, color, number
coordinate_system = [0, 0, 0,"0", 0]
xThreshold = [0, 0, 0,"0", 0] #默认值 ,中间值
judge = True
#def senddata():#串口通信,发送小球和存储区的详细信息
#uart.write(coordinate_system[0:])
颜色代码是find_blobs返回的blob对象中的一个成分, 用于标识,该色块是由在哪个阈值下选择的
颜色1: 红色的颜色代码
red_color_code = 1 # code = 2^0 = 1
颜色2: 绿色的颜色代码
green_color_code = 2 # code = 2^1 = 2
颜色3的代码
blue_color_code= 4 # color_code = 2^2 = 4
颜色4的代码
yellow_color_code= 8 # color_code = 2^3 = 8
K=720 #实际距离=k/像素的面积,k=36*20
K2 = 6.4/36
#实际大小=k2*直径的像素 k2=41/60
while(True):
clock.tick()
img = sensor.snapshot() #获取当期所采集到的图像快照
# 设置色块阈值,具体数值情况可以通过OpenMVIDE中的阈值调整功能来得出
# 工具 → Mechine Vision → Threshold Editor
# area_threshold面积阈值设置为100 ,如果色块被面积小于100,则会被过滤掉
# pixels_threshold 像素个数阈值,如果色块像素数量小于这个值,会被过滤掉
# merge 设置为True,合并所有重叠的寻找到的blob为一个色块
#识别
blobs = img.find_blobs([red_threshold, green_threshold, blue_threshold, yellow_threshold], pixels_threshold=50, area_threshold=50, merge=True)
if len(blobs) == 0:
continue
if blobs:
#如果找到了目标颜色
for blob in blobs:
#迭代找到的目标颜色区域
x = blob[0]
y = blob[1] #
width = blob[2] # 色块矩形的宽度
height = blob[3] # 色块矩形的高度
center_x = blob[5] # 色块中心点x值
center_y = blob[6] # 色块中心点y值
color_code = blob[8] # 颜色代码
coordinate_system[3] = blob[8]
# 添加颜色说明
if color_code == red_color_code:
img.draw_string(x, y - 10, "red", color = (0xFF, 0x00, 0x00))
if color_code == green_color_code:
img.draw_string(x, y - 10, "green", color = (0x00, 0xFF, 0x00))
if color_code == blue_color_code:
img.draw_string(x, y - 10, "blue", color = (0x00, 0x00, 0xFF))
if color_code == yellow_color_code:
img.draw_string(x, y - 10, "yellow", color = (0xF5, 0xDE, 0xB3))
#用矩形标记出目标颜色区域
img.draw_rectangle([x, y, width, height])
#在目标颜色区域的中心画十字形标记
img.draw_cross(center_x, center_y)
while(judge):
for blue_color_code in blobs:
#if coordinate_system[3] == red_color_code:
coordinate_system[0] += blob[5]# 色块中心点x值
coordinate_system[1] += blob[6]# 色块中心点y值
Lm = (blob[2]+blob[3])/2 #b[2]是长,b[3]是宽 矩形的像素面积
length = K/Lm
print ("blue",length)
coordinate_system[2] += length
coordinate_system[4] += 1
coordinate_system[3] = "blue"
coordinate_system[0] /= coordinate_system[4]
coordinate_system[1] /= coordinate_system[4]
coordinate_system[2] /= coordinate_system[4]
#senddata()
print (coordinate_system)
coordinate_system = xThreshold
judge = False
judge = True