'''
지금 과정 :: 0. 사람이라고 판단되는 객체 탐지 ->
1. 영상 내 얼굴이 있는지 확인 ->
2. 알고 있는 얼굴과 영상내 얼굴이라고 판단되는 것과 비슷한 정도 비교 ->
3. 그 얼굴을 기준으로 블러 처리
(얼굴이 나올 때)
바꿀 과정.v2 :: 0. 사람이라고 판단되는 객체와 머리라고 판단되는 객체 탐지 ->
1. 알고 있는 얼굴과 영상내 얼굴이라고 판단되는 것과 비슷한 정도로 비교
'''
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_241104.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_1105_1720.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)
print(f"Loaded face image biden_{i}.png")
else:
print(f"no face in image biden_{i}.png")
####### 영상 처리 ########
'''
(처음부터 얼굴이 잘 나오지 않았을 때)
바꿀 과정.v1 :: 0. 사람이라고 판단되는 객체와 머리라고 판단되는 객체 탐지 ->
1. 머리라고 판단되는 부분을 업 스케일해서 얼굴을 추출해본다
2. 아는 얼굴과 업스케일된 얼굴의 유사도를 측정해서 맞다고 판단되면 몸을 저장
3. 사람이라고 판단되는 객체와 인코딩 저장된 것과 비슷한 것을 찾아서 마스킹 해제 처리 (이게 Loop 처음에 와야한다..)
'''
def check(face_box, people_box, threshold=0.7):
x1, y1, x2, y2 = people_box
left, top, right, bottom = face_box
# 겹치는 영역 계산
overlap_x1 = max(x1, left)
overlap_y1 = max(y1, top)
overlap_x2 = min(x2, right)
overlap_y2 = min(y2, bottom)
# 겹치는 영역의 너비와 높이 계산
overlap_width = max(0, overlap_x2 - overlap_x1)
overlap_height = max(0, overlap_y2 - overlap_y1)
# 겹치는 영역의 면적
overlap_area = overlap_width * overlap_height
face_area = (right - left) * (bottom - top)
# 겹치는 비율 계산 (얼굴 박스 대비)
overlap_ratio = overlap_area / face_area
# 디버그 출력
print("Face Box:", left, top, right, bottom)
print("People Box:", x1, y1, x2, y2)
print("Overlap Ratio:", overlap_ratio)
# 겹치는 비율이 threshold 이상일 경우에만 True 반환
return overlap_ratio >= threshold
# 바디 인코딩 업데이트를 위한 함수
def update_body_history(body_history, body_encoding, max_history=5000):
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(np.argmax(distances))
body_history.append(body_encoding)
print("new_one :", body_encoding)
return body_history
# 변수 초기화
body_history = [] # 바디 인코딩 저장
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.6, iou=0.5, show_labels=True, show_conf=False, tracker="bytetrack.yaml")
## 객체 탕지된 리스트
people_boxes = []
head_boxes = []
### 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)
### 4. 인식된 얼굴 영역 복원
if face_locations:
print("face_detected!!")
for location in face_locations:
left, top, right, bottom = location # 인식된 얼굴의 bbox 받기
# 몸 객체 확인 + 얼굴 객체 확인
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]
body_history = update_body_history(body_history, body_encoding)
#### 5. 얼굴이 인식되지 않았을 때, 객체 중 가장 가까운 몸을 찾는다.
else:
print("no face detected!!")
# 히스토리가 있다면이 오히려 make sense할 것 같다.
# 얼굴이랑 매핑된 몸이 저장된 거니까 그게 있다 없다로 확인하는게 더 당연하니까
if body_history: # Human Detection 리스트가 있다면 (로직이 맞나?)
people_box_score_list = [] # 유사도 저장 리스트
for people_box in people_boxes: # people box를 하나씩 꺼내보기
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))
# 특정 임계치 이하인 경우에만 마스킹 해제
threshold = 25000 # 유사도 임계치 설정
if people_box_score_list:
min_value = min(people_box_score_list)
print("*** min_val( < 25000) : ", min_value)
if min_value < threshold:
x1, y1, x2, y2 = people_boxes[people_box_score_list.index(min_value)]
print("masked_off!!")
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()
*** 천천히 논리를 정리해보자,,,**