※ 우리 서비스의 첫 기능

1단계 ) 입주민의 영상 요청시 해당 입주민의 동선을 트래킹하여 블러처리하여 보여줄수 있음


영상처리 플로우 정리

'''
***Ver1***
[처음 얼굴이 인식된 이후, 마스킹 해제]
0. YOLO로 객체 탐지 (머리와 사람)
1-1. Face_Recognition Package로 객체 '머리'라고 해당하는 부분에서 얼굴을 추출해본다.
1-2. 얼굴이 추출되면, Known_faces에 추가해서 다음번에 머리에서 얼굴을 추출해 확인할 때, 유사도를 체크해서 다음 마스킹 해제 대상을 위해 저장
2. 영상을 블러처리 (선 블러처리)
3-1-1. 얼굴이 인식된 경우, 이미 Known_faces에 추가된 것까지 고려되었기 때문에 유사도가 높은 사람의 마스킹 해제
3-1-2. 마스킹을 해제하면서 같이 객체 '사람'에 해당하는 인코딩을 '바디 히스토리'에 저장한다.
3-2-1. 얼굴이 인식되지 않은 경우(얼굴이 인식된 이후 얼굴이 보이지 않을 때), 인식된 객체 '사람'에 해당하는 인코딩을 '바디 히스토리'와 유클리드 유사도 비교
3-2-2. '바디 히스토리'와의 유사도가 임계값(매직넘버)보다 작으면, 해당 객체 마스킹 해제와 함께 '바디 히스토리'에 객체 '사람'에 해당하는 인코딩 추가
'''
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_complete.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")

####### 영상 처리 ########
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

    # 겹치는 비율이 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)
    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=False, show_conf=True, 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]) # 0 human, 1 head
                x1, y1, x2, y2 = map(int, boxes[i])
                if cl
                    head_boxes.append([x1, y1, x2, y2])
                elif cls == 0:
                    people_boxes.append([x1, y1, x2, y2])

        ### 1-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: # 얼굴 추출
                ### 1-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)

        ### 2. 모든 프레임 블러 처리
        blurred_frame = cv2.GaussianBlur(frame, (99, 99), 39)

        ### 3-1-1. 인식된 얼굴 영역 복원
        if face_locations:
            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]): # 얼굴 bbox가 몸 bbox에 겹치는지 확인
                        blurred_frame[y1:y2, x1:x2] = frame[y1:y2, x1:x2] # 그 객체에 대해서 마스킹 해제
                        body_encoding = cv2.mean(blurred_frame)[:3]
                        ### 3-1-2. 히스토리에 인식된 객체 저장
                        body_history = update_body_history(body_history, body_encoding)

        ### 3-2-1. 얼굴이 인식되지 않았을 때(초기 얼굴 노출), 유사도 비교 이후 마스킹 해제
        else:
            if body_history:
                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] # 기록의 몸과 꺼낸 객체와의 유사도 체크
                    min_distance = min(distances) if distances else float('inf')
                    people_box_score_list.append(min_distance)

                # 특정 임계치 이하인 경우에만 마스킹 해제
                threshold = 20  # 하드 코딩 매직 넘버
                if people_box_score_list: # 인식된 Body가 있다면, Score
                    min_value = min(people_box_score_list)
                    if min_value < threshold:
                        x1, y1, x2, y2 = people_boxes[people_box_score_list.index(min_value)]
                        blurred_frame[y1:y2, x1:x2] = frame[y1:y2, x1:x
                        body_encoding = cv2.mean(frame[y1:y2, x1:x2])[:3]
                        ### 3-2-2. 히스토리에 인식된 객체 저장
                        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()

얼굴과 몸통 부분만 마스킹해제하자

### 4. 인식된 얼굴 영역 복원
if face_locations:
    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]): # 얼굴 bbox가 몸 bbox에 겹치는지 확인
                blurred_frame[top:bottom, left:right] = frame[top:bottom, left:right] # 그 객체에 대해서 마스킹 해제
                blurred_frame[bottom:y2, x1:x2] = frame[bottom:y2, x1:x2] # 그 객체에 대해서 마스킹 해제
                body_encoding = cv2.mean(blurred_frame)[:3]
                body_history = update_body_history(body_history, body_encoding)

#### 5. 얼굴이 인식되지 않았을 때, 객체 중 가장 가까운 몸을 찾는다.
else:
    if body_history:
        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] # 기록의 몸과 꺼낸 객체와의 유사도 체크
            min_distance = min(distances) if distances else float('inf')
            people_box_score_list.append(min_distance)

        # 특정 임계치 이하인 경우에만 마스킹 해제
        threshold = 20  # 유사도 임계치 설정
        if people_box_score_list: # 인식된 Body가 있다면, Score
            min_value = min(people_box_score_list)
            if min_value < threshold:
                x1, y1, x2, y2 = people_boxes[people_box_score_list.index(min_value)]
                for head_box in head_boxes:
                    left, top, right, bottom = head_box
                    if check([left, top, right, bottom], [x1, y1, x2, y2]):
                        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)