如何使用 Python比較兩張圖像并獲得準確度?
本文,將帶你了解如何使用 Python、OpenCV 和人臉識別模塊比較兩張圖像并獲得這些圖像之間的準確度水平。
首先,你需要了解我們是如何比較兩個圖像的。我們正在使用Face Recognition python 模塊來獲取兩張圖像的128 個面部編碼,我們將比較這些編碼。比較結果返回 True 或 False。如果結果為True ,那么兩個圖像將是相同的。如果是False,則兩個圖像將不相同。
128 種面部編碼將如下所示

128 個人臉編碼(人臉標志)
僅當比較結果返回 True 值時,才會打印準確度級別。
現在,讓我們進入本主題的編碼部分,
為了實現這一點,我們需要安裝幾個 python 模塊。為此,只需打開命令提示符或終端,鍵入以下內容。
pip install opencv-python
pip install face-recognition
安裝后,現在是時候導入這些模塊了。然后,我們需要創建一個名為 find_face_encodings(image_path) 的新函數,它獲取圖像位置(路徑)并返回 128 個面部編碼,這在比較圖像時非常有用。
find_face_encodings(image_path) 函數將使用 OpenCV 模塊,從我們作為參數傳遞的路徑中讀取圖像,然后返回使用 face_recognition 模塊中的 face_encodings() 函數獲得的 128 個人臉編碼。
import cv2
import face_recognition
def find_face_encodings(image_path):
# reading image
image = cv2.imread(image_path)
# get face encodings from the image
face_enc = face_recognition.face_encodings(image)
# return face encodings
return face_enc[0]
現在,使用兩個不同的圖像路徑調用 find_face_encodings(image_path) 函數,并將其存儲在兩個不同的變量中,image_1和image_2
# getting face encodings for first image
image_1 = find_face_encodings("image_1.jpg")
# getting face encodings for second image
image_2 = find_face_encodings("image_2.jpg")
現在,我們可以使用編碼執行比較和查找這些圖像的準確性等操作。
· 比較將通過使用 face_recognition 中的 compare_faces() 函數來完成。
· 通過找到 100 和 face_distance 之間的差異來確定準確性。
# checking both images are same
is_same = face_recognition.compare_faces([image_1], image_2)[0]
print(f"Is Same: {is_same}")
if is_same:
# finding the distance level between images
distance = face_recognition.face_distance([image_1], image_2)
distance = round(distance[0] * 100)
# calcuating accuracy level between images
accuracy = 100 - round(distance)
print("The images are same")
print(f"Accuracy Level: {accuracy}%")
else:
print("The images are not same")
輸出——案例 1


Is Same: True
The images are same
Accuracy Level: 64%
輸出——案例 2


Is Same: False
The images are not same
原文標題 : 如何使用 Python比較兩張圖像并獲得準確度?
請輸入評論內容...
請輸入評論/評論長度6~500個字
最新活動更多
-
11月7日立即參評>> 【評選】維科杯·OFweek 2025(第十屆)物聯網行業年度評選
-
11月20日立即報名>> 【免費下載】RISC-V芯片發展現狀與測試挑戰-白皮書
-
即日-11.25立即下載>>> 費斯托白皮書《柔性:汽車生產未來的關鍵》
-
11月27日立即報名>> 【工程師系列】汽車電子技術在線大會
-
11月28日立即下載>> 【白皮書】精準洞察 無線掌控——283FC智能自檢萬用表
-
12月18日立即報名>> 【線下會議】OFweek 2025(第十屆)物聯網產業大會


分享













