找回密码
 立即注册
楼主: Lvp***

国二,2023电赛 【G题】空地协同智能消防系

[复制链接]

该用户从未签到

1

主题

33

回帖

109

积分

注册会员

积分
109
 楼主| 发表于 2023-10-9 15:03:23 | 显示全部楼层
详细照片2
截图202310091503148017.jpg
回复 送花

使用道具 举报

该用户从未签到

1

主题

33

回帖

109

积分

注册会员

积分
109
 楼主| 发表于 2023-10-9 15:04:33 | 显示全部楼层
原始照片,用于采集训练
截图202310091504086655.jpg
截图202310091504216002.jpg
回复 支持 反对 送花

使用道具 举报

该用户从未签到

1

主题

33

回帖

109

积分

注册会员

积分
109
 楼主| 发表于 2023-10-9 15:04:58 | 显示全部楼层
放大训练照片
截图202310091504539676.jpg
回复 支持 反对 送花

使用道具 举报

该用户从未签到

1

主题

33

回帖

109

积分

注册会员

积分
109
 楼主| 发表于 2023-10-9 15:05:17 | 显示全部楼层
放大训练照片2
截图202310091505122124.jpg
回复 支持 反对 送花

使用道具 举报

该用户从未签到

1

主题

33

回帖

109

积分

注册会员

积分
109
 楼主| 发表于 2023-10-9 15:06:30 | 显示全部楼层
