Raspberry PI + OpenCV + PICamera = 얼굴/눈 인식


picamera, opencv 등 확인 후 없으면 설치(Python용)


얼굴/눈 인식에 대한 글이 있어서 따라해 봤는데 쉽게 성공.

picamera, opencv등을 먼저 설치하고(패키지로 먼저 설치된 것 사용해도 됨.) 얼굴/눈 인식에 사용하는 사전을 받아서 저장해 둔다.


사용된 사전은


https://github.com/Itseez/opencv/tree/master/data/haarcascades


에 등록되어있는 것을 이용


소스는 다음과 같다. 인터넷에 있는 몇가지 자료 짬뽕.


# import the necessary packages
from picamera.array import PiRGBArray
from picamera import PiCamera
import numpy
import time
import cv2

#multiple cascades: https://github.com/Itseez/opencv/tree/master/data/haarcascades
#https://github.com/Itseez/opencv/blob/master/data/haarcascades/haarcascade_frontalface_default.xml
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
#https://github.com/Itseez/opencv/blob/master/data/haarcascades/haarcascade_eye.xml
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')

# initialize the camera and grab a reference to the raw camera capture
camera = PiCamera()
camera.resolution = (640, 480)
camera.framerate = 32
rawCapture = PiRGBArray(camera, size=(640, 480))
 
# allow the camera to warmup
time.sleep(0.1)
 
# capture frames from the camera
for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
    image = frame.array
    gray  = cv2.cvtColor (image, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale (gray, 1.3, 5)

    for (x, y, w, h) in faces:
        cv2.rectangle (image, (x, y), (x + w, y + h), (255, 0, 0), 2)
        roi_gray  = gray  [y: y + h, x: x + w]
        roi_color = image [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)


    # show the frame
    cv2.imshow("Frame", image)
    key = cv2.waitKey(1) & 0xFF
 
    # clear the stream in preparation for the next frame
    rawCapture.truncate(0)
 
    # if the `q` key was pressed, break from the loop
    if key == ord("q"):
        break


주의: Copy&Paste시에 \t를 주의


'라즈베리파이' 카테고리의 다른 글

Raspberry PI 3 UART Enable  (0) 2018.07.05
RaspberryPI + PiCam으로 timelapse 만들기  (0) 2018.06.27
Raspberry PI를 camcoder로  (3) 2017.07.13
USB Audio 사용하기  (0) 2017.07.13
라즈베리파이에서 스트리밍  (0) 2017.02.20
Posted by codebank
,