AirSim 自动驾驶仿真 (2-3) python控制无人机 win10
阅读原文时间:2023年07月08日阅读:1

1首先搭建好环境

参考

2 python控制

https://blog.csdn.net/Zhaoxi_Li/article/details/108002544

官方代码位置

自己pythonj教程

https://www.cnblogs.com/gooutlook/p/15851233.html

3开启环境

无人机模式运行

加载在地图

游戏模式

4运行python代码

原厂目录下运行没问题

自己的脚本要添加airssim路径 否警报错

手动添加airsim遍历路径

import sys
#sys.path.append("/home/dongdong/3Code/Airsim/AirSim/PythonClient") #ubnutu
sys.path.append("E:/v0_Project/V2_labray/v4_Airsim/v0_AirsimAPI/Airsim171/PythonClient")#win10

#import setup_path #导入库路径 被代替

 启动

# In settings.json first activate computer vision mode:

#https://github.com/Microsoft/AirSim/blob/master/docs/image_apis.md#computer-vision-mode

#基本集成了飞机所有的控制,图像转换到opencv

#import setup_path
#导入自己的airsim编译路径
import sys
#sys.path.append("/home/dongdong/3Code/Airsim/AirSim/PythonClient") #ubnutu
sys.path.append("E:/v0_Project/V2_labray/v4_Airsim/v0_AirsimAPI/Airsim171/PythonClient")#win10

import airsim

import cv2
import time
import sys

import pprint
import numpy as np
import os
import tempfile

#选择要采集的图像类型
cameraType = "scene" #正常画面 12fps 1920*1080

cameraTypeMap = {
"depth": airsim.ImageType.DepthVis,#黑白景深图像
"segmentation": airsim.ImageType.Segmentation,#彩色目标分割图像
"seg": airsim.ImageType.Segmentation,#彩色目标分割图像
"scene": airsim.ImageType.Scene,#正常图像
"disparity": airsim.ImageType.DisparityNormalized,
"normals": airsim.ImageType.SurfaceNormals
}

#选择摄像头
'''
---camera_name_val: airsim自带的simple flight,每个无人机自带5个相机,其ID 与相机分别对应如下:
0 = front_center
1 = front_right
2 = front_left
3 = bottom_center #下视画面
4 = back_center
'''
cameraUse="3"

连接到Airsim仿真器

#client = airsim.MultirotorClient()#默认本机
client = airsim.MultirotorClient("127.0.0.1")#局域网主机IP

每1秒检查一次连接状态,并在控制台中报告,以便用户可以查看连接的进度(应该是开启了个线程,因为只是调用了一次)

client.confirmConnection()
#开启api控制,默认是false,有的设备不允许用API控制,所以用isApiControlEnabled可以查看是否可以用API控制
client.enableApiControl(True)

#获取无人飞机的所有数据
Flystate = client.getMultirotorState()
#s = pprint.pformat(state)
#print("state: %s" % s)

#从所有数据扣出 position坐标 北偏地坐标系
position1=Flystate.kinematics_estimated.position
#print(position1)
print("position位置")
print(position1.x_val)
print(position1.y_val)
print(position1.z_val) #负为上升,北偏地坐标系

#从所有数据扣出 gps_data数据 经纬度
gps_data=Flystate.gps_location
#print(gps_data)
print("GPS数据")
print(gps_data.altitude)
print(gps_data.latitude)
print(gps_data.longitude)

#单独获取当前位置GPS数据的api
#gps_data = client.getGpsData()
#s = pprint.pformat(gps_data)
#print("gps_data: %s" % s)

#按键等待
airsim.wait_key('安任何按键,开始采集起飞')
#起飞
landed = client.getMultirotorState().landed_state
if landed == airsim.LandedState.Landed:
print("taking off…")
client.takeoffAsync().join()
else:
print("already flying…")
client.hoverAsync().join()

#悬停
client.hoverAsync().join()

#飞行代码测试 有两种模式 定点飞和恒定速度飞 注销开启测试
'''
----------------------------飞行控制模式1----------------------------------
(1)坐标点控制
初始化原点,化点为x,y,z是全局坐标位置,velocity是速度。
实现的效果是以 1m/s 的速度飞到 (5, 0) 点,3m 高的位置。
.join() 后缀的意思是程序在这里等待直到任务完成,也就是四旋翼到达目标位置点,同时到达设置的高度。
如果不加 .join() 后缀,则不用等待任务是否完成,函数直接返回,程序继续往下执行。

'''

'''
airsim.wait_key('Press any key to fly1')
client.moveToZAsync(-3, 1).join() # 上升到3m高度
client.moveToPositionAsync(5, 0, -3, 1).join() # 飞到(5,0)点坐标 高度3米 速度1m/s
client.moveToPositionAsync(5, 5, -3, 1).join() # 飞到(5,5)点坐标 高度3米 速度1m/s
'''