雷达驱动代码
  1. # RadarDriver - By: CaiZhipeng - 周二 6月 27 2023
  2. import time, math,image
  3. from fpioa_manager import fm
  4. from machine import Timer,PWM,UART
  5. class RadarData:
  6.     def __init__(self,angle, distance):
  7.         self.angle = angle
  8.         self.distance = distance
  9.     def PrintRadarData(self):
  10.         print("angle:{:0.2f} distance:{:0.2f}".format(self.angle,self.distance))
  11.     def ToRectangularCoordinates(self):
  12.         angle_rad = math.radians(self.angle)
  13.         x = self.distance * math.cos(angle_rad)
  14.         y = self.distance * math.sin(angle_rad)
  15.         return x, y
  16.     def ToBytes(self):
  17.         angle_int = int(self.angle)
  18.         distance_int = int(self.distance)
  19.         angle_byte_H = (angle_int >> 8) & 0xFF
  20.         angle_byte_L = angle_int & 0xFF
  21.         distance_byte_H = (distance_int >> 8) & 0xFF
  22.         distance_byte_L = distance_int & 0xFF
  23.         return [angle_byte_H, angle_byte_L, distance_byte_H, distance_byte_L]
  24. class RadarClusterData:
  25.     def __init__(self,ClusterList):
  26.         self.ClusterList = ClusterList
  27.         self.length = len(ClusterList)
  28.         angles = [data.angle for data in ClusterList]
  29.         distances = [data.distance for data in ClusterList]
  30.         average_angle = sum(angles) / self.length
  31.         average_distance = sum(distances) / self.length
  32.         self.AverageRadarData = RadarData(average_angle,average_distance)
  33.         self.VarianceAngle = sum((x - average_angle) ** 2 for x in angles) / self.length
  34.         self.VarianceDistance = sum((x - average_distance) ** 2 for x in distances) / self.length
  35.     def PrintRadarClusterData(self):
  36.         print("AverageRadarData:")
  37.         self.AverageRadarData.PrintRadarData()
  38.         print("VarianceAngle:{:0.2f} VarianceDistance:{:0.2f}".format(self.VarianceAngle,self.VarianceDistance))
  39.    
  40. class RadarDbscan:
  41.     def __init__(self,DataList,Eps,MinPts):
  42.         self.DataList = DataList
  43.         self.Eps = Eps
  44.         self.MinPts = MinPts
  45.         self.ClusterList = []
  46.         self.NoiseList = []
  47.     def GetDistance(self, Data1, Data2):
  48.         # 定义极坐标的距离公式
  49.         theta_diff = Data1.angle - Data2.angle
  50.         return math.sqrt(Data1.distance**2 + Data2.distance**2 - 2*Data1.distance*Data2.distance*math.cos(theta_diff))
  51.    
  52.     def GetNeighbour(self, Data):
  53.         # 获取邻居
  54.         NeighbourList = []
  55.         for data in self.DataList:
  56.             if self.GetDistance(Data,data) <= self.Eps:
  57.                 NeighbourList.append(data)
  58.         return NeighbourList
  59.    
  60.     def GetCoreObject(self):
  61.         # 获取核心对象
  62.         CoreObjectList = []
  63.         for data in self.DataList:
  64.             if len(self.GetNeighbour(data)) >= self.MinPts:
  65.                 CoreObjectList.append(data)
  66.         return CoreObjectList
  67.    
  68.     def GetCluster(self):
  69.         # 获取聚类
  70.         CoreObjectList = self.GetCoreObject()
  71.         ClusterList = []
  72.         NoiseList = []
  73.         OkList = []
  74.         for data in CoreObjectList:
  75.             if data not in OkList:
  76.                 Cluster = []
  77.                 Cluster.append(data)
  78.                 OkList.append(data)
  79.                 NeighbourList = self.GetNeighbour(data)
  80.                 for Neighbour in NeighbourList:
  81.                     if Neighbour not in Cluster:
  82.                         Cluster.append(Neighbour)
  83.                         OkList.append(Neighbour)
  84.                 NewClusterData = RadarClusterData(Cluster)
  85.                 ClusterList.append(NewClusterData)
  86.         for data in self.DataList:
  87.             if data not in OkList:
  88.                 NoiseList.append(data)
  89.         self.ClusterList = ClusterList
  90.         self.NoiseList = NoiseList
  91.         return ClusterList, NoiseList
  92.    
  93.     def SortByCluster_size(self):
  94.         self.ClusterList.sort(key=lambda x: x.length)
  95.     def SortByVariance_distance(self):
  96.         self.ClusterList.sort(key=lambda x: x.VarianceDistance)
  97.     def SortByVariance_angle(self):
  98.         self.ClusterList.sort(key=lambda x: x.VarianceAngle)
  99. class RadarDriver:
  100.     # 雷达驱动类
  101.     def __init__(self,port_RX, port_TX,PWM_pin,PWM_freq,PWM_duty):
  102.         # 进行初始化设置和准备工作
  103.         fm.register(port_RX, fm.fpioa.UART2_RX, force=True)
  104.         fm.register(port_TX, fm.fpioa.UART2_TX, force=True)
  105.         tim = Timer(Timer.TIMER0, Timer.CHANNEL0, mode=Timer.MODE_PWM)
  106.         self.Time_interupt = Timer(Timer.TIMER1, Timer.CHANNEL0, mode=Timer.MODE_PERIODIC, period=4000, callback=self.ClearFlash)
  107.         self.MotorPWM = PWM(tim, freq=PWM_freq, duty=PWM_duty, pin=PWM_pin)
  108.         self.RplidarA1uart = UART(UART.UART2, 115200, read_buf_len=1024)
  109.         self.RadarDataList = []
  110.         self.SwitchFlag = 0
  111.         self.MinAngle = 0
  112.         self.MaxAngle = 360
  113.         self.MaxDistance = 500
  114.         self.MapImg = image.Image(size=(224,224))
  115.     def CheckHealthy(self):
  116.         CheckData = [0xA5, 0x52]
  117.         Res = []
  118.         self.RplidarA1uart.write(bytes(CheckData))
  119.         text = self.RplidarA1uart.read()
  120.         if text:
  121.             for txt in text:
  122.                 Res.append(txt)
  123.             if len(Res) >= 8:
  124.                 if(Res[0] == 0xA5 and
  125.                 Res[1] == 0x5A and
  126.                 Res[2] == 0x03 and
  127.                 Res[3] == 0x00 and
  128.                 Res[4] == 0x00 and
  129.                 Res[5] == 0x00 and
  130.                 Res[6] == 0x06):
  131.                     if Res[7] == 0x00:
  132.                         return 1
  133.                     else:
  134.                         return Res[-2:]
  135.         return 0
  136.     def EnableRplidar(self):
  137.         if(self.CheckHealthy()):
  138.             self.Time_interupt.start()
  139.             self.MotorPWM.enable()
  140.             return 1
  141.         return 0
  142.     def DisableRplidar(self):
  143.         self.PauseScan()
  144.         self.MotorPWM.disable()
  145.     def PauseScan(self):
  146.         if self.SwitchFlag == 1:
  147.             self.Time_interupt.stop()
  148.             EndData = [0xA5, 0x25]
  149.             self.RplidarA1uart.write(bytes(EndData))
  150.             self.SwitchFlag = 0
  151.     def ContinueScan(self):
  152.         Res = []
  153.         StartData = [0xA5, 0x82, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x22]
  154.         if self.SwitchFlag == 0:
  155.             self.Time_interupt.start()
  156.             self.RplidarA1uart.write(bytes(StartData))
  157.             text = self.RplidarA1uart.read()
  158.             if text:
  159.                 for txt in text:
  160.                     Res.append(txt)
  161.                 if len(Res) >= 7:
  162.                     if(Res[0] == 0xA5 and
  163.                     Res[1] == 0x5A and
  164.                     Res[2] == 0x54 and
  165.                     Res[3] == 0x00 and
  166.                     Res[4] == 0x00 and
  167.                     Res[5] == 0x40 and
  168.                     Res[6] == 0x82):
  169.                         self.SwitchFlag = 1
  170.                         return 1
  171.         return 0
  172.     def Decode_q3_6bit(self, number):
  173.         if number >= 32:
  174.             number = number - 64
  175.         return number / 8.0
  176.     def validate_packet(self,packet):
  177.         TrueChkSum = (packet[0]&0x0F) | ((packet[1]&0x0F)<<4)
  178.         data = packet[2:]
  179.         ChkSum = 0
  180.         for byte in data:
  181.             ChkSum ^= byte
  182.         return TrueChkSum == ChkSum
  183.     def ExpressAnalyseByte(self, Byte, Start_angle, Delta_angle, index):
  184.         distance1 = ((Byte[0]&0xFC) >> 2 | Byte[1] << 6)/10
  185.         distance2 = ((Byte[2]&0xFC) >> 2 | Byte[3] << 6)/10
  186.         theta1 = (Byte[0]&0x03)<<4 | (Byte[4]&0x0F)
  187.         theta2 = (Byte[2]&0x03)<<4 | ((Byte[4]&0xF0) >> 4)
  188.         angle1 = Start_angle + Delta_angle / 32.0 * index - self.Decode_q3_6bit(theta1)
  189.         angle2 = Start_angle + Delta_angle / 32.0 * (index+1) - self.Decode_q3_6bit(theta2)
  190.         if angle1 > 360:
  191.             angle1 = angle1 - 360
  192.         if angle2 > 360:
  193.             angle2 = angle2 - 360
  194.         if distance1>0:
  195.             self.RadarDataList.append(RadarData(angle1,distance1))
  196.         if distance2>0:
  197.             self.RadarDataList.append(RadarData(angle2,distance2))
  198.     def AngleDiff(self, Start_angle, new_Start_angle):
  199.         if Start_angle <= new_Start_angle:
  200.             result = new_Start_angle - Start_angle
  201.         else:
  202.             result = 360 + new_Start_angle - Start_angle
  203.         return result
  204.     def ExpressAnalyseData(self, data):
  205.         Start_angle = (data[0][2] | (data[0][3]&0x7F) << 8)/64.0
  206.         new_Start_angle = (data[1][2] | (data[1][3]&0x7F) << 8)/64.0
  207.         Delta_angle = self.AngleDiff(Start_angle,new_Start_angle)
  208.         for i in range(16):
  209.             self.ExpressAnalyseByte(data[0][4+i*5:9+i*5],Start_angle,Delta_angle,2*i+1)
  210.     def ExpressGetData(self, batch):
  211.         temp = []
  212.         RplidarA1Data = []
  213.         AnalyseRadarDataList = []
  214.         self.RadarDataList.clear()
  215.         while len(self.RadarDataList) < 32:
  216.             self.ContinueScan()
  217.             ResFlag = 0
  218.             text = self.RplidarA1uart.read(84*batch)
  219.             if text:
  220.                 #self.PauseScan()
  221.                 for txt in text:
  222.                     if(txt & 0xF0) == 0xA0 and ResFlag == 0:# 验证头帧
  223.                         temp.append(txt)
  224.                         ResFlag = 1
  225.                     elif(txt & 0xF0) == 0x50 and ResFlag == 1:# 验证头帧
  226.                         temp.append(txt)
  227.                         ResFlag = 2
  228.                     elif ResFlag < 2:# 有冗余数据舍去
  229.                         temp.clear()
  230.                         ResFlag = 0
  231.                     if ResFlag == 2:
  232.                         RplidarA1Data.extend(temp)# 存放头数据并开始接收
  233.                         temp.clear()
  234.                         ResFlag = 3
  235.                     elif ResFlag == 3 and len(RplidarA1Data) < 84:
  236.                         RplidarA1Data.append(txt)
  237.                     if len(RplidarA1Data) == 84:# 一次接收完成
  238.                         if self.validate_packet(RplidarA1Data):# 验证数据
  239.                             AnalyseRadarDataList.append(RplidarA1Data[:])# 存入解析队列(一个数据解析需要它的下一个数据的一个表象)
  240.                         if len(AnalyseRadarDataList) == 2:# 开始解析
  241.                             self.ExpressAnalyseData(AnalyseRadarDataList)
  242.                             AnalyseRadarDataList.pop(0)
  243.                         RplidarA1Data.clear()
  244.                         temp.clear()
  245.                         ResFlag = 0
  246.     def ClearFlash(self,Time_interupt):
  247.         self.RplidarA1uart.read(1024)
  248.     def ReadRadarData(self):
  249.         if self.MaxAngle > 360:
  250.             temp = self.MaxAngle
  251.             while self.MaxAngle > 360:
  252.                 self.MaxAngle = self.MaxAngle - 360
  253.             self.RadarDataList = [x for x in self.RadarDataList if self.MinAngle <= x.angle <= 360 or 0 <= x.angle <= self.MaxAngle and x.distance <= self.MaxDistance]
  254.             self.MaxAngle = temp
  255.         else:
  256.             self.RadarDataList = [x for x in self.RadarDataList if self.MinAngle <= x.angle <= self.MaxAngle and x.distance <= self.MaxDistance]
  257.         self.RadarDataList.sort(key=lambda x: x.angle)
  258.         return self.RadarDataList
  259.    
  260.     def CreatMapping(self,weight=224,height=224):
  261.         self.MapImg.clear()
  262.         X_max = self.MaxDistance * math.cos(math.radians(45))
  263.         Y_max = self.MaxDistance * math.cos(math.radians(45))
  264.         self.ReadRadarData()
  265.         for data in self.RadarDataList:
  266.             x,y = data.ToRectangularCoordinates()
  267.             x = int(x / X_max * weight / 2 + weight / 2)
  268.             y = int(y / Y_max * height / 2 + height / 2)
  269.             self.MapImg.draw_line(x,y,x,y,(225,225,255),thickness = 3)
  270.         return self.MapImg
  271.    
  272.     def CreatDbscanMapping(self,ClusterTotalList,NoiseList,weight=224,height=224):
  273.         self.MapImg.clear()
  274.         X_max = self.MaxDistance * math.cos(math.radians(45))
  275.         Y_max = self.MaxDistance * math.cos(math.radians(45))
  276.         for ClusterInedex in range(len(ClusterTotalList)):
  277.             g = int((ClusterInedex / len(ClusterTotalList)) * 255)
  278.             b = int(((len(ClusterTotalList) - ClusterInedex) / len(ClusterTotalList)) * 255)
  279.             for data in ClusterTotalList[ClusterInedex].ClusterList:
  280.                 x,y = data.ToRectangularCoordinates()
  281.                 x = int(x / X_max * weight / 2 + weight / 2)
  282.                 y = int(y / Y_max * height / 2 + height / 2)
  283.                 self.MapImg.draw_line(x,y,x,y,(255,g,b),thickness = 3)
  284.         for data in NoiseList:
  285.             x,y = data.ToRectangularCoordinates()
  286.             x = int(x / X_max * weight / 2 + weight / 2)
  287.             y = int(y / Y_max * height / 2 + height / 2)
  288.             self.MapImg.draw_line(x,y,x,y,(255,0,0),thickness = 3)
  289.         return self.MapImg
  290.    
  291.     def CreatAveragRadarDataMapping(self,ClusterTotalList,Dbscan,weight=224,height=224):
  292.         MaxIndex = 2
  293.         self.MapImg.clear()
  294.         X_max = self.MaxDistance * math.cos(math.radians(45))
  295.         Y_max = self.MaxDistance * math.cos(math.radians(45))
  296.         for Cluster in ClusterTotalList:
  297.             x,y = Cluster.AverageRadarData.ToRectangularCoordinates()
  298.             x = int(x / X_max * weight / 2 + weight / 2)
  299.             y = int(y / Y_max * height / 2 + height / 2)
  300.             self.MapImg.draw_line(x,y,x,y,(255,255,255),thickness = 3)
  301.         Dbscan.SortByVariance_angle()
  302.         if len(ClusterTotalList) < 2:
  303.             MaxIndex = len(ClusterTotalList)
  304.         for i in range(MaxIndex):
  305.             x,y = ClusterTotalList[i].AverageRadarData.ToRectangularCoordinates()
  306.             x = int(x / X_max * weight / 2 + weight / 2)
  307.             y = int(y / Y_max * height / 2 + height / 2)
  308.             self.MapImg.draw_circle(x,y,10,(255,0,0),thickness = 3)
  309.         Dbscan.SortByVariance_distance()
  310.         for i in range(MaxIndex):
  311.             x,y = ClusterTotalList[i].AverageRadarData.ToRectangularCoordinates()
  312.             x = int(x / X_max * weight / 2 + weight / 2)
  313.             y = int(y / Y_max * height / 2 + height / 2)
  314.             self.MapImg.draw_circle(x,y,10,(0,255,0),thickness = 3)
  315.         Dbscan.SortByCluster_size()
  316.         for i in range(MaxIndex):
  317.             x,y = ClusterTotalList[i].AverageRadarData.ToRectangularCoordinates()
  318.             x = int(x / X_max * weight / 2 + weight / 2)
  319.             y = int(y / Y_max * height / 2 + height / 2)
  320.             self.MapImg.draw_circle(x,y,10,(0,0,255),thickness = 3)
  321.         return self.MapImg
  322.     def SetScope(self,minangle,maxangle,distance=500):
  323.         minangle = int(minangle)
  324.         maxangle = int(maxangle)
  325.         distance = int(distance)
  326.         if minangle < maxangle and minangle < 360 and maxangle < 720:
  327.             if minangle < 0:
  328.                 minangle = 0
  329.             if maxangle > 360 and maxangle-360 > minangle:
  330.                 maxangle = 360
  331.             self.MinAngle = minangle
  332.             self.MaxAngle = maxangle
  333.         if distance > 0 :
  334.             self.MaxDistance = distance
  335.         return self.MinAngle,self.MaxAngle,self.MaxDistance
  336.     def GetScope(self):
  337.         return self.MinAngle,self.MaxAngle,self.MaxDistance
  338.             
  339. #Radar = RadarDriver(10,11,31,50000,69)
  340. #Radar.EnableRplidar()
  341. #while True:
  342.     #Radar.ExpressGetData(10)
  343.     #DataList = Radar.ReadRadarData()
  344.     #for data in DataList:
  345.         #data.PrintRadarData()
  346.         #print(data.ToBytes())
