1 查看文件中前10张图片大小
--os.listdir(path) #返回包含path路径中的所有文件名的一个列表
--PIL.Image.open(fname) #打开图片不读入内存,读入内存可用Image.load(fname)
#查看原图尺寸
from PIL import Image
import os
source_horse_path="E:/pycharmProject/horse-or-human/horses/" #存放图片的路径
source_human_path="E:/pycharmProject/horse-or-human/humans/"
horses=os.listdir(source_horse_path) #返回含目标路径中的文件名列表
humans=os.listdir(source_human_path)
horse_files=horses[:10]
human_files=humans[:10]
for filename in horse_files:
path=source_horse_path+filename
img=Image.open(path) #打开图片不读入内存,读入内存用Image.load(path)
print(img.size,sep=';',end=' ') #print(*objects, sep=' ', end='\n', 打印图片尺寸file=sys.stdout,flush=False)
print()
for filename in human_files:
path=source_human_path+filename
img=Image.open(path)
print(img.size,end=' ')
2 利用matplotlib.pyplot 将1中source_horse_path和source_human_path下的前8张图片显示到一张画布
--pyplot.gcf()#获取当前图像,如果pyplot图形堆栈中目前没有图形,则使用figure()创建一个新的图形。
--pyplot.subplot(rows,cols,position) #设置子图的位置row和col为画布一共有几行几列的子图,position为子图位置参数范围[1,rows*cols]
--pyplt.imread(fname)#将图片读入为数组形式
--pyplot.imshow(imgs) #将数据展示为2D图像
--pyplot.show() #显示所有打开的图像
--enumerate(iterable,start=0) #参数iterable为序列,或iterator迭代器。该函数返回元组类型,其中一个为计数值start默认从0开始,另一个为序列或迭代器中的值
--os.path.join(path,*paths) #拼接path和*paths,返回path和*paths所有成员的拼接
import matplotlib.pyplot as plt
#import matplotlib.image as mimg
#设置显示窗口16×16
rows=4 #共4行子图
cols=4 #共4列子图
pic_index=0
fig=plt.gcf() #获取当前图像,如果pyplot图形堆栈中目前没有图形,则使用figure()创建一个新的图形。
fig.set_size_inches(16,16) #设置画布大小16×16,set_size_inches(w, h=None, forward=True) 调整画布大小,forward默认为True,表示自动调整
pic_index+=8
next_horse_pic=[os.path.join(source_horse_path,fname)
for fname in horse_files[pic_index-8:pic_index]] #os.path.join(path,*paths)拼接path和*paths,返回path和*paths所有成员的拼接
next_human_pic=[os.path.join(source_human_path,fname)
for fname in human_files[pic_index-8:pic_index]]
for i, img_path in enumerate(next_horse_pic+next_human_pic):
#enumerate(iterable,start=0) 参数iterable为序列,或iterator迭代器。
#该函数返回元组类型,其中一个为计数值start默认从0开始,另一个为序列或迭代器中的值
sp=plt.subplot(rows,cols,i+1)
sp.axis('off') #不显示坐标轴
img=plt.imread(img_path) #将图像读入为数组,matplotlib.image.imread(fname)也可以将图像读入数组
plt.imshow(img)#将数据显示为二维图像
plt.show() #显示所有打开的图像
#plt.close()#关闭图形窗口
结果展示:
这是作者的学习笔记,在此分享,仅供参考。因为作者水平有限,如有疏漏之处,还望批评指正。