'''
----------------------------飞行控制模式2----------------------------------
(2) 速度运动控制模式
#全局坐标系是北东地坐标系
vx:全局坐标系下x轴方向上的速度
vy:全局坐标系下y轴方向上的速度
z:全局坐标系下的高度
duration:持续的时间,单位:秒
'''
'''
airsim.wait_key('Press any key to fly2')
client.moveToZAsync(-6, 1).join() # 上升到6m高度
client.moveByVelocityZAsync(1, 0, -6, 3).join() # 第三阶段:以1m/s速度向x前飞3秒钟 -6米高度
client.moveByVelocityZAsync(0, 1, -6, 3).join() # 第三阶段:以1m/s速度向y前飞3秒钟 -6米高度
'''

#按键等待
airsim.wait_key('按任何按键,开始采集图像,记得修改相机编号和图像类型')
client.moveToZAsync(-10, 10).join() #飞到10米高 10米速度
#client.moveByVelocityZAsync(0, 1, -10, 9) # 以y轴1m/s速度向y前飞9秒钟 10米高度 为了移动采集画面,不用等待join() 结束
client.moveByVelocityZAsync(100, 0, -10, 2) #2米/妙速度 10米高度 飞到 (100 ,0)位置

#---------------------画图输出帧率字体格式------------------
fontFace = cv2.FONT_HERSHEY_SIMPLEX
fontScale = 0.5
thickness = 2
textSize, baseline = cv2.getTextSize("FPS", fontFace, fontScale, thickness)
print (textSize)
textOrg = (10, 10 + textSize[1])
frameCount = 0
#startTime=time.clock()
startTime=0
fps = 0
#---------------------画图输出帧率字体格式------------------

cv2.namedWindow("Airsim", cv2.WINDOW_NORMAL)

while True:
# because this method returns std::vector, msgpack decides to encode it as a string unfortunately.
rawImage = client.simGetImage(cameraUse, cameraTypeMap[cameraType])#获取airsim原始格式视频数据
if (rawImage == None):
print("图像为空")
#sys.exit(0)
continue
else:
png = cv2.imdecode(airsim.string_to_uint8_array(rawImage), cv2.IMREAD_UNCHANGED)#AIRSIM转换数据OPENCV
cv2.putText(png,'FPS ' + str(fps),textOrg, fontFace, fontScale,(255,0,255),thickness)
cv2.imshow("Airsim", png)

frameCount  = frameCount  + 1  
#endTime=time.clock()  
endTime=0  
diff = endTime - startTime  
if (diff > 1):  
    fps = frameCount  
    frameCount = 0  
    startTime = endTime

key = cv2.waitKey(1) & 0xFF;  
if (key == 27 or key == ord('q') or key == ord('Q')):  
    break;

cv2.destroyAllWindows()

#降落
landed = client.getMultirotorState().landed_state
if landed == airsim.LandedState.Landed:
print("already landed…")
else:
print("landing…")
client.landAsync().join()

上锁

client.armDisarm(False)
client.reset()
#关闭控制
client.enableApiControl(False)

更多其他控制

https://www.cnblogs.com/gooutlook/p/15851233.html

其他

默认天气效果是关闭的,如果想启用天气效果,首先调用函数simEnableWeather(True)

各种天气效果可以使用simSetWeatherParameter方法来实现,输入是一个参数结构体WeatherParameter,例如:

client.simSetWeatherParameter(airsim.WeatherParameter.Rain, 0.25);

 第二个参数取值范围是0-1,第一个参数有如下属性。 

class WeatherParameter:
Rain = 0
Roadwetness = 1
Snow = 2
RoadSnow = 3
MapleLeaf = 4
RoadLeaf = 5
Dust = 6
Fog = 7

注意 RoadwetnessRoadSnow 和 RoadLeaf 效果需要自己添加 材质 。

具体细节可以参考对应示例文件

4.6 坐标系统
All AirSim API uses NED coordinate system, i.e., +X is North, +Y is East and +Z is Down. All units are in SI system. Please note that this is different from coordinate system used internally by Unreal Engine. In Unreal Engine, +Z is up instead of down and length unit is in centimeters instead of meters. AirSim APIs takes care of the appropriate conversions. The starting point of the vehicle is always coordinates (0, 0, 0) in NED system. Thus when converting from Unreal coordinates to NED, we first subtract the starting offset and then scale by 100 for cm to m conversion. The vehicle is spawned in Unreal environment where the Player Start component is placed. There is a setting called OriginGeopoint in settings.json which assigns geographic longitude, longitude and altitude to the Player Start component.

(1) getMultirotorState
调用一次则返回一次无人机状态。该状态包括碰撞(collision)、估计运动学(estimated kinematics)(即通过融合传感器计算的运动学)和时间戳(timestamp)(从纪元开始的纳秒)。运动学包含6个量:位置(position)、方向(orientation)、线速度和角速度、线加速度和角加速度。请注意,simple_slight目前不支持状态估计器,这意味着对于simple_flight飞行,估计和地面真实运动学值是相同的。然而,除了角加速度,估计的运动学可用于PX4。所有的量都在NED坐标系中,除了角速度和加速度在body框架中之外,在世界坐标系中使用国际单位制。
————————————————

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章