얼굴인식 후 저장
## **얼굴인식해서저장**
import cv2
import os
# Haar Cascade Classifier 파일을 로드합니다.
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') # 얼굴 검출을 위한 Haar Cascade 파일
# 카메라 캡처 초기화
camera = cv2.VideoCapture(0)
camera.set(3, 800) # 너비
camera.set(4, 600) # 높이
# 저장할 폴더 경로 설정
output_folder = 'captured_faces' # 저장할 폴더 이름
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# 저장할 이미지의 초기 인덱스 설정
image_index = 0
max_images = 100
while True:
ret, frame = camera.read()
if not ret:
break
# 회색조로 변환 (얼굴 인식 성능 향상을 위해)
gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 얼굴 검출
faces = face_cascade.detectMultiScale(gray_frame, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
# 얼굴이 검출된 경우 이미지를 저장
for (x, y, w, h) in faces:
face_img = frame[y:y+h, x:x+w]
image_path = os.path.join(output_folder, f'face_{image_index}.jpg')
cv2.imwrite(image_path, face_img)
image_index += 1
# 100장의 이미지를 저장하면 종료
if image_index >= max_images:
break
# 결과를 표시
cv2.imshow('Face Detector', frame)
# ESC 키를 누르면 종료
if cv2.waitKey(1) & 0xFF == 27 or image_index >= max_images:
break
# 카메라 해제 및 모든 창 닫기
camera.release()
cv2.destroyAllWindows()
저장된 얼굴 학습
import cv2
import os
import numpy as np
# 저장된 얼굴 이미지 폴더 경로
image_folder = 'captured_faces'
# 학습 데이터와 레이블을 저장할 리스트 초기화
Training_Data = []
Labels = []
# 이미지 파일을 읽어 회색조로 변환하여 리스트에 추가
for image_name in os.listdir(image_folder):
image_path = os.path.join(image_folder, image_name)
image = cv2.imread(image_path)
if image is None:
continue
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
Training_Data.append(gray_image)
Labels.append(0) # 모든 이미지를 동일한 레이블로 설정 (예: 0)
# 리스트를 numpy 배열로 변환
Labels = np.array(Labels)
# 모델 객체 생성
model = cv2.face.LBPHFaceRecognizer_create()
# 모델 학습
model.train(Training_Data, Labels)
# 훈련된 모델 파일로 저장
model.write('face_model.yml')
print("모델 학습 완료 및 저장")
얼굴인식
import cv2
import numpy as np
# Haar Cascade Classifier 파일을 로드합니다.
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
# 학습된 모델 파일을 로드합니다.
model = cv2.face.LBPHFaceRecognizer_create()
model.read('face_model.yml')
# 카메라 캡처 초기화
camera = cv2.VideoCapture(0)
camera.set(3, 800) # 너비
camera.set(4, 600) # 높이
while True:
ret, frame = camera.read()
if not ret:
break
# 회색조로 변환 (얼굴 인식 성능 향상을 위해)
gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 얼굴 검출
faces = face_cascade.detectMultiScale(gray_frame, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
# 얼굴이 검출된 경우
for (x, y, w, h) in faces:
face_img = gray_frame[y:y+h, x:x+w]
# 모델 예측
label, confidence = model.predict(face_img)
# 예측 결과 신뢰도가 75 이상인 경우 "ACCESS GRANTED", 아니면 "ACCESS DENIED"
if confidence < 75:
cv2.putText(frame, "ACCESS GRANTED", (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (0, 255, 0), 3)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
else:
cv2.putText(frame, "ACCESS DENIED", (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (0, 0, 255), 3)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)
# 결과를 표시
cv2.imshow('Face Detector', frame)
# 'q' 키를 누르면 종료
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 카메라 해제 및 모든 창 닫기
camera.release()
cv2.destroyAllWindows()