Bye Bye Moore

PoCソルジャーな零細事業主が作業メモを残すブログ

RealSense SDK for Pythonを Ubuntu22LTS on Raspi4B で試す その4:深度画像に枠を作ったり文字を入れたり

shuzo-kino.hateblo.jp

OpenCVの方に寄った話になりますが……せっかく深度情報を取れたので情報を書き出してみました。

実際のところ

import pyrealsense2 as rs
import numpy as np
import cv2

conf = rs.config()

width = 1280
height = 720

rect_l_w = int(width      / 4)
rect_l_h = int(height     / 4)
rect_r_w = int(width  * 3 / 4)
rect_r_h = int(height * 3 / 4)

# 高さ情報を取得
conf.enable_stream(rs.stream.depth, width, height, rs.format.z16, 30)

pipe = rs.pipeline()
profile = pipe.start(conf)

x_max = 0
y_max = 0
hight_threshold = 2.0
depth_data = 0.0

while True:
    frames = pipe.wait_for_frames()
    depth_frame = frames.get_depth_frame()

    depth_image = np.asanyarray(depth_frame.get_data())
    #色つきに(これをやらないと、灰色で使いモンにならない)
    depth_colormap = cv2.applyColorMap(cv2.convertScaleAbs(depth_image, alpha=0.08), cv2.COLORMAP_JET)


    depth_data = 0.0
    for x in range(rect_l_w, rect_r_w, 100):
      for y in range(rect_l_h, rect_r_h, 100):
        buff = depth_frame.get_distance(x,y)
        if ( (buff > depth_data) and (buff < hight_threshold)) :
          x_max = x
          y_max = y
          depth_data = buff

    #描画範囲
    cv2.rectangle(depth_colormap, (rect_l_w, rect_l_h ), (rect_r_w, rect_r_h), (0, 255, 0))

    #所定座標
    cv2.drawMarker(depth_colormap, (int(x_max), int(y_max)), (0, 0, 255), markerType=cv2.MARKER_TILTED_CROSS, markerSize=30)

    #数値描画
    point_result = f"{x_max:#4d},{y_max:#4d}, {depth_data:#3f}"
    cv2.putText(depth_colormap, point_result, (rect_l_w - 20, rect_l_h - 20), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 255, 255), thickness=4)

    cv2.imshow('RS',depth_colormap)

    #ESC keyS
    if cv2.waitKey(1) & 0xff == 27:
       cv2.destroyAllWindows()
       break

動かしてみると、こんな感じ
今回の例では2m以上離れたものは弾くように書いているので結果的に2mに近いところにマーカーするようになった