0
0

More than 3 years have passed since last update.

RaspberryPiでリアルタイム顔検出

Posted at

今回やること

RaspberryPiとWebカメラを使ってリアルタイム顔検出

環境

Rasbian(RaspberryPi 4)
Python
Opencv

処理

カスケード分類器のインストール

git clone https://github.com/opencv/opencv

コード

git cloneしたのと同じフォルダにコードを作成し、実行する必要があります。
(パスを変えればどこでもよい)

import tkinter
import cv2
import PIL.Image, PIL.ImageTk


class App:
    def __init__(self, window, window_title):
        self.window = window
        self.window.title(window_title)

        self.vcap = cv2.VideoCapture(0)
        self.width = self.vcap.get(cv2.CAP_PROP_FRAME_WIDTH)
        self.height = self.vcap.get(cv2.CAP_PROP_FRAME_HEIGHT)

        self.canvas = tkinter.Canvas(window, width=self.width, height=self.height)
        self.canvas.pack()

        self.close_btn = tkinter.Button(window, text="Close")
        self.close_btn.pack()
        self.close_btn.configure(command=self.destructor)

        self.delay = 15
        self.update()

        self.window.mainloop()

    def update(self):
        _, frame = self.vcap.read()
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

        cascade_path = "./opencv/data/haarcascades/haarcascade_frontalface_alt.xml"
        cascade = cv2.CascadeClassifier(cascade_path)
       faces=cascade.detectMultiScale(frame, scaleFactor=1.1, minNeighbors=1, minSize=(10,10))

        for x,y,w,h in faces:
            cv2.rectangle(frame, (x,y), (x+w, y+h), (0, 0, 255), thickness=30)

        self.photo = PIL.ImageTk.PhotoImage(image = PIL.Image.fromarray(frame))
        self.canvas.create_image(0, 0, image = self.photo, anchor = tkinter.NW)
        self.window.after(self.delay, self.update)

    def destructor(self):
        self.window.destroy()
        self.vcap.release()

App(tkinter.Tk(), "Tkinter & Camera module")

参考

https://yamitomo.com/article/133
https://www.argocorp.com/UVC_camera/Sample_OpenCV_cascade.detectMultiScale.html

注意書き

とりあえずやってみました。
めちゃくちゃ遅いです。
詳細の解説や改良、カメラモジュールでの確認は気が向いたらやっていきます。

0
0
0

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