이론 관련/2D 그래픽 관련

코사인 유사도

구차니 2025. 8. 14. 17:41

얼굴을 어떻게 인식하나 해서 찾아보는 중

코드에서 아래의 내용이 있어 보니 cosine similarity 라고 나오는데

 

    def get_similarity(self, face_a, face_b):
        """Finds the similarity between two masks
        This is done by taking the vectors in the face mask and finding the
        cosine similarity between them. The formula to find this is:

                                  f(a[n] * b[n])
        sim (a[],b[]) = -----------------------------------
                         sqrt(f(a[n]^2)) * sqrt(f(b[n]^2))

        where:
        - a[] and b[] both represent the array of values of a single face mask
        - f(n) is the sum of values where n is 0 through the length of a[]
          minus 1
        - a[] and b[] have equal lengths and equal indexes map to the same
          points on the face mask

        The idea behind this method is that vectors that have smaller
        vectors between them (independent of magnitude) should in theory be
        similar.
        """
        dot = 0
        a_sum = 0
        b_sum = 0
        for count in range(128):
            dot = dot + (face_a[count] * face_b[count])
            a_sum = a_sum + (face_a[count] * face_a[count])
            b_sum = b_sum + (face_b[count] * face_b[count])
        sim = dot / (np.sqrt(a_sum) * np.sqrt(b_sum))
        return sim

 

대충 검색해보니 취향을 찾기로도 써먹기도 한다고

[링크 : https://wikidocs.net/24603]

[링크 : https://benn.tistory.com/62]

 

[링크 : https://snu-eng.kr/html/2403/SS46_23_special.php]

 

face_recognition 라이브러리에서는 face_encodings로 특징점을 추출하고

compare_faces라는 함수로 유사도를 계산해주는 듯.

import face_recognition
known_image = face_recognition.load_image_file("biden.jpg")
unknown_image = face_recognition.load_image_file("unknown.jpg")

biden_encoding = face_recognition.face_encodings(known_image)[0]
unknown_encoding = face_recognition.face_encodings(unknown_image)[0]

results = face_recognition.compare_faces([biden_encoding], unknown_encoding)

[링크 : https://github.com/ageitgey/face_recognition]