复制代码
回复 支持 反对 送花

使用道具 举报

该用户从未签到

1

主题

33

回帖

109

积分

注册会员

积分
109
 楼主| 发表于 2023-10-9 15:06:52 | 显示全部楼层
照片拍摄驱动代码
  1. # Untitled - By: CaiZhipeng - 周日 7月 16 2023
  2. import os, sensor, utime, lcd
  3. class TakePhotoDriver:
  4.     def __init__(self, DataNum, DataName, FileName):
  5.         self.datanum = DataNum
  6.         self.dataname = DataName
  7.         self.filename = FileName
  8.         self.nownum = 1
  9.         lcd.init(freq=15000000)
  10.     def rename_files_in_directory(self,path):
  11.         files = os.listdir(path)
  12.         jpg_files = [f for f in files if f.endswith('.jpg') and f.split('.')[0].isdigit()]
  13.         jpg_files = sorted(jpg_files, key=lambda x: int(x.split('.')[0]))
  14.         for idx, file in enumerate(jpg_files, start=1):
  15.             old_file_path = "{}/{}".format(path, file)
  16.             new_file_path = "{}/{}.jpg".format(path, idx)
  17.             if old_file_path != new_file_path:
  18.                 os.rename(old_file_path, new_file_path)
  19.     def InitDataFile(self,modes = 1):
  20.         if not "TrainData" in os.listdir("/sd"):
  21.             os.mkdir("/sd/TrainData")
  22.         if not self.filename in os.listdir("/sd/TrainData"):
  23.             os.mkdir("/sd/TrainData/%s" % self.filename)
  24.         if not self.dataname in os.listdir("/sd/TrainData/%s" % self.filename):
  25.             os.mkdir("/sd/TrainData/{}/{}".format(self.filename, self.dataname))
  26.         path = "/sd/TrainData/{}/{}".format(self.filename, self.dataname)
  27.         if modes==1:
  28.             self.rename_files_in_directory(path)
  29.         files = os.listdir(path)
  30.         jpg_files = [f for f in files if f.endswith('.jpg') and f.split('.')[0].isdigit()]
  31.         max_index = 0
  32.         for f in jpg_files:
  33.             if f.endswith('.jpg'):
  34.                 index = int(f.split('.')[0])
  35.                 max_index = max(index, max_index)
  36.         self.nownum = max_index + 1
  37.     def TakePhoto(self,img = None,fliename = -1):
  38.         if self.nownum < self.datanum:
  39.             if img:
  40.                 if fliename == -1:
  41.                     img.save("/sd/TrainData/{}/{}/{}.jpg".format(self.filename, self.dataname, self.nownum))
  42.                 else:
  43.                     img.save("/sd/TrainData/{}/{}/{}.jpg".format(self.filename, self.dataname, fliename))
  44.             else:
  45.                 if fliename == -1:
  46.                     sensor.snapshot().save("/sd/TrainData/{}/{}/{}.jpg".format(self.filename, self.dataname, self.nownum))
  47.                 else:
  48.                     sensor.snapshot().save("/sd/TrainData/{}/{}/{}.jpg".format(self.filename, self.dataname, fliename))
  49.             utime.sleep_ms(5)
  50.             self.nownum += 1
  51.     def ShowInformation(self):
  52.         if self.datanum - self.nownum > 0:
  53.             ShowImg = sensor.snapshot()
  54.             ShowImg.draw_string(0,0,self.filename+"/"+self.dataname,(255,0,0))
  55.             ShowImg.draw_string(0,20,"NeedNum:{}/{}".format(self.nownum, self.datanum),(255,0,0))
  56.             lcd.display(ShowImg)
  57.         else:
  58.             lcd.draw_string(110, 120, "Data Is OK", lcd.BLACK, lcd.WHITE)
