python進行圖片相似度對比的兩種實現(xiàn)方法
Python提供了一些庫和工具可以用于圖片的相似度比對。下面介紹兩種常用的方法:
1、感知哈希(Perceptual Hashing)
這種方法通過計算圖像的哈希值來表示圖像的特征,從而進行相似度比對。
常用庫:imagehash 和 phash
具體代碼如下:
from PIL import Image
import imagehash
# 生成圖像的感知哈希
hash1 = imagehash.average_hash(Image.open('image1.jpg'))
hash2 = imagehash.average_hash(Image.open('image2.jpg'))
# 計算相似度
similarity = 1 - (hash1 - hash2) / len(hash1.hash) # 范圍為0到1,值越大表示相似度越高
print(similarity)2、結(jié)構(gòu)相似性(Structural Similarity)
這種方法通過比較圖像的結(jié)構(gòu)、紋理和亮度等特征來衡量相似度。
常用庫:scikit-image
具體代碼如下:
from PIL import Image
from skimage import metrics
from skimage.transform import resize
# 打開并調(diào)整圖像大小
image1 = Image.open('image1.jpg')
image2 = Image.open('image2.jpg')
image1 = image1.resize((500, 500)) # 調(diào)整圖像1的大小為500x500
image2 = image2.resize((500, 500)) # 調(diào)整圖像2的大小為500x500
# 將圖像轉(zhuǎn)換為灰度圖像
image1_gray = image1.convert("L")
image2_gray = image2.convert("L")
# 將圖像轉(zhuǎn)換為NumPy數(shù)組
image1_array = np.array(image1_gray)
image2_array = np.array(image2_gray)
# 計算結(jié)構(gòu)相似性指數(shù)(SSIM)
similarity = metrics.structural_similarity(image1_array, image2_array)
# 將相似性指數(shù)轉(zhuǎn)換為相似度(范圍0到1,值越大表示相似度越高)
similarity = (similarity + 1) / 2
print(similarity)到此這篇關(guān)于python進行圖片相似度對比的兩種實現(xiàn)方法的文章就介紹到這了,更多相關(guān)python 圖片相似度對比內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python常見數(shù)據(jù)結(jié)構(gòu)之棧與隊列用法示例
這篇文章主要介紹了Python常見數(shù)據(jù)結(jié)構(gòu)之棧與隊列用法,結(jié)合實例形式簡單介紹了數(shù)據(jù)結(jié)構(gòu)中棧與隊列的概念、功能及簡單使用技巧,需要的朋友可以參考下2019-01-01
Python調(diào)用requests庫實現(xiàn)自動化發(fā)牌功能
Python 時間操作例子和時間格式化參數(shù)小結(jié)
Python使用Crypto庫實現(xiàn)加密解密的示例詳解
python實現(xiàn)基本進制轉(zhuǎn)換的方法

