forked from linxiaobo110/QuadrotorFly
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCamDown.py
371 lines (343 loc) · 15.2 KB
/
CamDown.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""'used for manage and generate cam data with set ground-image.
it is a virtual camera
By xiaobo
Contact [email protected]
Created on 十一月 21 20:29 2019
"""
# Copyright (C)
#
# This file is part of quadrotorfly
#
# GWpy is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# GWpy is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GWpy. If not, see <http://www.gnu.org/licenses/>.
import numpy as np
import CommonFunctions as Cf
import cv2
from enum import Enum
import enum
from numba import jit
"""
********************************************************************************************************
**-------------------------------------------------------------------------------------------------------
** Compiler : python 3.6
** Module Name: CamDown
** Module Date: 2019/11/21
** Module Auth: xiaobo
** Version : V0.1
** Description: a virtual camera looking down
**-------------------------------------------------------------------------------------------------------
** Reversion :
** Modified By:
** Date :
** Content :
** Notes :
********************************************************************************************************/
"""
class CamDownPara(Enum):
Render_Mode_Mem = enum.auto()
Render_Mode_Cpu = enum.auto()
Render_Mode_Gpu = enum.auto()
class CamDown(object):
def __init__(self, img_horizon=400, img_vertical=400, img_depth=3,
sensor_horizon=4., sensor_vertical=4., cam_focal=2.36,
ground_img_path='./Data/groundImgWood.jpg',
small_ground_img_path='./Data/groundImgSmall.jpg',
small_land_img_path='./Data/landingMark.jpg',
render_mode=CamDownPara.Render_Mode_Mem):
"""
****************** horizon ****************
*
v
e
r
t
i
c
a
l
********************************************
:param img_horizon: the num of vertical pixes of the image which is generated by sensor
:param img_vertical: the num of horizon pixes of the image which is generated by sensor
:param img_depth: the num of chanel the image, i.e. rgb is 3
:param sensor_horizon: mm, the height of the active area of the sensor
:param sensor_vertical: mm, the width of the active area of the sensor
:param cam_focal: mm, the focal of the lens of the camera
"""
self.imgHorizon = img_horizon
self.imgVertical = img_vertical
self.imgDepth = img_depth
self.skx = sensor_horizon * 1. / img_horizon # skx is sensor_k_x
self.sky = sensor_vertical * 1. / img_vertical # skx is sensor_k_y
self.sx0 = sensor_horizon * 0.5
self.sy0 = sensor_vertical * 0.5
self.camFocal = cam_focal
self.axCamImgArr = np.zeros([self.imgVertical * self.imgHorizon, 3])
self.pixCamImg = np.zeros([self.imgVertical, self.imgHorizon, self.imgDepth], dtype=np.uint8)
self.groundImgPath = ground_img_path
self.groundImg = None
# small image
self.smallGroundImgPath = small_ground_img_path
self.smallLandingImgPath = small_land_img_path
self.smallGroundImg = None
self.smallLandingImg = None
self.smallImgHorizon = 7854
self.smallImgVertical = 3490
self.smallLandingImgHos = 315
self.smallLandingImgVet = 315
self.renderMode = render_mode
# init the array
for ii in range(self.imgVertical):
for j in range(self.imgHorizon):
self.axCamImgArr[ii * self.imgHorizon + j, :] = [ii, j, 1]
def load_ground_img(self):
if self.renderMode == CamDownPara.Render_Mode_Mem:
if self.groundImg is not None:
del self.groundImg
else:
self.groundImg = cv2.imread(self.groundImgPath)
elif self.renderMode == CamDownPara.Render_Mode_Cpu:
if self.smallGroundImg is not None:
del self.smallGroundImg
else:
self.smallGroundImg = cv2.imread(self.smallGroundImgPath)
# if read success, get size of image
if self.smallGroundImg is not None:
self.smallImgVertical, self.smallImgHorizon = self.smallGroundImg.shape
elif self.renderMode == CamDownPara.Render_Mode_Gpu:
if self.smallGroundImg is not None:
del self.smallGroundImg
else:
self.smallGroundImg = cv2.imread(self.smallGroundImgPath)
self.smallLandingImg = cv2.imread(self.smallLandingImgPath)
# if read success, get size of image
if self.smallGroundImg is not None:
self.smallImgVertical, self.smallImgHorizon, _ = self.smallGroundImg.shape
if self.smallLandingImg is not None:
self.smallLandingImgVet, self.smallLandingImgHos, _ = self.smallLandingImg.shape
def get_img_by_state(self, pos, att):
m_img2sensor = np.array([[self.skx, 0, self.sx0],
[0, -self.sky, -self.sy0],
[0, 0, 1]])
m_sensor2cam = np.array([[pos[2] / self.camFocal, 0, self.imgVertical / 2],
[0, pos[2] / self.camFocal, -self.imgHorizon / 2],
[0, 0, 1]])
m_cam2world = Cf.get_rotation_matrix(att)
m_cam2world[0:2, 2] = pos[0:2]
m_cam2world[2, :] = np.array([0, 0, 1])
m_trans = m_cam2world.dot(m_sensor2cam.dot(m_img2sensor))
if self.renderMode == CamDownPara.Render_Mode_Mem:
ax_real = m_trans.dot(self.axCamImgArr.transpose()).transpose()
for ii in range(self.imgVertical):
for j in range(self.imgHorizon):
self.pixCamImg[ii, j, :] = self.groundImg[int(ax_real[ii * self.imgHorizon + j, 0]),
int(ax_real[ii * self.imgHorizon + j, 1] + 10000), :]
elif self.renderMode == CamDownPara.Render_Mode_Cpu:
ax_real = m_trans.dot(self.axCamImgArr.transpose()).transpose()
for ii in range(self.imgVertical):
for j in range(self.imgHorizon):
ax_vertical = int(ax_real[ii * self.imgHorizon + j, 0]) % self.smallImgVertical
ax_horizon = int(ax_real[ii * self.imgHorizon + j, 1] + 10000) % self.smallImgHorizon
self.pixCamImg[ii, j, :] = self.smallGroundImg[ax_vertical, ax_horizon, :]
elif self.renderMode == CamDownPara.Render_Mode_Gpu:
ax_real = m_trans.dot(self.axCamImgArr.transpose()).transpose()
accelerate_img_mapping_gpu(ax_real, self.smallGroundImg, self.smallLandingImg, self.pixCamImg,
self.imgVertical, self.imgHorizon, self.smallImgHorizon, self.smallImgVertical,
self.smallLandingImgHos, self.smallLandingImgVet)
return self.pixCamImg
@jit(nopython=True)
def accelerate_img_mapping_gpu(m_ax_real, m_img_small, m_img_landing, m_img_result,
img_vertical, img_horizon, small_horizon, small_vertical, land_horizon, land_vertical):
"""
# 用来加速映射计算的函数
:param m_ax_real: 映射后的座标
:param m_img_small: 贴图,小图片
:param m_img_result: 目标图像
:param m_img_landing
:param img_vertical: 目标图像高度
:param img_horizon: 目标图像宽度
:param small_horizon: 贴图宽度
:param small_vertical: 贴图高度
:param land_horizon:
:param land_vertical
:return:
"""
land_hos_max = 5000 + land_horizon
land_vet_min = 5000 - land_vertical
for ii in range(img_vertical):
for j in range(img_horizon):
ax_vertical = int(m_ax_real[ii * img_horizon + j, 0])
ax_horizon = int(m_ax_real[ii * img_horizon + j, 1] + 10000)
if (ax_horizon > 5000) and (ax_horizon < land_hos_max) and (ax_vertical > land_vet_min) \
and (ax_vertical < 5000):
ax_horizon = ax_horizon - 5000
ax_vertical = ax_vertical - land_vet_min
m_img_result[ii, j, :] = m_img_landing[ax_vertical, ax_horizon, :]
else:
ax_vertical = ax_vertical % small_vertical
ax_horizon = ax_horizon % small_horizon
m_img_result[ii, j, :] = m_img_small[ax_vertical, ax_horizon, :]
return m_img_result
if __name__ == '__main__':
" used for testing this module"
testFlag = 3
if testFlag == 1:
cam1 = CamDown()
print('init completed!')
cam1.load_ground_img()
print('Load img completed!')
pos_0 = np.array([4251.97508977, -5843.00458236, 227.35483937])
att_0 = np.array([-0.13647458, -0.1990263, 0.27836947])
img1 = cam1.get_img_by_state(pos_0, att_0)
import matplotlib.pyplot as plt
plt.imshow(cam1.pixCamImg / 255)
cv2.imwrite('Data/test.jpg', img1)
elif testFlag == 2:
import matplotlib.pyplot as plt
# import matplotlib as mpl
from QuadrotorFlyModel import QuadModel, QuadSimOpt, QuadParas, StructureType, SimInitType
import MemoryStore
D2R = np.pi / 180
print("PID controller test: ")
uavPara = QuadParas(structure_type=StructureType.quad_x)
simPara = QuadSimOpt(init_mode=SimInitType.fixed, enable_sensor_sys=False,
init_att=np.array([10., -10., 30]), init_pos=np.array([5, -5, 0]))
quad1 = QuadModel(uavPara, simPara)
record = MemoryStore.DataRecord()
record.clear()
step_cnt = 0
# init the camera
cam1 = CamDown()
cam1.load_ground_img()
print('Load img completed!')
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
out1 = cv2.VideoWriter('Data/img/test.avi', fourcc, 1 / quad1.uavPara.ts, (cam1.imgVertical, cam1.imgHorizon))
for i in range(1000):
ref = np.array([0., 0., 1., 0.])
stateTemp = quad1.observe()
# get image
pos_0 = quad1.position * 1000
att_0 = quad1.attitude
img1 = cam1.get_img_by_state(pos_0, att_0)
# file_name = 'Data/img/test_' + str(i) + '.jpg'
# cv2.imwrite(file_name, img1)
out1.write(img1)
action2, oil = quad1.get_controller_pid(stateTemp, ref)
print('action: ', action2)
action2 = np.clip(action2, 0.1, 0.9)
quad1.step(action2)
record.buffer_append((stateTemp, action2))
step_cnt = step_cnt + 1
record.episode_append()
out1.release()
print('Quadrotor structure type', quad1.uavPara.structureType)
# quad1.reset_states()
print('Quadrotor get reward:', quad1.get_reward())
data = record.get_episode_buffer()
bs = data[0]
ba = data[1]
t = range(0, record.count)
# mpl.style.use('seaborn')
fig1 = plt.figure(1)
plt.clf()
plt.subplot(3, 1, 1)
plt.plot(t, bs[t, 6] / D2R, label='roll')
plt.plot(t, bs[t, 7] / D2R, label='pitch')
plt.plot(t, bs[t, 8] / D2R, label='yaw')
plt.ylabel('Attitude $(\circ)$', fontsize=15)
plt.legend(fontsize=15, bbox_to_anchor=(1, 1.05))
plt.subplot(3, 1, 2)
plt.plot(t, bs[t, 0], label='x')
plt.plot(t, bs[t, 1], label='y')
plt.ylabel('Position (m)', fontsize=15)
plt.legend(fontsize=15, bbox_to_anchor=(1, 1.05))
plt.subplot(3, 1, 3)
plt.plot(t, bs[t, 2], label='z')
plt.ylabel('Altitude (m)', fontsize=15)
plt.legend(fontsize=15, bbox_to_anchor=(1, 1.05))
plt.show()
# performance test
elif testFlag == 3:
import matplotlib.pyplot as plt
# import matplotlib as mpl
from QuadrotorFlyModel import QuadModel, QuadSimOpt, QuadParas, StructureType, SimInitType
import MemoryStore
import time
D2R = np.pi / 180
video_write_flag = True
print("PID controller test: ")
uavPara = QuadParas(structure_type=StructureType.quad_x)
simPara = QuadSimOpt(init_mode=SimInitType.fixed, enable_sensor_sys=False,
init_att=np.array([0., 0., 0]), init_pos=np.array([0, -0, 0]))
quad1 = QuadModel(uavPara, simPara)
record = MemoryStore.DataRecord()
record.clear()
step_cnt = 0
# init the camera
cam1 = CamDown(render_mode=CamDownPara.Render_Mode_Gpu)
cam1.load_ground_img()
print('Load img completed!')
if video_write_flag:
v_format = cv2.VideoWriter_fourcc(*'MJPG')
out1 = cv2.VideoWriter('Data/img/test.avi', v_format, 1 / quad1.uavPara.ts, (cam1.imgVertical, cam1.imgHorizon))
for i in range(1000):
if i == 0:
time_start = time.time()
ref = np.array([0., 0., 3., 0.])
stateTemp = quad1.observe()
# get image
pos_0 = quad1.position * 1000
att_0 = quad1.attitude
img1 = cam1.get_img_by_state(pos_0, att_0)
# file_name = 'Data/img/test_' + str(i) + '.jpg'
# cv2.imwrite(file_name, img1)
if video_write_flag:
out1.write(img1)
action2, oil = quad1.get_controller_pid(stateTemp, ref)
print('action: ', action2)
action2 = np.clip(action2, 0.1, 0.9)
quad1.step(action2)
record.buffer_append((stateTemp, action2))
step_cnt = step_cnt + 1
time_end = time.time()
print('time cost:', str(time_end - time_start))
record.episode_append()
if video_write_flag:
out1.release()
print('Quadrotor structure type', quad1.uavPara.structureType)
# quad1.reset_states()
print('Quadrotor get reward:', quad1.get_reward())
data = record.get_episode_buffer()
bs = data[0]
ba = data[1]
t = range(0, record.count)
# mpl.style.use('seaborn')
fig1 = plt.figure(1)
plt.clf()
plt.subplot(3, 1, 1)
plt.plot(t, bs[t, 6] / D2R, label='roll')
plt.plot(t, bs[t, 7] / D2R, label='pitch')
plt.plot(t, bs[t, 8] / D2R, label='yaw')
plt.ylabel('Attitude $(\circ)$', fontsize=15)
plt.legend(fontsize=15, bbox_to_anchor=(1, 1.05))
plt.subplot(3, 1, 2)
plt.plot(t, bs[t, 0], label='x')
plt.plot(t, bs[t, 1], label='y')
plt.ylabel('Position (m)', fontsize=15)
plt.legend(fontsize=15, bbox_to_anchor=(1, 1.05))
plt.subplot(3, 1, 3)
plt.plot(t, bs[t, 2], label='z')
plt.ylabel('Altitude (m)', fontsize=15)
plt.legend(fontsize=15, bbox_to_anchor=(1, 1.05))
plt.show()