'''测试16bit和32bit图像的python存储方法'''import numpy as np import scipy.miscfrom PIL import Image # 用已有的8bit和16bit图作存储测试path16 = 'D:/Py_exercise/lena16.tif'path8 = 'D:/Py_exercise/lena8.tif'tif16 = scipy.misc.imread(path16) #<class 'numpy.uint16'>tif8 = scipy.misc.imread(path8) #<class 'numpy.uint8'>print(np.shape(tif16),type(tif16[0,0])) print(np.shape(tif8),type(tif8[0,0])) print() save16 = 'D:/Py_exercise/lena16_save.tif'save8 = 'D:/Py_exercise/lena8_save.tif'scipy.misc.imsave(save16, tif16) #--> 8bitscipy.misc.imsave(save8, tif8) #--> 8bit # Create a mat which is 64 bit floatnrows = 512ncols = 512np.random.seed(12345)y = np.random.randn(nrows, ncols)*65535 #<class 'numpy.float64'>print(type(y[0,0]))print() # Convert y to 16 bit unsigned integersz16 = (y.astype(np.uint16)) #<class 'numpy.uint16'>print(type(z16[0,0]))print() # 用产生的随机矩阵作存储测试save16 = 'D:/Py_exercise/lena16_save1.tif'scipy.misc.imsave(save16, z16) #--> 8bit im = Image.frombytes('I;16', (ncols,nrows), y.tostring())im.save('D:/Py_exercise/lena16_save21.tif') #--> 16bitim = Image.fromarray(y) im.save('D:/Py_exercise/lena16_save22.tif') #--> 32bitim = Image.fromarray(z16) im.save('D:/Py_exercise/lena16_save23.tif') #--> 16bit # 归一化后的np.float64仍然存成了uint8zNorm = (z16-np.min(z16))/(np.max(z16)-np.min(z16)) #<class 'numpy.float64'>print(type(zNorm[0,0]))save16 = 'D:/Py_exercise/lena16_save11.tif'scipy.misc.imsave(save16, zNorm) #--> 8bit # 归一化后的np.float64直接转8bit或16bit都会超出阈值,要*255或*65535# 如果没有astype的位数设置,会直接存成32bitzImg = (zNorm*65535).astype(np.uint16) im = Image.fromarray(zImg)im.save('D:/Py_exercise/lena16_save31.tif') #--> 16bitim = Image.fromarray(zNorm)im.save('D:/Py_exercise/lena16_save32.tif') #--> 32bit(0~1)