复制代码
回复 支持 反对 送花

使用道具 举报

该用户从未签到

1

主题

33

回帖

109

积分

注册会员

积分
109
 楼主| 发表于 2023-10-9 15:07:37 | 显示全部楼层
串口飞机通讯驱动代码
  1. # RadarDriver - By: CaiZhipeng - 周二 6月 27 2023
  2. from Driver import UartDriver as UD,TakePhotoDriver as TD,RadarDriver as RD
  3. import sensor,image,lcd,time,gc, sys, os
  4. import KPU as kpu
  5. sensor.reset()
  6. sensor.set_pixformat(sensor.RGB565)
  7. sensor.set_framesize(sensor.QVGA)
  8. sensor.skip_frames(time = 2000)
  9. sensor.set_windowing((224, 224))
  10. sensor.set_vflip(1)
  11. #lcd.init(freq=15000000)
  12. labels = ['FlightPark']
  13. anchors = [3.83, 3.58, 3.47, 3.41, 3.25, 3.25, 2.5, 2.5, 2.84, 2.84]
  14. ParkingTask = kpu.load("/sd/Models/Parking.kmodel")
  15. ParkingNetwork = kpu.init_yolo2(ParkingTask, 0.4, 0.3, 5, anchors)
  16. UartToStc32 = UD.UartDriver(6, 7,[0x4e,0x35],[0x4e,0x35])#rx tx 发送帧头 接收帧头
  17. MyRadar = RD.RadarDriver(10, 11, 31, 50000, 70)
  18. MyRadar.EnableRplidar()
  19. MyData = TD.TakePhotoDriver(DataNum = 200, DataName = "Radar", FileName = "2021Game")
  20. MyData.InitDataFile()
  21. def ToBytes(num):
  22.     num_H = (num >> 8) & 0xFF
  23.     num_L = num & 0xFF
  24.     return [num_H, num_L]
  25. def JoinBytes(Bytes):
  26.     low_byte = Bytes[1]
  27.     high_byte = Bytes[0]
  28.     return (high_byte << 8) | low_byte
  29. def GetMinDistance(Radar):
  30.     Radar.ExpressGetData(10)
  31.     DataList = Radar.ReadRadarData()
  32.     if DataList:
  33.         min_radar_data = min(DataList, key=lambda radar_data: radar_data.distance)
  34.         return min_radar_data.ToBytes()
  35.     else:
  36.         return [0xFF,0xFF,0xFF,0xFF]
  37. def SetAngleScope(Scope,Radar):
  38.     MinAngle = JoinBytes(Scope[0:2])
  39.     MaxAngle = JoinBytes(Scope[2:4])
  40.     Maxdistance = JoinBytes(Scope[4:6])
  41.     Radar.SetScope(int(MinAngle),(MaxAngle))
  42. def GetAngleScope(Radar):
  43.     minangle,maxangle,maxdistance = Radar.GetScope()
  44.     return ToBytes(minangle)+ToBytes(maxangle)+ToBytes(maxdistance)
  45. def FindfrequentBarCode(List):
  46.     counter = {}
  47.     for s in List:
  48.         if s not in counter:
  49.             counter[s] = 0
  50.         counter[s] += 1
  51.     Frequentstr = max(counter, key=counter.get)
  52.     return int(Frequentstr)
  53. def IdentifyBarCode(Batch,TimeOut):
  54.     timeout = TimeOut
  55.     DataList = []
  56.     while(len(DataList) < Batch and timeout > 0):
  57.         img = sensor.snapshot()
  58.         barcodes = img.find_barcodes()
  59.         if barcodes:
  60.             for barcode in barcodes:
  61.                 barcodeData = barcode.payload()
  62.                 (x, y, w, h) = barcode.rect()
  63.                 #img.draw_rectangle(barcode.rect())
  64.                 #img.draw_string(x, y, barcodeData, color=(0,255,0), scale=1)
  65.                 #lcd.display(img)
  66.                 DataList = DataList + [barcodeData]
  67.         else:
  68.             timeout -= 1
  69.     if len(DataList) > Batch//2:
  70.         return FindfrequentBarCode(DataList)
  71.     return -1
  72. def BarcodeTask(Uart,Radar):
  73.     Data = [0x01]
  74.     #IdentifyResult = IdentifyBarCode(10,5)
  75.     #if IdentifyResult == -1:
  76.     Data = Data + [0x00]
  77.     Result = GetMinDistance(Radar)
  78.     Data = Data + Result
  79.     Scope = GetAngleScope(Radar)
  80.     Data = Data + Scope
  81.     Uart.SendData(Data)
  82. def CalculateCenter(rect):
  83.     x, y, width, height = rect
  84.     center_x = x + width // 2
  85.     center_y = y + height // 2
  86.     return [center_x,center_y]
  87. def AverageCoordinate(List):
  88.     x_List, y_List = zip(*List)
  89.     x_avg = sum(x_List) / len(x_List)
  90.     y_avg = sum(y_List) / len(y_List)
  91.     return [x_avg,y_avg]
  92. #Batch:识别Batch帧的数据平均成一帧 TimeOut:尝试TimeOut次未达到收集不齐Batch帧率,收集多少算多少
  93. def SearchPark(YoloV2Task, Batch, TimeOut):
  94.     ResultList = []
  95.     timeout = TimeOut
  96.     while(len(ResultList) < Batch and timeout > 0):
  97.         img = sensor.snapshot()
  98.         SearchResults = kpu.run_yolo2(YoloV2Task,img)
  99.         if SearchResults:
  100.             timeout = TimeOut
  101.             for Result in SearchResults:
  102.                 img.draw_rectangle(Result.rect())
  103.                 Coordinate = CalculateCenter(Result.rect())
  104.                 ResultList.append(Coordinate)
  105.         #lcd.display(img)
  106.         timeout -= 1
  107.     if ResultList:
  108.         return ResultList
  109.     else:
  110.         return [0xff,0xff]
  111. def SearchParkTask(MyUart):
  112.     Data = [0x02]#发送时带模式号
  113.     ParkingList = SearchPark(ParkingTask, 1, 10)
  114.     if ParkingList[0] != 0xff:
  115.         ParkImgCoordinate = AverageCoordinate(ParkingList)
  116.     else:
  117.         ParkImgCoordinate = ParkingList
  118.     #ParkCoordinate = [(int)(ParkImgCoordinate[0]-112)//1,(int)(112-ParkImgCoordinate[1])//1] # 计算以最中心点为原点的坐标
  119.     ParkCoordinate = [(int)(ParkImgCoordinate[0]),(int)(ParkImgCoordinate[1])]
  120.     Data = Data + ParkCoordinate
  121.     MyUart.SendData(Data)
  122. # Batch:识别多少次 TimeOut:识别不到重试次数
  123. def JudgeColorBlobs(Batch, TimeOut):
  124.     Color = (37, 95, -28, -6, -39, 29)
  125.     ColorRoi = (54,54,112,112)
  126.     timeout = TimeOut
  127.     SuccessCount = 0
  128.     while(SuccessCount < Batch and timeout > 0):
  129.         Picture = sensor.snapshot()
  130.         ColorBlobs = Picture.find_blobs([Color],roi=ColorRoi, x_stride = 5,y_stride = 5,pixels_threshold=50,merge=True)
  131.         if ColorBlobs:
  132.             SuccessCount += 1
  133.         else:
  134.             timeout -= 1
  135.     if SuccessCount == Batch:
  136.         return 1
  137.     return 0
  138. def JudgeColorTask(MyUart):
  139.     Data = [0x03]#发送时带模式号
  140.     Result = JudgeColorBlobs(5,10)
  141.     Data = Data + [Result]
  142.     MyUart.SendData(Data)
  143. OldRevDatas = [0x00]
  144. Count = 0
  145. while True:
  146.     RevDatas = UartToStc32.ReadData()# 串口读到的模式标志为是持久性的 stc发送一次改变模式 直到下一次收到数据后
  147.     if RevDatas:
  148.         RevCmd = RevDatas[0]
  149.     if RevCmd != 0x00 and RevCmd != 0x11 and RevCmd != 0x01 and RevCmd != 0x02 and RevCmd != 0x03 and RevCmd != 0x0F and RevCmd != 0xF0:
  150.         UartToStc32.RcvData = OldRevDatas
  151.     if RevCmd == 0x01:
  152.         BarcodeTask(UartToStc32,MyRadar)
  153.     elif RevCmd == 0x11:
  154.         if len(RevDatas)>=7:
  155.             SetAngleScope(RevDatas[1:7],MyRadar)
  156.         UartToStc32.RcvData = [0x01]
  157.     elif RevCmd == 0x02:
  158.         MyRadar.PauseScan()
  159.         SearchParkTask(UartToStc32)
  160.     elif RevCmd == 0x03:
  161.         MyRadar.PauseScan()
  162.         JudgeColorTask(UartToStc32)
  163.     elif RevCmd == 0x0F:
  164.         MyData.TakePhoto()
  165.         UartToStc32.SendData([0x0F]+ToBytes(MyData.datanum-MyData.nownum+1))
  166.         UartToStc32.RcvData = OldRevDatas
  167.     elif RevCmd == 0x0E:
  168.         MapImg = MyRadar.CreatMapping()
  169.         MyData.TakePhoto(img = MapImg)
  170.         UartToStc32.SendData([0x0E]+ToBytes(MyData.datanum-MyData.nownum+1))
  171.         UartToStc32.RcvData = OldRevDatas
  172.     elif RevCmd == 0x00:
  173.         Count += 1
  174.         MyRadar.PauseScan()
  175.         if Count >= 50:
  176.             Count = 0
  177.             UartToStc32.SendData([0x00,0x00,0x00])# 停机
  178.     OldRevDatas = RevDatas[:]
  179. gc.collect()
