PIL直方图抛出缓冲区溢出。我怎么能绕过这个呢?

时间:2012-08-14 07:42:46

标签: python image-processing python-imaging-library histogram

我想用Python生成16位灰度图像的直方图。当我运行以下代码时,我得到一个缓冲区溢出。

#!/usr/bin/python

from PIL import Image
import numpy as np

i = Image.open('t.tif')
a = i.histogram()

print a

错误消息(缩短)

tdettmer@thinkpad:~/code/histogram$ ./h.py 
*** buffer overflow detected ***: /usr/bin/python terminated
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(__fortify_fail+0x37)[0x7f3f33ed6007]
/lib/x86_64-linux-gnu/libc.so.6(+0x107f00)[0x7f3f33ed4f00]
/usr/lib/python2.7/dist-packages/PIL/_imaging.so(ImagingHistogramNew+0x33)

现在,我完全可以看到从16位图像生成直方图会占用大量资源,但是我可以以某种方式解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

由于您似乎已经在使用numpy,因此值得指出它有自己的histogram function。您可以在converting the PIL image to a numpy array之后使用它。也许他们的直方图实施会更有效率。

答案 1 :(得分:0)

由于PIL的直方图方法似乎在16位图像上都很奇怪,我编写了自己的函数来生成直方图。我有12位的显微图像,存储在16位tiff文件中。所以这个tiff里面的最大灰度值是4096。

打开图像并读取像素的功能:

def getPixels(file):
    img = Image.open(file)

    pixels = img.load()
    width, height = img.size

    all_pixels =  []

    for x in range(width):
        for y in range(height):
            cpixel = pixels[x, y]
            all_pixels.append(cpixel)

    return all_pixels

...生成直方图:

def generateHistogram(file, z):
    px = getPixels(file)
    a = np.histogram(px, bins=np.arange(z))
相关问题