2010-11-15 101 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