Tello内蔵の単眼カメラの画像を、Macbook側で受信し、受信した画像に、その瞬間のTelloの飛行高度を、フレーム画像の左上に文字列埋め込みして、Macbookのウィンドウにリアルタイムに出力してみました。
今回は、各瞬間のフレーム画像に、英語の文字列を埋め込みました。
日本語の文字列を埋め込むためには、OpenCV2のputTextメソッドを、日本語対応させる必要があります。
- OpenCVで日本語フォントを描写する を関数化する
- 【OpenCV】【Python】画像上に日本語のテキストを描画
- OpenCV 3.4 + Python3 フォントファイルを指定して日本語を表示する
なお、putText関数はたくさん引数を従えていますが、各引数の仕様については、次のサイトを参考にしました。
書いたソースコードのコア部分
( Tello機体情報の受信 )
time_of_flight_distance_senser_val = tello.get_distance_tof()
height= tello.get_height()
#### __( 出力するフレーム画像への文字列埋込み )__
>```Python3:
>input_text_1 = "ToF Distane {0} cm".format(time_of_flight_distance_senser_val)
>input_text_2 = "Height {0} cm".format(height)
>
>cv2.putText(img, str(input_text_1), (0, 50), cv2.FONT_HERSHEY_TRIPLEX, 1, (255, 255, 255), 1, cv2.LINE_AA)
>cv2.putText(img, str(input_text_2), (0, 100), cv2.FONT_HERSHEY_TRIPLEX, 1, (255, 255, 255), 1, cv2.LINE_AA)
>```
## ソースコード全文
```Python3:
from timeout_decorator import timeout, TimeoutError
from djitellopy import Tello
import cv2, math, time
import matplotlib.pyplot as plt
TIMEOUT_SEC = 0.1
@timeout(TIMEOUT_SEC)
def input_with_timeout(msg=None):
return input(msg)
tello = Tello()
tello.connect()
tello.streamon()
frame_read = tello.get_frame_read()
# tello.takeoff()
while True:
# In reality you want to display frames in a seperate thread. Otherwise
# they will freeze while the drone moves.
img = frame_read.frame
cv2.imshow("drone", img)
#cv2.imshow('Canny', cv2.Canny(img, 100, 200))
#bitwised_img = cv2.bitwise_not(img)
#cv2.imshow('Bitwised', bitwised_img)
# https://djitellopy.readthedocs.io/en/latest/tello/#djitellopy.tello.Tello.query_battery
time_of_flight_distance_senser_val = tello.get_distance_tof()
input_text_1 = "ToF Distane {0} cm".format(time_of_flight_distance_senser_val)
height= tello.get_height()
input_text_2 = "Height {0} cm".format(height)
# Terminal標準出力
print(input_text_1)
print(input_text_2)
# カメラ画像にTelloの現在高度(ToFセンサ計測距離(cm)、高さ(cm))を埋込む
cv2.putText(img, str(input_text_1), (0, 50), cv2.FONT_HERSHEY_TRIPLEX, 1, (255, 255, 255), 1, cv2.LINE_AA)
cv2.putText(img, str(input_text_2), (0, 100), cv2.FONT_HERSHEY_TRIPLEX, 1, (255, 255, 255), 1, cv2.LINE_AA)
cv2.imshow("Video with Tello Status Info", img)
#plt.imshow(img)
#plt.show()
#output_frame_image_file_name = "dummy"
#cv2.imwrite(output_frame_image_file_name, img)
#次の行(key = cv2.・・・)を削除すると、画像が受信できなくなる。
key = cv2.waitKey(1) & 0xff
try:
msg = input_with_timeout('\n{}秒以内に操作コマンドを入力して下さい :'.format(TIMEOUT_SEC))
print('\n操作コマンド: {} を受信しました。\n'.format(msg))
if msg == "i":
tello.takeoff()
elif msg == "w":
tello.move_forward(30)
elif msg == "s":
tello.move_back(30)
elif msg == "a":
tello.move_left(30)
elif msg == "d":
tello.move_right(30)
elif msg == "e":
tello.rotate_clockwise(30)
elif msg == "q":
tello.rotate_counter_clockwise(30)
elif msg == "r":
tello.move_up(30)
elif msg == "f":
tello.move_down(30)
elif msg == "g":
tello.land()
except TimeoutError:
print('\n操作コマンド入力時間切れ。次のフレーム画像を読み込みます。\n')
tello.land()