python将自己的图片实现与数

我也是最进才开始接触深度学习,因为老师的项目,借鉴了一些 前辈的博客, 点击打开链接,前辈的博客我借鉴了部分。

cifar-10这个数据相信很多接触过机器学习的人都肯定有所了解。今天,我们通过cifar-10存储将图片转化为可训练数据的思路将我们自己的图片转化为Python格式的数据。

图片大小为32*32。现在我们来聊聊步骤: 
①图片转化为数组并存为二进制文件: 
1.使用PIL打开图片,并将其分离为RGB三个通道 
2.利用numpy分别将RGB三个通道转化为数组并将其转为一维数组 (32*32->1024) 
3.将RGB三个一维数组(1024)拼接成一个一维数组(3072),再接入大数组,最终形成n*3072的一维数组,最终在reshape成n行3072列的二维数组 
4.使用pickle序列化数组对象并保存到文件里

②从二进制文件中读取数据并重新恢复为图片: 
1.打开数据文件并使用pickle加载并反序列化数据得到数组 
2.使用PIL分别得到每张图片的RGB通道,然后将其合并 
3.使用matplotlib显示图像 
4.保存图像

我所用的是python3.6,pycharm。

from __future__ import  print_function
import numpy as np
import PIL.Image as Image
import pickle as p
import matplotlib.pyplot as pyplot
import  os

result=np.array([])
list1=[]
image_path='C:/Users/ZZZZdd/Desktop/Date/train'
for filenames in os.listdir(r'C:/Users/ZZZZdd/Desktop/Date/train'):
     list1.append(filenames)
#      print(filenames)
# print(list1)
n=len(list1)
# print(n)
for i in range(n):
    image=Image.open(image_path+'/'+list1[i])
# print(image_path+'/'+list1[1])
    image=image.resize([32,32])
    r,g,b=image.split()
    # 注意:下面一定要reshpae(1024)使其变为一维数组,
    # 否则拼接的数据会出现错误,导致无法恢复图片
    r_arr=np.array(r).reshape(1024)
    g_arr=np.array(g).reshape(1024)
    b_arr=np.array(b).reshape(1024)
    # 行拼接,类似于接火车;最终结果:共n行,
    # 一行3072列,为一张图片的rgb值
    image_arr=np.concatenate((r_arr,g_arr,b_arr))
    result=np.concatenate((result,image_arr))
result=result.reshape(n,3072)# 将一维数组转化为count行3072列的二维数组
print('转换数组成功')
file_path='C:/Users/ZZZZdd/Desktop/Date/data2.bin'
with open(file_path,mode='wb')as f :
    p.dump(result,f)
print('保存文件成功')
with open (file_path,mode='rb')as f :
    arr=p.load(f) # 加载并反序列化数据
rows=arr.shape[0]
# print(rows)
arr=arr.reshape(rows,3,32,32)
# print(arr.shape)
for index in range(rows):
    a=arr[index]
    # 得到RGB通道
    r=Image.fromarray(a[0]).convert('L')
    g=Image.fromarray(a[1]).convert('L')
    b =Image.fromarray(a[2]).convert('L')
    image=Image.merge('RGB',(r,g,b))
    #显示图片
    pyplot.imshow(image)
    pyplot.show()
    image.save(file_path+'result'+str(index)+'png','png')
我将项上传,需要的朋友可以去我这下载。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值