#-*- coding:utf-8 -*- import cv2 import os from nt import chdirclass CompareImage(object):def __init__(self, image_1_path, image_2_path):self.minimum_commutative_image_diff = 0.25 self.image_1_path = image_1_pathself.image_2_path = image_2_path#返回值为10000图像数据相同 def compare_image(self):image_1 = cv2.imread(self.image_1_path, 0)image_2 = cv2.imread(self.image_2_path, 0)img_hist_diff, img_template_diff, commutative_image_diff = self.get_image_difference(image_1, image_2)if img_hist_diff<0.1 and img_template_diff<0.1:if commutative_image_diff < self.minimum_commutative_image_diff:return commutative_image_diffreturn 10000 # random failure value @staticmethod def get_image_difference(image_1, image_2):first_image_hist = cv2.calcHist([image_1], [0], None, [256], [0, 256])second_image_hist = cv2.calcHist([image_2], [0], None, [256], [0, 256])img_hist_diff = 1-cv2.compareHist(first_image_hist, second_image_hist,0)img_template_probability_match = cv2.matchTemplate(first_image_hist, second_image_hist, cv2.TM_CCOEFF_NORMED)[0][0]img_template_diff = 1 - img_template_probability_match# taking only 10% of histogram diff, since it's less accurate than template method commutative_image_diff = (img_hist_diff / 5) + img_template_diffreturn [img_hist_diff,img_template_diff,commutative_image_diff]#打开文件夹 def open_file(file_name):for root, dirs, files in os.walk(file_name):temp = 0 for i in range(len(files)):#files[i].index('chong')!=-1找到字符串,图像已经比较过 if files[i].find('f') != -1:continue # #初始值 my_file = os.path.join(root, files[i])for j in range(len(files)-1):# print my_file, '===' # 比较两张图相似点,相同则重命名第二张图 if files[j].find('f')!=-1:continue compare_image = CompareImage(os.path.join(root, files[i]), os.path.join(root, files[j+1]))image_difference = compare_image.compare_image()print image_differenceif image_difference != 10000:print os.path.join(root, files[j])# 图像相同重命名 148.8_543.6_18020180320233355_180 # print os.path.join(root,files[j][0:files[j].find('.jpg')]+"_chong.jpg") pre = os.path.join(root, files[j])# chdir(os.path.dirname(pre)) try:os.rename(pre, os.path.join(root, str(temp) + "_chong_") + str(j) + ('.jpg'))except WindowsError:pass # try: # print os.path.join(root,str(temp)+"_f_")+str(j)+('.jpg') # os.rename(pre,os.path.join(root,str(temp)+"_f_")+str(j)+('.jpg')) # except WindowsError: # pass temp+=1 if __name__ == '__main__':file_name = 'F:\\test\\test' open_file(file_name)# chdir(file_name+'/1.jpg')
详细解决方案
直方图比较图像,相似度小于5时重名名
热度:47 发布时间:2023-09-30 22:04:25.0
相关解决方案