import os
from PIL import Image
image_path = 'F:/AI平台/测试资源/风机叶片/原图/'
# 遍历文件夹及其子文件夹中的文件,并存储在一个列表中
# 输入文件夹路径、空文件列表[]
# 返回 文件列表Filelist,包含文件名(完整路径)
def get_filelist(dir, Filelist):
newDir = dir
if os.path.isfile(dir):
"""如果path是文件而非文件夹,将文件路径加入Filelist"""
# print(os.path(dir))
Filelist.append(dir)
# # 若只是要返回文件文,使用这个
# Filelist.append(os.path.basename(dir))
elif os.path.isdir(dir):
"""如果path是文件夹,"""
for s in os.listdir(dir):
# 如果需要忽略某些文件夹,使用以下代码
# if s == "xxx":
# continue
newDir = os.path.join(dir, s) #join函数,将dir和s拼接为dir\s
get_filelist(newDir, Filelist) #调用本函数
return Filelist
def transtpicsize(Start_path,i,sizelist):
# print list
im = Image.open(Start_path)
w, h = im.size
print('宽w,高h:', w, h)
# print w,h
# iphone 5的分辨率为1136*640,如果图片分辨率超过这个值,进行图片的等比例压缩
k=0
for j in sizelist:
w2=int(j['w1'])
h2=int(j['h1'])
print('宽,高:',w2,h2)
if (w >w2-100 and w<w2+100 and h>h2-100 and h<h2+100):
h_new = h2
w_new = w2
out = im.resize((w_new, h_new), Image.ANTIALIAS)
new_pic = str(i)+Start_path[-4:]
print('k',k)
l=os.path.join('F:/test-process/picstranst/'+str(k),new_pic)
out.save(l)
k = k + 1
# else:
# out = im.resize((w2, h2), Image.ANTIALIAS)
# new_pic = str(i)+Start_path[-4:]
# l=os.path.join('F:/test-process/picstranst/othersize/',new_pic)
# out.save(l)
# k = k + 1
if __name__ == '__main__':
sizelist=[]
max_w=6720.0
min_w=500.0
while min_w<max_w:
min_w=min_w+100
min_h=min_w*1080/720
size1={'w1':min_w,'h1':min_h}
sizelist.append(size1)
max_w = 6720.0
min_w = 500.0
while min_w<max_w:
min_w=min_w+100
min_h=min_w*308/400
size1={'w1':min_w,'h1':min_h}
sizelist.append(size1)
list = get_filelist('F:\AI平台\测试资源\安全帽\VOC2028\JPEGImages/', [])
# print(len(list))
j=0
i = 0
'''建len(sizelist)个文件夹,所有图片按照长款,每100个单位尺寸切割为一种尺寸,并存储到对应的文件夹下面'''
while j<len(sizelist):
if os.path.exists(str(j)):
j = j + 1
pass
else:
os.mkdir(str(j))
j=j+1
for e in list:
print('e',e)
if 'jpg' in e or 'png' in e or 'JPG' in e or 'PNG' in e:
print(i)
transtpicsize(Start_path=e,i=i,sizelist=sizelist)
i=i+1