您的位置:首页 > 编程语言

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

2017-07-04 23:20 232 查看
该程序同时也解决opencv中文路径,图片不能正常读取的问题。

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

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

import cv2
import numpy as np
from matplotlib import pyplot as plt
import os
import 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版本
# imread

path_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 cv2
import sys
reload(sys)
sys.setdefaultencoding('u8')
path_file = u"sample"
img = cv2.imread(path_file.decode('u8').encode('gbk'),-1)


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

好了,如果大家遇到问题,不能运行的话,请加群:98556420,提出疑问吧。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