티스토리 뷰
OPENCV를 이용하여 얼굴 감지하기
스텝 1
OpenCV 설치
OpenCV는 라즈베리파이에 내장되어 있지 않다.
쫄지마세요!! 설치는 간단합니다.
sudo apt-get update
sudo apt-get install python-opencv libopencv-dev
설치가 잘 되었는지 확인하기
python 을 입력한다.
import cv 를 입력한다.
뭔가 잘못됐다..
그런데 import cv2 는 된다.
위에처럼 빈 프롬프트가 나오면 정상이다.
그럼 코딩할때 import cv2 로 진행하도록 한다.
스텝2 Haar cascade
Haar cascade는 얼굴을 인식하는 알고리즘이다. 왜냐하면 컴퓨터는 사람 얼굴이 어떤지 모른다. 그래서 "Haar cascade" 알고리즘을 이용하여 얼굴을 인식하게 해준다.
스텝3 코딩하기
import os, sys, time
import cv2.cv as cv
minSize = (20, 20)
imageScale = 1
haarScale = 2
minNeighbors = 3
haarFlags = cv.CV_HAAR_DO_CANNY_PRUNING
def detectFace(img, cascade):
# allocate temporary images
gray = cv.CreateImage((img.width,img.height), 8, 1)
small_img = cv.CreateImage((cv.Round(img.width /
imageScale),cv.Round (img.height / imageScale)), 8, 1)
# convert color input image to grayscale
cv.CvtColor(img, gray, cv.CV_BGR2GRAY)
# scale input image for faster processing
cv.Resize(gray, small_img, cv.CV_INTER_LINEAR)
cv.EqualizeHist(small_img, small_img)
faces = cv.HaarDetectObjects(small_img, cascade,
cv.CreateMemStorage(0),haarScale, minNeighbors, haarFlags, minSize)
if faces:
print "\tDetected ", len(faces), " object(s)"
for ((x, y, w, h), n) in faces:
#the input to cv.HaarDetectObjects was resized, scale the
#bounding box of each face and convert it to two CvPoints
pt1 = (int(x * imageScale), int(y * imageScale))
pt2 = (int((x + w) * imageScale), int((y + h) * imageScale))
cv.Rectangle(img, pt1, pt2, cv.RGB(255, 0, 0), 3, 8, 0)
return img
else:
return False
# scan all directories and subdirectories for jpg images
def readDirectory(fileLocation, cascade):
for root, dirs, files in os.walk(fileLocation):
print root, "has:"
for name in files:
if name.find(".jpg") >=1 :
#sequentially loop, load and detect.
print "Analysing " + name +":"
#measure how long it takes
t = cv.GetTickCount()
#load in the image
image = cv.LoadImage(os.path.join(root,name), 1)
match = detectFace(image, cascade)
if match:
#save a new image with a box round each face
cv.SaveImage( fileLocation + "/face_" + name, match)
t = cv.GetTickCount() -t
print "\tTime = %gms" %(t/(cv.GetTickFrequency()*1000.0))
if __name__ == '__main__':
cdir = "/usr/share/opencv/haarcascades/"
cascade = cv.Load(cdir + "haarcascade_frontalface_default.xml")
if len(sys.argv) != 2:
print 'please provide a directory to read'
sys.exit(1)
readDirectory(sys.argv[1], cascade)