얼굴 인식
import cv2
import numpy as np
#분류기
path =('')
cascPath = path + '/xml/haarcascade_frontalface_default.xml'
faceCascade = cv2.CascadeClassifier(cascPath)
#video caputure setting
capture = cv2.VideoCapture(0)
capture.set(cv2.CAP_PROP_FRAME_WIDTH,1280) #CAP_PROP_FRAME_WIDTH == 3
capture.set(cv2.CAP_PROP_FRAME_HEIGHT,960) #CAP_PROP_FRAME_HEIGHT == 4
#console message
face_id = input('\n enter user id end press <return> ==> ')
print("\n [INFO] Initializing face capture. Look the camera and wait ...")
count = 0 # # of caputre face images
#영상 처리 및 출력
while True:
ret, frame = capture.read() #카메라 상태 및 프레임
# frame = cv2.flip(frame, 1) #좌우반전(1), 상하반전(0)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,#검출하고자 하는 원본이미지
scaleFactor = 1.2, #검색 윈도우 확대 비율, 1보다 커야 한다
minNeighbors = 6, #얼굴 사이 최소 간격(픽셀)
minSize=(20,20) #얼굴 최소 크기. 이것보다 작으면 무시
)
#얼굴에 대해 rectangle 출력
for (x,y,w,h) in faces:
cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)
#inputOutputArray, point1 , 2, colorBGR, thickness)
count += 1
cv2.imwrite(path+"dataset/object."+str(face_id)+'.'+str(count)+".jpg",
gray[y:y+h, x:x+w])
#종료 조건
if cv2.waitKey(1) > 0 : break #키 입력이 있을 때 반복문 종료
if count >= 100 : break #100 face sample
print("\n [INFO] Exiting Program and cleanup stuff")
capture.release() #메모리 해제
cv2.destroyAllWindows()#모든 윈도우 창 닫기
cv2.waitKey(1)
얼굴 학습
import cv2
import numpy as np
from PIL import Image #python imaging library
import os
# Path for face image database
path =('')
xml_path = ('C:/Users/Hoon/Desktop/ENCOREPYTHON/OpenCV/xml')
print(xml_path)
recognizer = cv2.face.LBPHFaceRecognizer_create()
detector = cv2.CascadeClassifier("C:/Users/Hoon/Desktop/ENCOREPYTHON/OpenCV/haarcascade_frontalface_default.xml")
# function to get the images and label data
def getImagesAndLabels(path):
imagePaths = [path+'dataset/'+f for f in os.listdir(path+'dataset/')
if f.startswith('o')]
faceSamples=[]
ids = []
for imagePath in imagePaths:
PIL_img = Image.open(imagePath).convert('L') # convert it to grayscale
img_numpy = np.array(PIL_img,'uint8')
id = int(os.path.split(imagePath)[-1].split(".")[1])
faces = detector.detectMultiScale(img_numpy)
for (x,y,w,h) in faces:
faceSamples.append(img_numpy[y:y+h,x:x+w])
ids.append(id)
return faceSamples,ids
print ("\n [INFO] Training faces. It will take a few seconds. Wait ...")
faces,ids = getImagesAndLabels(path)
recognizer.train(faces, np.array(ids))
# Save the model into trainer/trainer.yml
recognizer.write(path + 'trainer/trainer.yml') # recognizer.save() worked on Mac, but not on Pi
# Print the numer of faces trained and end program
print("\n [INFO] {0} faces trained. Exiting Program".format(len(np.unique(ids))))
<캠 >
import cv2
import numpy as np
path =('')
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read(path+'trainer/trainer.yml')
cascadePath = path+'xml/haarcascade_frontalface_default.xml'
faceCascade = cv2.CascadeClassifier(cascadePath)
font = cv2.FONT_HERSHEY_SIMPLEX
id = 0
names = ['Hoon','dave', 'shake', 'cup']
cam = cv2.VideoCapture(0)
cam.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
cam.set(cv2.CAP_PROP_FRAME_HEIGHT, 960)
minW = 0.1 * cam.get(cv2.CAP_PROP_FRAME_WIDTH)
minH = 0.1 * cam.get(cv2.CAP_PROP_FRAME_HEIGHT)
while True:
ret, img = cam.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.2,
minNeighbors=6,
minSize=(int(minW), int(minH))
)
for(x,y,w,h) in faces:
cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0),2)
id, confidence = recognizer.predict(gray[y:y+h, x:x+w])
if confidence < 55 :
id = names[id]
else:
id = "unknown"
confidence = " {0}%".format(round(100-confidence))
cv2.putText(img,str(id), (x+5,y-5),font,1,(255,255,255),2)
cv2.putText(img,str(confidence), (x+5,y+h-5),font,1,(255,255,0),1)
cv2.imshow('camera',img)
if cv2.waitKey(1) > 0 : break
print("\n [INFO] Exiting Program and cleanup stuff")
cam.release()
cv2.destroyAllWindows()
cv2.waitKey(1)
'OpenCV' 카테고리의 다른 글
OpenCV - QR코드 인식 (0) | 2022.11.22 |
---|---|
OpenCV - OBJECT DETECTION (0) | 2022.11.21 |
OpenCV - 디스크립터(Descriptor) (0) | 2022.11.16 |
OpenCV - CircleGrid (0) | 2022.11.15 |
OpenCV - 체스보드 패턴 코너점 검출 (0) | 2022.11.15 |