复制代码
回复 支持 反对 送花

使用道具 举报

该用户从未签到

1

主题

33

回帖

109

积分

注册会员

积分
109
 楼主| 发表于 2023-10-9 15:08:27 | 显示全部楼层
所使用K210原理图
截图202310091508202352.jpg
回复 支持 反对 送花

使用道具 举报

该用户从未签到

1

主题

33

回帖

109

积分

注册会员

积分
109
 楼主| 发表于 2023-10-9 15:08:45 | 显示全部楼层
规格尺寸图,方便打板
截图202310091508333262.jpg
回复 支持 反对 送花

使用道具 举报

该用户从未签到

1

主题

33

回帖

109

积分

注册会员

积分
109
 楼主| 发表于 2023-10-9 15:09:43 | 显示全部楼层
备赛通讯文档(MARKDOWN格式)
1. 数据帧基本格式(帧头+模式)


| 发送 | 0x4e,0x35(头)0x35 0x4e(尾) |
| ---- | ---------------------------- |
| 接收 | 0x4e,0x35                    |
| 模式 | 0x00/0x01/0x02               |

   **接收/发送帧头可修改**

   ```python
UartToStc32 = UD.UartDriver(6, 7,[0x4e,0x35],[0x4e,0x35])#rx tx 发送帧头 接收帧头
   ```

