2017-07-10 7 views
-2

私はlena(有名な絵の名前)のヒストグラムを描くために必要な宿題があります。 そして、ここがmatplot.orgのコード例を、次に私のhistogram.Iで何かが間違っているとは私のコードです:Pythonの関数matplotlib.pyplot.histのいくつかの質問

import matplotlib.pyplot as plt 
import numpy as np 

def rgb2gray(rgb):          # rgb to grey 
    temp = np.dot(rgb[..., :3], [0.299, 0.587, 0.114]) 
    new = np.zeros([512,512], 'uint8') 
    for i in range(512): 
     for j in range(512): 
      new[i, j] = round(temp[i, j])    #float to int 
    return new 

lena = plt.imread("E:\lena.bmp") 
lena_gray = rgb2gray(lena) 
len, width = lena_gray.shape 

n, bins, patches = plt.hist(lena_gray, normed=1) 
print(n ,bins, patches) 

plt.show() 

しかし、私が得るヒストグラムは次のとおりです。

histogram.png

間違い私は絵の下を拡大するときです:

magnify.png

ご覧のとおり、そこに私のコードでは、関数histの最初のパラメータはlena_grayです。配列lena_greyの数字はすべて整数です。だから私はヒストグラムで2つの数字の間に非常に多くのビンがあるのか​​、なぜx軸に小数点があるのか​​を知りたい。

+0

あなたは代わりに、おそらく例のコードにリンク画像 –

+0

へのリンクを投稿のあなたの出力を印刷する必要がありますか?これはmatplotlibの典型的な動作です。 – user2699

答えて

1

plt.histに行列を渡しています。これは、処理する配列のリストとして解釈されます。 documentationを参照してください。各512列のヒストグラムが計算されて表示されます。あなたが最初のベクトルへの画像行列の形状を変更した場合、ヒストグラムは罰金判明:

import matplotlib.pyplot as plt 
import numpy as np 

def rgb2gray(rgb):          # rgb to grey 
    return np.dot(rgb[..., :3], [0.299, 0.587, 0.114]).astype(int) 

lena = plt.imread("E:\lena.bmp") 
lena_gray = rgb2gray(lena) 
len, width = lena_gray.shape 

# use np.reshape to transform matrix to vector 
n ,bins, patches = plt.hist(np.reshape(lena_gray,(-1,1)), normed=1) 
print(n ,bins, patches) 

plt.show() 
+1

ピクセルの順序はヒストグラムとは無関係なので、単に配列を平坦化することもできます: 'plt.hist(lena_gray.flatten()、)' – ImportanceOfBeingErnest

関連する問題