python 单张图片转换为ubyte格式文件

#-*-encoding=utf-8-*-
import os
from PIL import Image
from array import *

def toUbyte(filename):

	data_image = array('B')
	data_label = array('B')
	
	# print(filename)
	# print(filename.split('/')[2])
	label = int(ord(filename.split('/')[2])) # 此处取出路径中标签名(即图片所在文件夹的名dog)

	Im = Image.open(filename).convert("L") # Image将三通道转为单通道

	pixel = Im.load()
	width, height = Im.size
	print(width, height)

	for x in range(0,width):
		for y in range(0,height):
			data_image.append(pixel[y,x])

	data_label.append(label) # labels start 

	hexval = "{0:#0{1}x}".format(len(FileList),10) # number of files in HEX

	header = array('B')
	header.extend([0,0,8,1])
	header.append(int('0x'+hexval[2:][:2],16))
	header.append(int('0x'+hexval[4:][:2],16))
	header.append(int('0x'+hexval[6:][:2],16))
	header.append(int('0x'+hexval[8:][:2],16))

	data_label = header + data_label

	hexval = "{0:#0{1}x}".format(width,10) # width in HEX
	header.append(int('0x'+hexval[2:][:2],16))
	header.append(int('0x'+hexval[4:][:2],16))
	header.append(int('0x'+hexval[6:][:2],16))
	header.append(int('0x'+hexval[8:][:2],16))
	hexval = "{0:#0{1}x}".format(height,10) # height in HEX
	header.append(int('0x'+hexval[2:][:2],16))
	header.append(int('0x'+hexval[4:][:2],16))
	header.append(int('0x'+hexval[6:][:2],16))
	header.append(int('0x'+hexval[8:][:2],16))

	header[3] = 3 # Changing MSB for image data (0x00000803)

	data_image = header + data_image
    # 转换后的文件放在ubyte文件夹下
	output_file = open('ubyte/t10k-images-idx3-ubyte', 'wb')
	data_image.tofile(output_file)
	output_file.close()

	output_file = open('ubyte/t10k-labels-idx1-ubyte', 'wb')
	data_label.tofile(output_file)
	output_file.close()
	
	# gzip转换为.gz文件
	#os.system('gzip '+'ubyte/t10k-images-idx3-ubyte')
	#os.system('gzip '+'ubyte/t10k-labels-idx1-ubyte')
	
if __name__ == '__main__':
	filename = 'Image/test/dog/dog_1.jpg'
	toUbyte(filename)
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值