'''
지금 과정 :: 0. 사람이라고 판단되는 객체 탐지 ->
1. 영상 내 얼굴이 있는지 확인 ->
2. 알고 있는 얼굴과 영상내 얼굴이라고 판단되는 것과 비슷한 정도 비교 ->
3. 그 얼굴을 기준으로 블러 처리
(얼굴이 나올 때)
바꿀 과정.v2 :: 0. 사람이라고 판단되는 객체와 머리라고 판단되는 객체 탐지 ->
1. 알고 있는 얼굴과 영상내 얼굴이라고 판단되는 것과 비슷한 정도로 비교
'''
'''
(처음부터 얼굴이 잘 나오지 않았을 때)
바꿀 과정.v1 :: 0. 사람이라고 판단되는 객체와 머리라고 판단되는 객체 탐지 ->
1. 머리라고 판단되는 부분을 업 스케일해서 얼굴을 추출해본다
2. 아는 얼굴과 업스케일된 얼굴의 유사도를 측정해서 맞다고 판단되면
3. 몸을 저장하고, 사람이라고 판단되는 객체와 인코딩 저장된 것과 비슷한 것을 찾아서 마스킹 해제 처리 (이게 Loop 처음에 와야한다..)
'''
import os
import numpy as np
import cv2
from cv2 import dnn_superres
from ultralytics import YOLO
import face_recognition
# YOLOv8 모델 불러오기
model = YOLO('./models/best_241031.pt') # YOLO v11
#업스케일 도구 가져오기
sr = dnn_superres.DnnSuperResImpl_create()
#모델 읽어오기
path = './EDSR_x3.pb'
sr.readModel(path)
#모델의 이미지 스케일 지정하기(x3일때는 3, EDSR_x4.pb일때는 4를 입력하면 된다.)
sr.setModel('edsr', 3)
image_path = "./images/"
movie_path = "./movies/"
output_path = "./output/"
# Output 파일 경로
output_file = output_path + "blured_version1.mp4"
# 디렉토리가 존재하지 않으면 생성
if not os.path.exists(output_path):
os.makedirs(output_path)
# Load the movie
movie_name = movie_path + "biden_test.mp4"
video_capture = cv2.VideoCapture(movie_name)
# 비디오 프레임의 너비, 높이, FPS 정보 가져오기
frame_width = int(video_capture.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(video_capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = video_capture.get(cv2.CAP_PROP_FPS)
# 비디오 저장을 위한 설정 (코덱, 프레임 크기, FPS)
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
frame_skip = 2 # 프레임 스킵 간격
out = cv2.VideoWriter(output_file, fourcc, fps / frame_skip, (frame_width, frame_height))
# 알려진 얼굴 인코딩 추가
known_face_encodings = []
for i in range(1, 11):
biden_image = face_recognition.load_image_file(image_path + f"biden{i}.png")
face_encodings = face_recognition.face_encodings(biden_image)
if face_encodings:
biden_image_encoded = face_recognition.face_encodings(biden_image)[0]
known_face_encodings.append(biden_image_encoded)
else:
print(f"no face in image biden_{i}.png")
####### 영상 처리 ########
'''
(처음부터 얼굴이 잘 나오지 않았을 때)
바꿀 과정.v1 :: 0. 사람이라고 판단되는 객체와 머리라고 판단되는 객체 탐지 ->
1. 머리라고 판단되는 부분을 업 스케일해서 얼굴을 추출해본다
2. 아는 얼굴과 업스케일된 얼굴의 유사도를 측정해서 맞다고 판단되면 몸을 저장
3. 사람이라고 판단되는 객체와 인코딩 저장된 것과 비슷한 것을 찾아서 마스킹 해제 처리 (이게 Loop 처음에 와야한다..)
'''
def check(face_box, people_box):
x1, y1, x2, y2 = people_box
left, top, right, bottom = face_box # 이 안에
# 얼굴 박스의 경계가 사람 박스와 겹치는지를 확인
print("Face Box", left, top, right, bottom)
print("People Box", x1, y1, x2, y2)
if (x1 <= left <= x2) and (y1 <= top <= y2) and (x1 <= right <= x2) and (y1 <= bottom <= y2):
return True
return False
# 바디 인코딩 업데이트를 위한 함수
def update_body_history(body_history, body_encoding, max_history=11):
distances = [np.linalg.norm(np.array(body_encoding) - np.array(body)) for body in body_history]
if len(body_history) >= max_history:
body_history.pop(distances.index(max(distances)))
body_history.append(body_encoding)
return body_history
# 변수 초기화
body_history = [] # 바디 인코딩 저장
head_encodings = [] # YOLO, cv2
frame_count = 0 # 프레임 카운터
while video_capture.isOpened():
ret, frame = video_capture.read()
if not ret:
break
height, width, channels = frame.shape
if not (frame_count % frame_skip): # 프레임 당 객체 탐지 (YOLO v11)
results = model.track(frame, persist=True, conf=0.45, iou=0.4, show_labels=True, show_conf=False, tracker="bytetrack.yaml")
people_boxes = [] # Blur 해제할 몸 저장
head_boxes = [] # 머리 locations temp 저장
### 0. 사람이라고 판단되는 객체와 머리라고 판단되는 객체를 탐지
for result in results:
boxes = result.boxes.xyxy # 바운딩 박스 좌표
length = len(boxes)
class_ids = result.boxes.cls
for i in range(length):
cls = int(class_ids[i])
x1, y1, x2, y2 = map(int, boxes[i])
if cls == 0:
people_boxes.append([x1, y1, x2, y2])
elif cls == 1: # 1 head
head_boxes.append([x1, y1, x2, y2])
### 1. 머리라고 판단되는 부분을 업 스케일해서 얼굴을 추출해본다
face_locations = [] # fr
for x1,y1,x2,y2 in head_boxes:
# upscaled_head = sr.upsample(frame[y1:y2, x1:x2]) # upscaled *3
# face_location = face_recognition.face_locations(upscaled_head)
head = frame[y1:y2, x1:x2]
rgb_head = cv2.cvtColor(head, cv2.COLOR_BGR2RGB) # BGR에서 RGB로 변환
face_location = face_recognition.face_locations(rgb_head) # 얼굴 위치 탐지
if face_location: # 얼굴 추출
### 2. 아는 얼굴과 업스케일이된 얼굴의 유사도를 측정해서 맞다고 판단하기
# face_encoding = face_recognition.face_encodings(upscaled_head, face_location)
face_encodings = face_recognition.face_encodings(rgb_head, face_location)
for face_encoding in face_encodings:
matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
best_match_index = np.argmin(face_distances)
if matches[best_match_index] and face_distances[best_match_index] < 0.45: # 닮다고 생각되는 얼굴 추가
face_locations.append([x1, y1, x2, y2])
known_face_encodings.append(face_encoding)
print("known_face_encodings added!")
### 3. 모든 프레임 블러 처리
blurred_frame = cv2.GaussianBlur(frame, (99, 99), 15)
blurred_frame = cv2.GaussianBlur(blurred_frame, (33, 33), 9)
print("--------------")
print('face_locations:', face_locations, "people_boxes :", people_boxes)
print("--------------")
### 4. 인식된 얼굴 영역 복원
if face_locations:
for location in face_locations: # 한번 풀어주기
left, top, right, bottom = location
# 몸 객체 확인 + 얼굴 객체 확인
for (x1, y1, x2, y2) in people_boxes:
if check([left, top, right, bottom], [x1, y1, x2, y2]): # 그 몸에 대해서 마스킹 해제
print("masked off!!")
blurred_frame[y1:y2, x1:x2] = frame[y1:y2, x1:x2]
body_encoding = cv2.mean(blurred_frame)[:3]
if body_history:
distance = []
# 거리 확인해서 가장 유사도가 낮은(*거리가 먼) 몸을 갈아치우기
for body in body_history:
distance.append(np.linalg.norm(np.array(body_encoding) - np.array(body)))
if len(body_history) > 10: # 11개일 경우, 정리
body_history.pop(distance.index(max(distance)))
body_history.append(body_encoding)
break
else: # 바디 인코딩 추가
body_history.append(body_encoding)
else:
body_history.append(body_encoding) # 인코딩 변환 후 저장
############################## 수정할 부분 (주말에 local에서 해보고 확인할 것)
#### 5. 얼굴이 인식되지 않았을 때, 객체 중 가장 가까운 몸을 찾는다.
else:
if people_boxes:
people_box_score_list = []
for people_box in people_boxes:
left, top, right, bottom = people_box
body_encoding = cv2.mean(frame[top:bottom, left:right])[:3]
distances = [np.linalg.norm(np.array(body_encoding) - np.array(body)) for body in body_history]
people_box_score_list.append(sum(distances))
# 가장 가까운 사람 찾기 및 마스킹 해제
x1, y1, x2, y2 = people_boxes[people_box_score_list.index(min(people_box_score_list))]
blurred_frame[y1:y2, x1:x2] = frame[y1:y2, x1:x2]
# 바디 인코딩 업데이트
body_encoding = cv2.mean(frame[y1:y2, x1:x2])[:3]
body_history = update_body_history(body_history, body_encoding)
##############################
# 처리된 프레임을 파일로 저장
out.write(blurred_frame)
frame_count += 1 # 프레임 카운터 증가
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 비디오 및 파일 저장 종료
video_capture.release()
out.release()
cv2.destroyAllWindows()

Serving 하는 것을 Gunicorn, Uvicorn의 Multi Processing을 하기 위해서