2012-03-29 64 views
3

我有一个包含超过200 raw图像的文件夹,我想他们都转换为png或任何其他形式,在C这是很容易的,但在python我不知道它是如何做如何将原始图像转换为Python中的PNG?

我发现这个片段

#import struct 
import numpy, array, PIL, Image 
from struct import * 

#declarations 
arr1D = array.array('H') #H is unsigned short 

#------------------------------------ 
#read 16 bit unsigned raw depth image 
#------------------------------------ 
w   = 640 
h   = 480 
fid  = open('/home/salman/salman/NiSimpleRead_salman/data/200.raw') 
#fid   = open('/home/salman/test.raw') 
numBytes = w*h 
arr1D.read(fid, numBytes) 
fid.close() 

#---------------------------------------------------- 
#convert to float numpy array -> scale -> uint8 array 
#---------------------------------------------------- 
numarr = numpy.array(arr1D, dtype='float'); 
numarr = 255 - (numarr*255.0/numarr.max()) 
numarr.shape = (h,w) 
numarr = numarr.astype('uint8') 

#====================== 
#IMAGES 
#====================== 

#2D numpy array -> image 
#----------------------- 
img  = Image.fromarray(numarr); #print data.dtype.name 

#image view and save 
#------------------- 
#img.show() 
img.save('/home/salman/test.png') 

这是我能找到的唯一代码片段,这是正确的方法吗?

+0

或者,在命令行中使用ImageMagick中的一个:'转换*。RAW --format png'。 – 2012-03-29 11:25:36

+0

或者,或者交替使用Python的ImageMagick绑定。 – 2012-03-29 11:26:17

+1

“在C中很容易” - 你能指出一点吗? – jsbueno 2012-03-29 13:14:58

回答

6

它应该是这样的:

rawData = open("foo.raw" 'rb').read() 
imgSize = (x,y) 
# Use the PIL raw decoder to read the data. 
# the 'F;16' informs the raw decoder that we are reading 
# a little endian, unsigned integer 16 bit data. 
img = Image.fromstring('L', imgSize, rawData, 'raw', 'F;16') 
img.save("foo.png") 

使用the handbookanother SO question

的第一个参数是图像模式,并且可以是任何从:

  • 1(1位的像素,黑色和白色,存储有每字节的一个像素)
  • L(8位像素,黑色和白色)
  • P(8比特象素,使用彩色调色板)
  • RGB(3×8比特象素,真彩色)
  • RGBA映射到任何其他模式(4×8比特象素,真彩与透明度面具)
  • CMYK(4×8比特象素,分色)
  • 的YCbCr(3×8比特象素,彩色视频格式)
  • I(32位带符号整数像素)
  • F(32位浮点像素)
0
from PIL import Image 
rawData = open("foo.raw", 'rb').read() 
imgSize = (703,1248)# the image size 
img = Image.frombytes('L', imgSize, rawData) 
img.save("foo.jpg")# can give any format you like .png 

是为我工作