2010-11-15 105 views
3

我一直工作在一个脚本,我需要它基本上是:PIL:创建图像颜色亮度的一维直方图?

  • 使图像灰度(或黑白,我会都发挥,看看哪一个效果更好)。
  • 处理每个单独的列并为每列创建一个净强度值。
  • 将结果吐在有序列表中。

有一个非常简单的方法与ImageMagick的做到这一点(虽然你需要一些Linux实用程序来处理输出文本),但我没有真正看到如何使用Python和PIL做到这一点。

这是我到目前为止有:

from PIL import Image 

image_file = 'test.tiff' 

image = Image.open(image_file).convert('L') 

histo = image.histogram() 
histo_string = '' 

for i in histo: 
    histo_string += str(i) + "\n" 

print(histo_string) 

这东西输出(我期待绘制结果),但它看上去一点也不像ImageMagick的输出。我使用它来检测扫描书籍的接缝和内容。

感谢任何人的帮助!


我有这样的作品,现在一(讨厌看的)解决方案:

from PIL import Image 
import numpy 

def smoothListGaussian(list,degree=5): 
    window=degree*2-1 
    weight=numpy.array([1.0]*window) 
    weightGauss=[] 

    for i in range(window): 
    i=i-degree+1 
    frac=i/float(window) 
    gauss=1/(numpy.exp((4*(frac))**2)) 
    weightGauss.append(gauss) 

    weight=numpy.array(weightGauss)*weight 
    smoothed=[0.0]*(len(list)-window) 

    for i in range(len(smoothed)): 
    smoothed[i]=sum(numpy.array(list[i:i+window])*weight)/sum(weight) 

    return smoothed 

image_file = 'verypurple.jpg' 
out_file = 'out.tiff' 

image = Image.open(image_file).convert('1') 
image2 = image.load() 
image.save(out_file) 

intensities = [] 

for x in xrange(image.size[0]): 
    intensities.append([]) 

    for y in xrange(image.size[1]): 
    intensities[x].append(image2[x, y]) 

plot = [] 

for x in xrange(image.size[0]): 
    plot.append(0) 

    for y in xrange(image.size[1]): 
    plot[x] += intensities[x][y] 

plot = smoothListGaussian(plot, 10) 

plot_str = '' 

for x in range(len(plot)): 
    plot_str += str(plot[x]) + "\n" 

print(plot_str) 
+0

3D,你能展示一个你正在寻找的输出的例子吗? – 2010-11-15 19:49:44

回答

10

我看到你正在使用numpy。我会首先将灰度图像转换为numpy数组,然后使用numpy来沿轴进行求和。奖励:当你修正它接受一维数组作为输入时,你可能会发现你的平滑函数运行得更快。

>>> from PIL import Image 
>>> import numpy as np 
>>> i = Image.open(r'C:\Pictures\pics\test.png') 
>>> a = np.array(i.convert('L')) 
>>> a.shape 
(2000, 2000) 
>>> b = a.sum(0) # or 1 depending on the axis you want to sum across 
>>> b.shape 
(2000,) 
+0

我会测试一下!它看起来比我现在所拥有的更干净... – Blender 2010-11-16 23:05:56

+0

是的!这正是我需要的! :d – Blender 2010-11-16 23:15:29

7

the docs for PILhistogram为您提供了图像中的每个像素值的像素数的列表。如果您有灰度图像,则会有256个不同的可能值,范围从0到255,而从image.histogram返回的列表将有256个条目。

+0

看来,我一直在混淆直方图与其他东西...它确实给了我正确的输出,但它不是我真正想要的。对于图像中每个垂直的像素列,我想要基本上有一个亮度(或强度,我不熟悉这个术语)列表。直方图只是给了我有多少像素落入了什么颜色范围。 – Blender 2010-11-15 20:00:03

+1

PIL维护者移动该文档链接[here](http://www.effbot.org/imagingbook/image.htm#tag-Image.Image.histogram)。 – 2017-05-08 17:48:39

+1

谢谢@LloydMacLea - 我已更新链接。 – 2017-05-10 00:21:03