티스토리 뷰

반응형

우분투 서버에 파이썬으로 얼굴인식 하기


파이썬이 설치가 안되어있다면 http://brtech.tistory.com/45

opencv 가 설치가 안되어있다면 http://brtech.tistory.com/68



튜토리얼에 나와있는 Haar Cascades 를 이용한 얼굴 인식 방법이다.


먼저 이곳에서 원하는 트레이닝셋을 받는다. 

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


튜토리얼대로 인물사진의 정면과 인식된 얼굴에 눈을 찾기 위해 우선 두가지 트레이닝 셋을 받았다.

wget https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_frontalface_default.xml

wget https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_eye.xml 


그리고 python 스크립트를 짜기 위해 파일을 만든다.

vi detect.py 

( 위의 트레이닝셋 파일과 위의 파일은 같은 위치에 있어야 한다. ) 

그리고 다음의 코드를 삽입한다.


import numpy as np

import cv2

import sys

import urllib


def url_to_image(url):

    # download the image, convert it to a NumPy array, and then read

    # it into OpenCV format

    resp = urllib.urlopen(url)

    image = np.asarray(bytearray(resp.read()), dtype="uint8")

    image = cv2.imdecode(image, cv2.IMREAD_COLOR)


    # return the image

    return image



face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')


src = sys.argv[1]

img = url_to_image(src)

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)


faces = face_cascade.detectMultiScale(

        gray,

        scaleFactor=1.1,

        minNeighbors=5,

        minSize=(50, 50)

)


print('found {0} faces'.format(len(faces)))


for (x,y,w,h) in faces:

    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)


cv2.imwrite('detect_result.jpg',img)

튜토리얼에 소스를 조금 바꾸어, 웹에 있는 이미지 주소를 가지고 얼굴인식을 하는 소스로 변형했다. 


스크립트 실행 방법은 아래와 같다.

python detect.py {이미지 주소}

python detect.py https://s-media-cache-ak0.pinimg.com/originals/69/6b/7b/696b7bfee856d62fc1e34e811bd62e14.jpg

실행이 완료되면 터미널에 found ~ faces 라고 출력되며 찾은 결과에 마커가 추가되어 detect_result.jpg 라는 파일로 저장된다. 


이미지를 몇장 구해서 결과와 대조해본다. 

아래는 각각의 결과들이다.   


( 영화 투모로우 랜드의 이미지들..  ) 

tomorrowland movie에 대한 이미지 검색결과

tommorowland image face detect result

훌륭한 결과이다. 비록 눈을 인식해 내진 못했지만! 


관련 이미지

tommorowland image face detect result

두 여배우는 왜 인식이 안되었을까


tomorrowland movie에 대한 이미지 검색결과

tommorowland image face detect result

넘 예쁜 배우의 얼굴을.. 미안 ㅠ



반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함