2. 停机坪任务任务 0x02(0x4e 0x35 0x02)

   - 未找到停机坪:`0xff,0xff`
     eg.`0x4e 0x35 0x02 0xff 0xff 0x35 0x4e  `
   - 找到停机坪:`x,y`
     x:0~224 y:0~244 以左上角为原点向左向下分别为x,y正轴
     eg.`0x4E 0x35 0x02 0x9D 0x6C 0x35 0x4e
     表示坐标:157 108`

3. 颜色判断任务 0x03(0x4e 0x35 0x03)

   - 识别到草地`0x01`
     eg.`0x4E 0x35 0x03 0x01 0x35 0x4e `
   - 没有识别到草地`0x00`
     eg.`0x4E 0x35 0x03 0x00 0x35 0x4e`

4. 停机模式 0x00(默认为停机模式)(0x4e 0x35 0x00)
   返回`0x4E 0x35 0x00 0x00 0x00 0x35 0x4e `

# 水平方向K210与stc串口通讯协议

1. 数据帧基本格式(帧头+模式)


    | 发送 | 0x4e,0x35 |
    | --- | --- |
    | 接收 | 0x4e,0x35 |
    | 模式 | 0x00/0x01 |
   
    **接收/发送帧头可修改**
   
    ```python
    UartToStc32 = UD.UartDriver(6, 7,[0x4e,0x35],[0x4e,0x35])#rx tx 发送帧头 接收帧头
    ```

