1. 程式人生 > >python影象處理:直方圖

python影象處理:直方圖

灰度圖直方圖

呼叫matplotlib.pyplot庫進行繪圖,其中的hist函式可直接繪製直方圖。呼叫方式:
n, bins, patches = plt.hist(arr, bins=50, normed=1, facecolor='green', alpha=0.75)
hist的引數非常多,但常用的就這五個,只有第一個是必須的,後面四個可選

arr: 需要計算直方圖的一維陣列
bins: 直方圖的柱數,可選項,預設為10
normed: 是否將得到的直方圖向量歸一化。預設為0
facecolor: 直方圖顏色
alpha: 透明度

返回值 :

n: 直方圖向量,是否歸一化由引數設定
bins: 返回各個bin的區間範圍
patches: 返回每個bin裡面包含的資料,是一個list

示例

import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
img = np.array(Image.open('/home/keysen/caffe/examples/images/cat.jpg').convert('L'))

plt.figure('cat')
arr = img.flatten()
n, bins, patches = plt.hist(arr, bins=256, normed=1, facecolor='green', alpha=0.75)
plt.show()

output

這裡寫圖片描述

上面用到的flatten函式在這裡單獨介紹,相關的函式是reshape函式。

# 一維陣列
arr = np.arange(15)
print arr

output

[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14]

如果我們要把這個一維陣列,變成一個3*5二維矩陣,使用reshape來實現

re_arr = arr.reshape(3,5)
print(re_arr)

output

[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]

現在如果我們返過來,知道一個二維矩陣,要變成一個一維陣列,就不能用reshape了,只能用flatten. 我們來看兩者的區別

a1=re_arr.reshape(1,-1)  #-1表示為任意,讓系統自動計算
print(a1)
a2=re_arr.flatten()
print(a2)

output

[[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14]]
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14]

可以看出,用reshape進行變換,實際上變換後還是二維陣列,兩個方括號,因此只能用flatten.

彩色圖片直方圖

實際上是和灰度直方圖一樣的,只是分別畫出三通道的直方圖,然後疊加在一起

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
src= Image.open('/home/keysen/caffe/examples/images/cat.jpg')
r,g,b=src.split()

plt.figure("cat")
ar=np.array(r).flatten()
plt.hist(ar, bins=256, normed=1,facecolor='r',edgecolor='r',hold=1)
ag=np.array(g).flatten()
plt.hist(ag, bins=256, normed=1, facecolor='g',edgecolor='g',hold=1)
ab=np.array(b).flatten()
plt.hist(ab, bins=256, normed=1, facecolor='b',edgecolor='b')
plt.show()

output

這裡寫圖片描述