import sensor, image, time, math,display
from pyb import UART
#相关变量的初始化
GRAYSCALE_THRESHOLD = [(0, 40)]
ROIS = [
(0, 100, 160, 20, 0.8),
(0, 050, 160, 20, 0.3),
(0, 000, 160, 20, 0.1)
]
weight_sum = 0
for r in ROIS: weight_sum += r[4]
#滤波相关变量初始化
direction_history=[]
filter_size=20
#相机初始化
sensor.reset()
sensor.set_pixformat(sensor.GRAYSCALE)
sensor.set_framesize(sensor.QQVGA)
sensor.skip_frames(30)
sensor.set_auto_gain(False)
sensor.set_auto_whitebal(False)
sensor.set_vflip(True)
sensor.set_hmirror(True)
clock = time.clock()
uart=UART(3,115200)
uart.init(115200,bits=8,parity=None,stop=1)
#lcdc初始化
lcd = display.SPIDisplay()
while(True):
sensor.set_vflip(True)
clock.tick()
img = sensor.snapshot()
centroid_sum = 0
#首先寻找对应颜色阈值的色块
for r in ROIS:
blobs = img.find_blobs(GRAYSCALE_THRESHOLD, roi=r[0:4], merge=True)
if blobs:
most_pixels = 0
largest_blob = 0
#找到色块后遍历该色块,以找到其中像素最多的一个点,作为绘制线框的中心点
for i in range(len(blobs)):
if blobs[i].pixels() > most_pixels:
most_pixels = blobs[i].pixels()
largest_blob = i
#绘制矩形线框
img.draw_rectangle(blobs[largest_blob].rect())
img.draw_cross(blobs[largest_blob].cx(),
blobs[largest_blob].cy())
centroid_sum += blobs[largest_blob].cx() * r[4]
center_pos = (centroid_sum / weight_sum)
#lcd初始化
lcd.write(sensor.snapshot())
#角度相关计算
deflection_angle = 0
direction_send = 0
direction_judge = 0
#计算偏离中心的角度,对其求反正切即可得到偏转角
deflection_angle = -math.atan((center_pos-80)/60)
deflection_angle = math.degrees(deflection_angle)
#角度滤波
direction_history.append(deflection_angle)
if len(direction_history)>filter_size:
direction_history.pop(0)
#偏转角和偏转方向相关计算
avg_deflection_angle=sum(direction_history)/len(direction_history)
direction_judge=avg_deflection_angle
deflection_angle=abs(avg_deflection_angle)
#判断偏转方向
if direction_judge > 10:
direction_send=1
elif direction_judge< -10:
direction_send=2
else:
direction_send=0
#串口发送和打印相关变量
send_data=bytearray([0x2C,0x12,direction_send,int(deflection_angle),0x5B])
uart.write(send_data)
print("Turn Angle:",int(deflection_angle) ,"Direction:",direction_send)
print(clock.fps())添加了senor.set_vflip(True)也没有反应。
目前屏幕在lcd上也不是竖屏显示,而是横屏显示。
谁来救救孩子!!!急
注释
#sensor.set_vflip(True)
#sensor.set_hmirror(True)