2. 识别条形码任务0x01(0x4e 0x35 0x01)

   - 识别到条形码返回条形码数据(0x01 data)

     eg.`0x4E 0x35 0x01 0x01 0x03 0x35 0x4e`

     识别到了条形码,数字为3

   - 未识别到条形码返回最近的雷达信息(0x00 angle_H, angle_L, distance_H, distance_L,min_scope_angle_H,min_scope_angle_L,max_scope_angle_H,max_scope_angle_L)
     eg.`0x4E 0x35 0x01 0x00 0x00 0xB3 0x00 0x16 0x00 0x00 0x01 0x0E 0x35 0x4e`

       未识别到了条形码,最近障碍为263° 16cm处(此时从0到270°中的最小值)

3. 停机模式 0x00(默认为停机模式)(0x4e 0x35 0x00)
   返回`0x4E 0x35 0x00 0x00 0x00 0x35 0x4e`

  # 辅助功能

  1. 拍照(0x4e 0x35 0x0F)
     进行拍照并存入SD卡返回剩余拍照的数量eg.0x4e 0x35 0x0F 0x02 0x53 表示剩余595张图片

     ```python
     MyData = TrainDataCollection(DataNum = 800, DataName = "Parking", FileName = "2021Game")//拍照数量/二级文件夹名称/一级文件夹名称
     ```

     

  2. 拍照(0x4e 0x35 0x11min_scope_angle_H,min_scope_angle_L,max_scope_angle_H,max_scope_angle_L)

     eg.`0x4E 0x35 0x11 0x00 0x00 0x01 0x0E`修改扫描范围为0到270°
回复 支持 反对 送花

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|手机版|深圳国芯人工智能有限公司 ( 粤ICP备2022108929号-2 )

GMT+8, 2024-4-29 12:12 , Processed in 0.088237 second(s), 65 queries .

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表