PIL图像从RGB转换为YCbCr导致4个通道而不是3个并且像RGB一样运行

絢瀬絵*_*瀬絵里 7 python python-imaging-library

好吧,标题是非常自我解释的.我有一个图像文件,我想分别分为Y,Cb和Cr.打开文件后,将其从RGB(打开图像文件时的默认模式)转换为YCbCr,然后使用numpy.array()将其转换为数组,产生一个包含4个通道的2D数组,这不是根据http://www.nmt.edu/tcc/help/pubs/pil/pil.pdf中的文档我的预期

这是我在翻译中所做的事情:

ImageFile = Image.open('filePath', 'r')
ImageFile = ImageFile.convert('YCbCr')
ImageFileYCbCr = numpy.array(ImageFile)
ImageFileYCbCr
Run Code Online (Sandbox Code Playgroud)

结果

array([[[103, 140, 133,  95],
    [140, 133,  91, 141],
    [132,  88, 141, 131],
    ..., 
    [129,  65, 146, 129],
    [ 64, 146, 130,  65],
    [146, 129,  64, 147]],

   [[129,  64, 147, 129],
    [ 62, 149, 130,  62],
    [149, 130,  62, 149],
    ..., 
Run Code Online (Sandbox Code Playgroud)

当我把它分成它的频道时

ImageFileY = copy.deepcopy(ImageFileYCbCr) # to make a separate copy as array is immutable
ImageFileY[:,:,1] *= 0
ImageFileY[:,:,2] *= 0
ImageFileY[:,:,3] *= 0
ImageFileYOnly = Image.fromarray(ImageFileY)
ImageFileYOnly.show()
Run Code Online (Sandbox Code Playgroud)

它产生了一个红色通道,就好像它是一个RGB.我可以分别获得Y,Cb,Cr值吗?

编辑:Numpy版本1.3,Python 2.6 Linux Backtrack 5

絢瀬絵*_*瀬絵里 9

https://mail.python.org/pipermail/image-sig/2010-October/006526.html

这是Numpy的一个老bug.纠正它

>>> import numpy
>>> import Image as im
>>> image = im.open('bush640x360.png')
>>> ycbcr = image.convert('YCbCr')

>>> B = numpy.ndarray((image.size[1], image.size[0], 3), 'u1', ycbcr.tostring())
>>> print B.shape
(360, 640, 3)
>>> im.fromarray(B[:,:,0], "L").show()
Run Code Online (Sandbox Code Playgroud)

  • 在PIL的后续版本中,(1.1.7,可能更早),`tostring()`已被删除,因此第5行应该是:`B = numpy.ndarray((image.size [1],image.size [ 0],3),'u1',ycbcr.tobytes())` (2认同)