#-*-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)
python 单张图片转换为ubyte格式文件
最新推荐文章于 2023-05-09 15:50:38 发布