#coding =utf-8 ' 1-Converts a picture to an array of binary files 2-reads from binary files and restores to picture ' 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):" "Convert a picture to an array as a binary file" "n = filenames.__len__ () #获取图片个数 result = N Umpy.array ([]) #创建一个空的一维数组 print ("Start converting pictures to arrays") for I in Range (n): image = PiL. Image.open (self.image_base_path+filenames[i]) r,g,b = Image.split () # RGB Channel Separation # Note: The following must be RESHPAE (1024) to make it into a one-dimensional array, otherwise the number of stitching An error has occurred, resulting in the inability to recover the picture R_arr = Numpy.array (R). Reshape (1024) G_arr = Numpy.array (g). Reshape (1024) B_arr = Numpy.array (b). Reshape (1024) # line stitching, similar to the train; end result: A total of n rows, row 3072 columns, the RGB value of a picture Image_arr = Numpy.concatenate ((R_arr,g_arr,b_arr)) results = Numpy.concatenate ((result,image_arr)) result = Result.reshape (n,3072) # Converts a one-dimensional array into a two-dimensional array of n row 3072 columns print ("Transformation array over, start saving as text Pieces ") File_path = Self.data_base_path + ' datA2.bin ' with open (file_path,mode= ' WB ') as F:pickle.dump (result,f) print ("Save Success") def Array_to_image (self,filename : ' Read the data from the binary and revert to the picture ' with open (Self.data_base_path + filename,mode= ' RB ') as F:arr = Pickle.load (f) # Load and deserialize data rows = arr.shape[0] #rows =5 #pdb. Set_trace () #print ("Rows:", rows) arr = Arr.reshape (rows,3,32,32) prin T (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.ima
Ge_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 (' Data
2.bin ')
The contents of the printed array:
Binary-> picture) __python ">
Picture converted from data
Binary-> picture) __python ">