안녕하세요! Mediapipe의 face detection 기술을 통해 얼굴 모자이크를 해보겠습니당
라이브러리가 설치되어 있지 않다면 먼저 설치해 주세요!
pip install opencv-python
pip install mediapipe
먼저 필요한 라이브러리를 import 해줍니다.
import cv2
import mediapipe as mp
# 미디어파이프 초기화
mp_face_detection = mp.solutions.face_detection
mp_drawing = mp.solutions.drawing_utils
face_detection = mp_face_detection.FaceDetection(min_detection_confidence=0.30)
웹캠을 사용해 줍니다. 보통은 0으로 하시면 될 겁니다!
# 카메라 캡처
cap = cv2.VideoCapture(1)
얼굴을 감지하고 모자이크 하는 함수를 작성해 보겠습니다.
def detect_face(image, factor=15):
# RGB 이미지로 변환
frame_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# 얼굴 감지 수행
results = face_detection.process(frame_rgb)
if results.detections:
for detection in results.detections:
# 감지된 얼굴의 바운딩 박스 정보 가져오기
bboxC = detection.location_data.relative_bounding_box
ih, iw, _ = image.shape
x, y, w, h = int(bboxC.xmin * iw), int(bboxC.ymin * ih), int(bboxC.width * iw), int(bboxC.height * ih)
# 얼굴 주위에 픽셀화 적용
# 얼굴 영역 크기 조정
face_roi = image[y:y+h, x:x+w]
face_roi = cv2.resize(face_roi, (0, 0), fx=0.04, fy=0.04) # 얼굴 크기 축소
face_roi = cv2.resize(face_roi, (w, h), interpolation=cv2.INTER_NEAREST) # 원래 크기로 확대
image[y:y+h, x:x+w] = face_roi # 원본 이미지에 픽셀화된 얼굴 영역 적용
return image
bboxC = detection.location_data.relative_bounding_box
ih, iw, _ = image.shape
x, y, w, h = int(bboxC.xmin * iw), int(bboxC.ymin * ih), int(bboxC.width * iw), int(bboxC.height * ih)
이 코드를 통해 얼굴 영역을 가져오고
face_roi = image[y:y+h, x:x+w]
face_roi = cv2.resize(face_roi, (0, 0), fx=0.04, fy=0.04)
face_roi = cv2.resize(face_roi, (w, h), interpolation=cv2.INTER_NEAREST)
image[y:y+h, x:x+w] = face_roi
이 코드를 통해 얼굴 영역에 모자이크를 처리하게 됩니다.
마지막으로 웹캠이 실행되는 동안 모자이크를 수행하는 코드를 작성해 줍니다. (방금 작성한 detect_face 함수를 사용합니다.)
while True:
ret, frame = cap.read()
if not ret:
break
# 얼굴 감지 및 픽셀화 적용
frame = detect_face(frame)
# 화면에 출력
cv2.imshow('Face Pixelation', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
짠
'과정 > 2차 AI프로젝트(해커톤참가)' 카테고리의 다른 글
프로젝트 '재움' 서비스 개발 시작 (0) | 2023.10.17 |
---|---|
MediaPipe를 통해 지정한 자세 정확도 테스트 (1) | 2023.10.13 |
2차 프로젝트 재움 진행사하아앙_1005 (1) | 2023.10.06 |
MediaPipe 각도를 이용한 자세 유추해보기 (0) | 2023.10.02 |
MediaPipe를 이용한 간단한 앉은 자세 인식하기 (0) | 2023.09.26 |
댓글