python中matplotlib关于直方图AttributeError: ‘Rectangle‘ object has no property ‘normed‘的解决方法
文章目錄
- 遇到的問題
- 解決方法
- 參考
3秒版本:
改成如下形式即可,去掉normed,改成density(布爾值),意思是開啟概率分布(直方圖面積為1).
plt.hist(hist_r, bins = 40, density=True,facecolor="red", edgecolor="black", alpha=0.7)遇到的問題
今天在閱讀《數字圖像處理與python實現》一書中的圖像直方圖實驗時,想繪制彩色圖片三通道直方圖,但是書中并沒有給出源碼。
只是給出了計算直方圖的部分代碼
然后在網上去搜尋三通道直方圖的畫法,還真找到了:python數字圖像處理(9):直方圖與均衡化
其中給出的方法是調用hist方法來繪制:
然后就按照這種方式來做,結果就是報錯:
AttributeError: 'Rectangle' object has no property 'normed'嘗試刪除normed,可以運行,結果如下:得到并不是歸一化的直方圖,和書中給的可視化圖形也并不一致。
用于測試的代碼
from skimage import exposure, io, data from matplotlib import pyplot as plt import matplotlib import numpy as np# 設置matplotlib正常顯示中文和負號 matplotlib.rcParams['font.sans-serif']=['SimHei'] # 用黑體顯示中文 matplotlib.rcParams['axes.unicode_minus']=False # 正常顯示負號image = data.coffee()# 計算直方圖 hist_r = exposure.histogram(image[:, :, 0], nbins = 256) hist_g = exposure.histogram(image[:, :, 1], nbins = 256) hist_b = exposure.histogram(image[:, :, 2], nbins = 256)plt.subplot(2, 2, 1) plt.title("原圖") io.imshow(image)# data = np.random.randn(10000) plt.subplot(2, 2, 2) plt.title("R通道顏色直方圖") plt.hist(hist_r, bins = 40, facecolor="red", edgecolor="black", alpha=0.7)plt.subplot(2, 2, 3) plt.title("G通道顏色直方圖") plt.hist(hist_g, bins = 40, facecolor="green", edgecolor="black", alpha=0.7)plt.subplot(2, 2, 4) plt.title("B通道顏色直方圖") plt.hist(hist_b, bins = 40, facecolor="blue", edgecolor="black", alpha=0.7)plt.show()解決方法
然后在stackoverflow和其他博文中翻閱了一下,最終還是打開了matplotlib 的開發文檔
https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.hist.html#matplotlib.pyplot.hist
這個hist是在matplotlib.pyplot下的:
這是hist函數原型
matplotlib.pyplot.hist(x, bins=None, range=None, density=False, weights=None, cumulative=False, bottom=None, histtype=‘bar’, align=‘mid’, orientation=‘vertical’, rwidth=None, log=False, color=None, label=None, stacked=False, *, data=None, **kwargs)
其中關于density參數的解釋
densitybool, default: False
If True, draw and return a probability density: each bin will display the bin’s raw count divided by the total number of counts and the bin width (density = counts / (sum(counts) * np.diff(bins))), so that the area under the histogram integrates to 1 (np.sum(density * np.diff(bins)) == 1).
If stacked is also True, the sum of the histograms is normalized to 1.
density是概率密度的開關,如果density=True,就是直方圖歸一化,面積加起來為1.
所以改成:
plt.hist(hist_r, bins = 40, density=True,facecolor="red", edgecolor="black", alpha=0.7)
代碼
參考
[1]https://blog.csdn.net/qq_45069279/article/details/105636669
[2]https://blog.csdn.net/haoyu_xie/article/details/106814610
[3]https://matplotlib.org/stable/api/index.htmlmatplotlib參考API
總結
以上是生活随笔為你收集整理的python中matplotlib关于直方图AttributeError: ‘Rectangle‘ object has no property ‘normed‘的解决方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mathtype6在word2019中闪
- 下一篇: python画图fig.show()一闪