# -*- coding:utf-8 -*-
import pickle,pprint
from PIL import Image
import numpy as np
import os
import matplotlib.image as plimg
class DictSave(object):
def __init__(self,filenames):
self.filenames = filenames
self.arr = []
self.all_arr = []
print
def image_input(self,filenames):
for filename in filenames:
self.arr = self.read_file(filename)
if self.all_arr==[]:
self.all_arr = self.arr
else:
self.all_arr = np.concatenate((self.all_arr,self.arr))
def read_file(self,filename):
im = Image.open(filename)#打开一个图像
# 将图像的RGB分离
r, g, b = im.split()
# 将PILLOW图像转成数组
r_arr = plimg.pil_to_array(r)
g_arr = plimg.pil_to_array(g)
b_arr = plimg.pil_to_array(b)
# 将60*180二维数组转成1024的一维数组
r_arr1 = r_arr.reshape(10800)
g_arr1 = g_arr.reshape(10800)
b_arr1 = b_arr.reshape(10800)
# 3个一维数组合并成一个一维数组,大小为32400
arr = np.concatenate((r_arr1, g_arr1, b_arr1))
return arr
def pickle_save(self,arr):
print ("正在存储")
# 构造字典,所有的图像数据都在arr数组里,这里只存图像数据,没有存label
contact = {'data': arr}
f = open('contact', 'wb')
pickle.dump(contact, f)#把字典存到文本中去
f.close()
print ("存储完毕")
if __name__ == "__main__":
filenames = [os.path.join("%d.png" % i) for i in range(0, 100)] #100个图像
ds = DictSave(filenames)
ds.image_input(ds.filenames)
ds.pickle_save(ds.all_arr)
print ("最终数组的大小:"+str(ds.all_arr.shape))
将图片保存为cifar-10类似的格式
最新推荐文章于 2022-11-06 19:54:16 发布
本文介绍了一种使用Python处理图像数据的方法,通过读取图像文件并将其转换为数组形式进行存储。具体步骤包括:利用PIL库加载图像,将图像的RGB通道分离,并将每个通道的数据转换为一维数组,最后将这些数组合并并使用pickle库进行持久化存储。
3万+





