如何用几行代码读取目录下所有的图片

来源:互联网 发布:网卡mac地址修改 编辑:程序博客网 时间:2024/06/01 22:36

该程序同时也解决opencv中文路径,图片不能正常读取的问题。

最近写了一个,爬去了较多的妹子资源,但是需要手动的一个一个的去浏览图片,闲太麻烦了,能不能制作一个软件,能直接读取某目录下的所有图片呢?好,说干就干吧。

首先需要引入一些常用的库:

import cv2import numpy as npfrom matplotlib import pyplot as pltimport osimport time

接下来,就是所有的代码量了,直接上干货吧

复制代码
ph = r"E:\image\小清新"def list_dir(path):    for f in os.listdir(path):        f= path+ r"\\"+f        if os.path.isfile(f):            pp = str(f)            print("file is:"+ str(f))            if (pp.find("png") != -1) or (pp.find("jpg") != -1):                #cv2.namedWindow("img",cv2.WINDOW_NORMAL)                print("will to read file:" + str(f))                #img = cv2.imread(f)                img = cv2.imdecode(np.fromfile(f,dtype=np.uint8),-1)   //说明python2的操作在这里不同,需要进行修改                if img is None:                    continue                else:                    img = cv2.resize(img,(1024,768))                cv2.imshow("img",img)                cv2.waitKey(20)        elif os.path.isdir(f):            print("find dir:" + str(f))            list_dir(f)        else:            #list_dir(f)            print("find unknow:" + str(f))    cv2.destroyAllWindows()    print("list_dir end")    list_dir(ph)print("all end")
复制代码

python2和python3需要进行修改的地方:

python3版本
复制代码
# python3版本# imreadpath_file = "sample"img = cv2.imdecode(np.fromfile(path_file,dtype=np.uint8),-1)#imwrite_path = "sample"cv2.imencode('.jpg',img)[1].tofile(_path)
复制代码
python2版本
复制代码
# python 2版本import cv2import sysreload(sys)sys.setdefaultencoding('u8')path_file = u"sample"img = cv2.imread(path_file.decode('u8').encode('gbk'),-1)
复制代码

好了,大功告成,试试只用几行代码就搞定图片浏览器的快感吧。

好了,如果大家遇到问题,不能运行的话,请加群:98556420,提出疑问吧。

原创粉丝点击