raspberry pi opencv ビデオで顔認識

はてなブックマーク - raspberry pi opencv ビデオで顔認識
LINEで送る
Pocket

前のこの記事の続きです!

RaspberryPiで顔認識OpenCVで(コンパイルの方法も!)

今回は

ビデオの中の顔を検出するプログラムを実行したいと思います。

合わせてnoteのよくメンテする記事もご参考ください。

まず、新しいバージョンのpythonを使うために(python 3)下記のコマンドを実行しておきましょう。

詳細説明は、前回の記事をご参照ください。

source ~/.profile
workon cv

続いて、下記のプログラムを用意します。

注意:まず picameraをインストールしてください

同じRaspberry Piでpython 2の環境で、プログラムが実行できたのに

python 3の環境が下記のエラーが出ました。

ImportError :  No module named ‘picamera’

結局pyhon 3の環境では、picamera をインストールしていないから、見つからないのは当然です。

下記のコマンドを実行する!

pip install picamera

python3の環境にインストールしました。

下記のプログラムを実行します!

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from picamera.array import PiRGBArray
from picamera import PiCamera
import cv2, time

# フレームサイズ
FRAME_W = 320
FRAME_H = 192

# 正面の顔検出用
cascPath = '/usr/local/share/OpenCV/lbpcascades/lbpcascade_frontalface.xml'
faceCascade = cv2.CascadeClassifier(cascPath)

camera = PiCamera()
camera.resolution = (FRAME_W, FRAME_H)
camera.framerate = 32
rawCapture = PiRGBArray(camera, size=(FRAME_W, FRAME_H))
time.sleep(0.1)

for image in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):

    frame = image.array
    # frame = cv2.flip(frame, -1) # 上下反転する場合

    # Convert to greyscale for detection
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    gray = cv2.equalizeHist( gray )

    # 顔検出
    faces = faceCascade.detectMultiScale(gray, 1.1, 3, 0, (10, 10))

    # 検出した顔に枠を書く
    for (x, y, w, h) in faces:
        # 見つかった顔を矩形で囲む
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

    frame = cv2.resize(frame, (540,300))

    # ビデオに表示 
    cv2.imshow('Video', frame)
    key = cv2.waitKey(1) & 0xFF

    rawCapture.truncate(0)

    if key == ord("q"):
        break

cv2.destroyAllWindows()

 

深夜、妻と子供が寝た後

ギリギリ画面に暗い照明を当てて、取ったスクリーンショットです。お許しください。

出来ました!

ここでは、画像ですが、実際はもちろん、ビデオで流している映像を動的に二人の顔を検出しています!

(ちなみに、これはWeworkの二人です。)

これで、監視カメラとか

店舗の来客人数識別カウンターなど、色々応用が出来そうですね。

後、サーボと組み合わせて、顔追跡も出来そうですね。

というよりは、次回顔追跡をやってみたいです!

Raspberry Piで最新版のopenCV(3.4.4)をコンパイルして使いたい方はこちらの記事をどうぞ!

はてなブックマーク - raspberry pi opencv ビデオで顔認識
LINEで送る
Pocket

Add a Comment

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close