Python(1):简单图像处理(图片->二进制->图片)

#coding=utf-8

'''
1-将图片转化为数组并存为二进制文件
2-从二进制文件中读取数并重新恢复为图片
'''

from __future__ import print_function
import numpy
import PIL.Image 
import pickle
import matplotlib.pyplot
import pdb

class Operation(object):
	image_base_path = "../image/"
	data_base_path = "../data/"

	def image_to_array(self,filenames):
		"""
		将图片转化为数组并存为二进制文件
		"""
		n = filenames.__len__()#获取图片个数
		result = numpy.array([]) #创建一个空的一维数组
		print("开始将图片转化为数组")
		for i in range(n):
			image = PIL.Image.open(self.image_base_path+filenames[i])
			r,g,b = image.split() # rgb通道分离
			# 注意:下面一定要reshpae(1024)使其变为一维数组,否则拼接的数据会出现错误,导致无法恢复图片
			r_arr = numpy.array(r).reshape(1024)
			g_arr = numpy.array(g).reshape(1024)
			b_arr = numpy.array(b).reshape(1024)
			# 行拼接,类似于接火车;最终结果:共n行,一行3072列,为一张图片的rgb值
			image_arr = numpy.concatenate((r_arr,g_arr,b_arr))
			result = numpy.concatenate((result,image_arr))

		result = result.reshape(n,3072) # 将一维数组转化为n行3072列的二维数组
		print("转化数组over,开始保存为文件")
		file_path = self.data_base_path + 'data2.bin'
		with open(file_path,mode='wb') as f:
			pickle.dump(result,f)
		print("保存成功")

	def array_to_image(self,filename):
		'''
		从二进制文件中读取数据并重新恢复为图片
		'''
		with open(self.data_base_path + filename,mode='rb') as f:
			arr = pickle.load(f) #加载并反序列化数据
		rows = arr.shape[0] #rows=5
		#pdb.set_trace()
		#print("rows:",rows)
		arr = arr.reshape(rows,3,32,32)
		print(arr)	#打印数组
		for index in range(rows):
			a = arr[index]
			#得到RGB通道
			r = PIL.Image.fromarray(a[0]).convert('L')
			g = PIL.Image.fromarray(a[1]).convert('L')
			b = PIL.Image.fromarray(a[2]).convert('L')
			image = PIL.Image.merge("RGB",(r,g,b))
			#显示图片
			matplotlib.pyplot.imshow(image)
			matplotlib.pyplot.show()
			#image.save(self.image_base_path + "result" + str(index) + ".png",'png')

if __name__ == "__main__":
	my_operator = Operation()
	images = []
	for j in range(5):
		images.append(str(j) + ".png")
#	my_operator.image_to_array(images)
	my_operator.array_to_image('data2.bin')



打印的数组内容:

从数据转换来的图片



  • 7
    点赞
  • 74
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值