【问题标题】:Why does this PIL call crash python?为什么这个 PIL 调用 crash python?
【发布时间】:2011-03-24 00:27:59
【问题描述】:
import Image
from numpy import zeros, asarray
YUV = zeros((240, 320, 3), dtype='uint8')
im = Image.fromarray(YUV, mode="YCbCr")
blah = asarray(im)

当我运行它(Py 2.7.1 上的 IPython 0.10.1)时,它似乎让 python 读取了一些它不应该读取的内存。有时它会崩溃,有时它不会崩溃,但我肯定可以通过将 320x240 零增加到 3200x2400 和/或调用 blah.copy() 来使其崩溃。另外,如果我这样做:

from matplotlib import pyplot as p
p.subplot(221); p.imshow(blah[:,:,0])
p.subplot(222); p.imshow(blah[:,:,1])
p.subplot(223); p.imshow(blah[:,:,2])
p.subplot(224); p.imshow(blah[:,:,3])
p.gray()
p.show()

我开始看到垃圾内存出现在大约第 180 行的 blah 中。这是怎么回事?我是否以不好的方式从 PIL Image 转换为 numpy 数组?使用 array(im) 而不是 asarray(im) 有什么区别,什么是首选? (请注意,在前一种情况下,它有时仍然会崩溃,但它似乎更稳定且垃圾更少)

(这是related question

【问题讨论】:

    标签: python arrays numpy python-imaging-library


    【解决方案1】:

    我注意到您的图像是 YCbCr 3 通道,但您显示的是 4 个通道。原来“垃圾数据”问题是caused by a bug in PIL's array interface,而修复是committed in Nov 2010。 PIL 的数组接口正在返回第 4 个通道。

    我在 PIL 1.1.7 下运行了您的测试用例并看到了噪音。我注释掉了224 子图并使用latest PIL trunk code 重新运行了您的测试,并生成了一个没有噪音的正确的3 通道阵列。崩溃也可能是相关的,但我无法在我的环境中重现。

    【讨论】:

    • 谢谢!一般来说,在转换为 numpy 数组时使用 asarray(im) 或 array(im) 是否正确.. 甚至可能是 asanyarray?这里有什么重要的区别吗?
    • 不客气!我看到的示例都使用numpy.asarray() 进行转换,但其他变体应该根据您的需要工作。例如numpy.asfarray 会将值转换为浮点数。
    猜你喜欢
    • 2022-11-01
    • 2011-05-28
    • 1970-01-01
    • 2020-09-13
    • 2020-03-03
    • 2012-03-14
    • 1970-01-01
    • 1970-01-01
    • 2014-08-12
    相关资源
    最近更新 更多