python3寻找相同图片
2021/5/17 12:29:00
本文主要是介绍python3寻找相同图片,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
**契机:**项目中图片过多,导致太大,找到相同图片,减少项目大小(快来帮我看看,为啥我的“hello world ”有一个G)
思路:
1.百度上一堆都是找相识图片(计算hash的偏差),我试过了,计算的图片哈希值偏差设置成0也不是相同图片(好像,是为了提高速度,他们首先将图片进行的缩减,还有的使用灰度处理)等等,效果极其不好(找相同图片不好,找相似还不错)
2.我就开始,想找相同文件,利用文件MD5,但测试后明显不行,美术就是导不同的文件出来(即使内容相同),MD5也是不同,这只能找到(有程序在不同地方存放相同文件)
3.我开始想读取图片的值直接进行对比,效果是我想要的,就是可能运行的比较慢
使用的方法:
python3 xxx.py(下面的Python文件) file(你项目的文件夹)
结果:
会在你的文件夹下,生成一个表格,表格内有相同图片的信息
需要安装什么库,自己看着安装吧(xlwt和PIl),我装太多了,没有安装库,就可以了
**新增:**感觉使用md5解决使用了相同文件就行了,没必要把全部相同图片找出来,,,有空重新写下加上,,因为发现美术动画会有一定的相同图片,,,只要保证不同程序导入图片时,别导入相同文件,就能省下不少空间
import os import sys from PIL import Image,ImageDraw,ImageFile import xlwt # 图片集合 list = [] list2 = [] def compare_image_with_hash(): # 设置表格横列 b = 0 book_name_xls = sys.argv[1] + ".xls" workbook = xlwt.Workbook() # 新建一个工作簿 sheet = workbook.add_sheet("itme") for i in range(len(list)): pd = True if list2[i] : continue for j in range(i+1,len(list)): if list2[j] : continue if compare_image(list[i], list[j]): if pd : pd = False print(list[i]) print("相同的图片") sheet.write(b, 0, list[i]) # 向表格中写入数据(对应的行和列) sheet.write(b, 1, "相同的图片") # 向表格中写入数据(对应的行和列) b = b + 1 list2[j] = True print(list[j]) sheet.write(b, 1, list[j]) # 向表格中写入数据(对应的行和列) b = b + 1 if bool(1 - pd) : print("结束") workbook.save(book_name_xls) # 保存工作簿 # 完全相同的图片 def compare_image(img_file1, img_file2): if img_file1 == img_file2: return True fp1 = open(img_file1, 'rb') fp2 = open(img_file2, 'rb') img1 = Image.open(fp1) img2 = Image.open(fp2) ImageFile.LOAD_TRUNCATED_IMAGES = True b = img1 == img2 fp1.close() fp2.close() return b # 读取文件 def list_all(dir_name): for dirpath, dirnames, filenames in os.walk(dir_name): for filename in filenames: src_path = dirpath + '/' + filename suffix = filename[-4:] if suffix != '.png' : continue list.append(src_path) list2.append(False) # compare_image_with_hash(src_path, dir_name) compare_image_with_hash() if __name__ == '__main__': if len(sys.argv) == 1: print('must has name dir') exit(-1) if len(sys.argv) >= 2: list_all(sys.argv[1])
这篇关于python3寻找相同图片的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-04Python外包有哪些常见的主要库-icode9专业技术文章分享
- 2024-10-02基于深度学习的钢铁缺陷检测系统(yolov8、注意力机制、PyQt5界面、Python)
- 2024-10-01怎么用python搭建一个系统-icode9专业技术文章分享
- 2024-09-30Python基础入门教程
- 2024-09-30获取参数学习:Python中的基础教程
- 2024-09-30Python编程基础详解
- 2024-09-29点击加载学习:Python编程基础教程
- 2024-09-29数据科学五大Python前端库:第二部分
- 2024-09-27使用python 将ETH账户的资产打散
- 2024-09-26Python编程基础