利用SSIM和MSE比较两图像之间的相似度并写入txt文件 我有200对图像,相邻两张图像为一对图像,计算每对图像之间的相似度,并将计算得到的SSIM和MSE结果写入txt文件中,代码如下:
from skimage import measure
import matplotlib.pyplot as plt
import numpy as np
import cv2
import os
from PIL import Image
path = 'E:/dataset/cow/SSIM'
def mse(imageA, imageB):
err = np.sum((imageA.astype("float") - imageB.astype("float")) ** 2)
err /= float(imageA.shape[0] * imageA.shape[1])
return err
if __name__ == '__main__':
i = 0
files = []
filelist = os.listdir(path)
for filename in filelist:
filename = filename.split(".jpg")[0]
files.append(int(filename))
files.sort()
while(1):
if i < len(files):
img1_dir = os.path.join(path,str(files[i])+'.jpg')
img2_dir = os.path.join(path,str(files[i+1])+'.jpg')
original = cv2.imread(img1_dir)
contrast = cv2.imread(img2_dir)
print('--------------')
originals = cv2.cvtColor(original, cv2.COLOR_BGR2GRAY)
contrasts = cv2.cvtColor(contrast, cv2.COLOR_BGR2GRAY)
img2=Image.open(img2_dir)
s = measure.compare_ssim(originals, contrasts)
m = mse(originals, contrasts)
fw = open('./SSIM.txt','a')
fw.write(img1_dir+'-'+img2_dir+'-'+str(s)+'-'+str(m)+ '\n')
fw.close()
print(img1_dir+'-'+img2_dir+'-'+str(s)+'-'+str(m))
i = i+2
else:
break
结果为:
|