본문 바로가기
공부공부/2023 쌓여가는 나의 지식~

Mediapipe를 이용한 얼굴 모자이크(Blur)처리

by Lee_story_.. 2023. 10. 13.
728x90

 

Mediapipe란

구글에서 개발한 오픈소스 플랫폼으로

각종 딥러닝을 통한 인식들을 지원합니다. 

 

주로 사람의 손, 얼굴, 각 관절의 Keypoint들을 추적하여 인식하는 기능을 가지고 있습니다. 

 

https://github.com/google/mediapipe

 

GitHub - google/mediapipe: Cross-platform, customizable ML solutions for live and streaming media.

Cross-platform, customizable ML solutions for live and streaming media. - GitHub - google/mediapipe: Cross-platform, customizable ML solutions for live and streaming media.

github.com

 

 

사용법 또한 간단합니다.

 

 

아래처럼 라이브러리를 설치해주고

pip install mediapipe

 

 

 

얼굴인식 모델을 불러와 사용해주기만 하면 끝!

 

with mp_face_detection.FaceDetection(
    model_selection=1, min_detection_confidence=0.5) as face_detection:
    
    
    
    
  ....



face_detection.process(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))

 

 

이제 인식결과를 출력해주는 부분을 만들어 봅시다. 코드부분을 작성해줍시다.

with mp_face_detection.FaceDetection(
    model_selection=1, min_detection_confidence=0.5) as face_detection:
  
  for idx, file in enumerate(IMAGE_FILES):
      image = cv2.imread(file)
      print(file+"인식시작")
      
      results = face_detection.process(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))

      boundList=[]

      if not results.detections:
        print("인식된 얼굴이 없습니다.")
        continue

      annotated_image = image.copy()# 박스만  그려줄 이미지

      for detection in results.detections: 
        mp_face_detection.get_key_point(
            detection, mp_face_detection.FaceKeyPoint.NOSE_TIP)
        
        mp_drawing.draw_detection(annotated_image, detection)

        tempDetect=detection.location_data.relative_bounding_box
        boundList.append(tempDetect)
        
        
        cv2.imwrite(str(idx) + '.png', annotated_image)

results에 인식결과들을 저장해주고 draw_detection을 통해 하얀색 사각 박스를 그려줍시다.

 

 

 

정면부는 아래 사진처럼 잘 되는것 같습니다.

 

 

마스크를 쓰고 있거나 확실치 않은 얼굴은 잘 인식되지 않는것 같습니다...

(너무 많아서 그런가..?) 

 

<출처 https://www.hankookilbo.com/News/Read/202005061378388912>

 

 

정확하지 않으면 인식하지 못하는것 같습니다.

하지만 속도는 매우 빠르기 때문에 높은 정확도가 필요하지 않다면 유용하게 사용할 수 있을것 같습니다!

 

 

이제 박스가 아닌 모자이크 처리 (= blur)코드!

 imagePIL = Image.open(file)
      image_width, image_height = imagePIL.size

      for point in boundList: 
          x_start, y_start = int(point.xmin * image_width), int(point.ymin * image_height)
          x_end, y_end = int((point.xmin + point.width) * image_width), int((point.ymin + point.height) * image_height)
          
          # 인식 결과 부분 잘라서
          cropped_image = imagePIL.crop((x_start, y_start, x_end, y_end))
          
          # 블러 = 모자이크 처리해서
          blurred_image = cropped_image.filter(ImageFilter.BoxBlur(30))
          
          # 원래위치에 붙여넣기
          imagePIL.paste(blurred_image, (x_start, y_start, x_end, y_end))

 

이전 인식결과 사각 박스의 각 포인트를 불러와(인식하면서 boundList에 저장함) 

 

filter함수를 통해 흐려지게 만들어 줍시다.

 

 

 

그리고 마지막으로 저장

file_name = os.path.basename(file)
      file_name = os.path.splitext(file_name)[0]

      imagePIL.save('./Result/'+file_name+'.png')

    
      cv2.imwrite('./Result/'+file_name + '_box.png', annotated_image)

 

여기까지 끝!

 

 

 

 

잘 되는것 같습니다!

 

 

 

 

모자이크 처리를 하는데에는 다양한 방법이 있었던 것 같습니다. 

이번엔 가장 간단한 ImageFilter를 사용해서 구현해 보았습니다!

 

 

 

 

 

틀린점이 있다면 댓 달아주세요!

댓글