3
8

More than 3 years have passed since last update.

MacとPythonとRealSenseとOpenCVでリアルタイム顔検知

Posted at

RealSenseD435iを触ってみたのでMacでPythonからRealSenseSDKを扱う方法について書く

ひとまず動いたので記念に。
例のごとく記憶を頼りに書くので、漏れてる点などあるかも。

前提

  • macOS Mojave
  • Python 3.7.4
  • OpenCV 4.1.1
  • pyrealsense2

準備

  1. Python3のインストール
  2. JupyterLabのインストール(https://jupyterlab.readthedocs.io/en/stable/#)
  3. OpenCVのインストール pip3 install opencv-python
  4. pyrealsense2のビルド、インストール

ここが一番大変。
https://github.com/IntelRealSense/librealsense/tree/master/wrappers/python
からソースコードをCloneして、cmakeします。
上記URL中にpipのインストールコマンドが提供されているような記載がありますが、MacOSは現時点対応されていません。自力でビルドあるのみです。

ビルドしたら、PATHの設定などを実施。自分はzshなので、vi ~/.zshenvで。
また、librealsense/build/tools/realsense-viewerrealsense-viewerがあるのでこれを実行できればビルドが成功していることを確認できます。

インストールしたらlibrealsense/wrappers/python/examplesにサンプルコードがありますので、その中から、opencv_viewer_example.pyを実行してください。
実行できれば、Python3環境にPyrealsense2がimportできることを確認できます。

場合によっては、Python環境へ.soファイルのシンボリックリンクを手動で配置する必要があるかもしれません。

OpenCVとの連携

まず、JupyterNotebook上からもimportができるか確認しておきます。

importtest.py
import cv2
import pyrealsense2 as rs

print(cv2)
print(rs)

早速、Pyrealsense2のサンプルコードと、OpenCVのサンプルコードを組み合わせて、コードを書きます。

importtest.py
import numpy as np
import cv2
import pyrealsense2 as rs

face_cascade = cv2.CascadeClassifier('/usr/local/lib/python3.7/site-packages/cv2/data/haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('/usr/local/lib/python3.7/site-packages/cv2/data/haarcascade_eye.xml')

# Configure depth and color streams
pipeline = rs.pipeline()
config = rs.config()
config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30)
config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 30)

# Start streaming
pipeline.start(config)

try:
    while True:

        # Wait for a coherent pair of frames: depth and color
        frames = pipeline.wait_for_frames()
        color_frame = frames.get_color_frame()
        depth_frame = frames.get_depth_frame()

        if not depth_frame or not color_frame:
            continue

        img = np.asanyarray(color_frame.get_data())
        depth_img = np.asanyarray(depth_frame.get_data())
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

        depth_colormap = cv2.applyColorMap(cv2.convertScaleAbs(depth_img, alpha=0.03), cv2.COLORMAP_JET)

        faces = face_cascade.detectMultiScale(gray, 1.3, 5)
        for (x,y,w,h) in faces:
            img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
            roi_gray = gray[y:y+h, x:x+w]
            roi_color = img[y:y+h, x:x+w]
            eyes = eye_cascade.detectMultiScale(roi_gray)
            for (ex,ey,ew,eh) in eyes:
                cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)

        images = np.hstack((img, depth_colormap))

        cv2.imshow('img',images)
        cv2.waitKey(30)
        cv2.destroyAllWindows()

finally:

    # Stop streaming
    pipeline.stop()

理由はわかりませんが、cv2.waitKey(30)の数値の部分を小さくすると、異常終了しやすくなります。(気のせいかも)

終わりに

これだけで、RGB画像と、深度画像を同時表示させつつ顔認識を実施するアプリを実装できました。
OpenCVとPyrealsense2を勉強すれば、Open3Dなどと組み合わせてPointCloudを表示したりすることができるはずです。
今後挑戦していきます。

3
8
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
8