如何在Python中将原始图像转换为PNG格式?

8

我有一个包含200多个原始图像的文件夹,我想将它们全部转换为png或其他格式,在C语言中这很容易,但在Python中我不知道该怎么做。

我找到了这段代码:

#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')

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

或者,可以在命令行中使用ImageMagick:convert *.raw --format png - Li-aung Yip
或者,另一种选择是使用Python的ImageMagick绑定。 - Li-aung Yip
1
在C语言中这很容易,你能指出来吗? - jsbueno
@jsbueno,我说“在C语言中很容易”是因为我看到了很多将“raw”转换为其他格式的代码片段,但我只看到了1个Python版本的代码片段。 - user
2个回答

10
应该是这样的:
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")

使用手册另一个SO问题

第一个参数是图像模式,可以是以下任何一种:

  • 1(1位像素,黑白,每字节存储一个像素)
  • L(8位像素,黑白)
  • P(8位像素,使用调色板映射到任何其他模式)
  • RGB(3x8位像素,真彩色)
  • RGBA(4x8位像素,带透明度掩码的真彩色)
  • CMYK(4x8位像素,颜色分离)
  • YCbCr(3x8位像素,彩色视频格式)
  • I(32位有符号整数像素)
  • F(32位浮点像素)

"F;16" 不再作为无符号整数成立。我认为现在它们将其用作浮点数。如果我没有记错的话。 - majidarif
这个答案已经不准确了。请参考:https://dev59.com/d2LVa4cB1Zd3GeqPtBcy#45445890 - Harshit Jindal
怎么做这个的反向操作?我有一个 ndarray,想要将其写成 (.raw) 格式的图像? - Uday Posia

9
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

这是适合我的一个解决方案


如何进行反向操作?我有一个ndarray,想要将其写成(.raw)格式的图像? - Uday Posia

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接