5
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Jetson NanoとWebカメラで簡単顔認識トライ

Last updated at Posted at 2019-11-24

はじめに

Jetson NanoでWebカメラを使用してリアルタイム顔認識を試しました。

参考にしたページ

画像取得トライ

まずはWebカメラでどうすれば画像を取得できるのかを確認します。
めっちゃ簡単でした。

camTest.py

import cv2

# カメラを起動
capture = cv2.VideoCapture(0)

while(True):
    # 1フレームの画像を取得
    ret, frame = capture.read()
    # 画像をウィンドウに表示
    cv2.imshow("frame", frame)
    # qを押されたら停止
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
# 解放
capture.release()
cv2.destroyAllWindows()

qを押せば止まるのですが、ターミナルではなくウィンドウにフォーカスがある状態で押さないと正常に機能しません。

顔認識

OpenCVをインストールした時にカスケード分類器のファイルが一緒に入っているのでそれを使います。
(https://github.com/opencv/opencv/tree/master/data/haarcascades)

顔認識の手順は以下のようです

  1. 画像を取得
  2. グレースケールに変換
  3. 顔認識処理
  4. 認識位置に枠を書く
find_face.py

# -*- coding: utf-8 -*-

import time
import cv2

# フレームサイズ(大きいと処理が重たくなります)
FRAME_W = 320
FRAME_H = 240

# 顔検出用のカスケード分類器(特徴量をまとめたファイルらしい)
# 他のフォルダにあったものを読み込もうとしたらエラーになったので同じフォルダにコピーした
cascadeFilePath = './haarcascade_frontalface_default.xml'
cascade = cv2.CascadeClassifier(cascadeFilePath)

# カメラ設定
cam = cv2.VideoCapture(0)
time.sleep(1)                 # 起動待ち(とりあえず)
cam.set(cv2.CAP_PROP_FPS, 60) # 60もでたか不明
cam.set(cv2.CAP_PROP_FRAME_WIDTH, FRAME_W)
cam.set(cv2.CAP_PROP_FRAME_HEIGHT, FRAME_H)

while(True):
    # qで終了
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

    # 画像取得
    ret, frame = cam.read()
    # グレースケールに変換
    gray_image = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
    # 顔認識
    facerect = cascade.detectMultiScale(gray_image, scaleFactor=1.1, minNeighbors=2, minSize=(30, 30))

    # 顔が検出されたか
    if len(facerect) > 0:
        # 枠線用の色
        line_color = (255, 102, 51)
        # テキストの色
        font_color = (255, 102, 51)

        # 検出した顔に枠とFACEの文字を書く
        for (x, y, width, height) in facerect:
            cv2.rectangle(frame, (x, y), (x + width, y + height), line_color, 2)
            cv2.putText(frame, 'FACE', (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.7, font_color, 1, cv2.LINE_AA)

    # ウィンドウに表示
    cv2.imshow('frame', frame)
    

# 終了処理
cam.release()
cv2.destroyAllWindows()

リアルタイムに認識されました!
64995AAA-1ABA-4969-960B-2DD91F03FB4A.jpeg

5
7
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
5
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?