# 二、对图像进行直方图统计

`image.ravel()`把图像的所有像素点信息进行统计
`plt.hist(image.ravel(),256,[0,256])`将图像信息进行统计，统计成256个bin，范围为[0,255]
`cv2.calcHist([image],[i],None,[256],[0,256])`[image]为当前出来图像，[i]这里使用了一个循环也就是依次BGR三个通道，None是掩膜信息这里没有用到，[256]表示直方图的size，[0,256]BGR三颜色的像素值的范围

``````import cv2
import numpy as np
from matplotlib import pyplot as plt

def plot(image):
plt.hist(image.ravel(),256,[0,256])
plt.show("matlab自带直方图")

def hist(image):
color = ('blue','green','red')
for i,color in enumerate(color):
hist = cv2.calcHist([image],[i],None,[256],[0,256])
plt.plot(hist,color=color)
plt.xlim([0,256])
plt.show()

cv2.imshow("image",src)
cv2.namedWindow("image",cv2.WINDOW_AUTOSIZE)

plot(src)
hist(src)

cv2.waitKey(0)
cv2.destroyAllWindows()
``````

# 三、直方图的均衡化

`OpenCV中的直方图均衡化针对的都是灰度图`

##### Ⅰ全局直方图均衡化
``````import cv2
import numpy as np
from matplotlib import pyplot as plt

def equalizeHist(image):
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
dst = cv2.equalizeHist(gray)
#yy = cv2.cvtColor(dst,cv2.COLOR_GRAY2BGR)
cv2.imshow("equalizeHist",dst)

cv2.imshow("image",src)
cv2.namedWindow("image",cv2.WINDOW_AUTOSIZE)

equalizeHist(src)

cv2.waitKey(0)
cv2.destroyAllWindows()
``````

##### Ⅱ局部直方图均衡化
``````import cv2
import numpy as np
from matplotlib import pyplot as plt

def clahe(image):
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
clahe = cv2.createCLAHE(clipLimit=2.0,tileGridSize=(8,8))
dst = clahe.apply(gray)
cv2.imshow("clahe",dst)

cv2.imshow("image",src)
cv2.namedWindow("image",cv2.WINDOW_AUTOSIZE)

clahe(src)

cv2.waitKey(0)
cv2.destroyAllWindows()
``````

# 四、直方图反向投影

### Ⅰ2D直方图

`cv2.calcHist([image],[0,1],None,[180,256],[0,180,0,256])`其中[180,256]表示bin的个数，可以修改，当然范围越小越精确

``````import cv2
import numpy as np
from matplotlib import pyplot as plt

def hist2d(image):
hsv = cv2.cvtColor(image,cv2.COLOR_BGR2HSV)
hist = cv2.calcHist([image],[0,1],None,[180,256],[0,180,0,256])
cv2.imshow("hist2d",hist)

def hist2d_1(image):
hsv = cv2.cvtColor(image,cv2.COLOR_BGR2HSV)
hist = cv2.calcHist([image],[0,1],None,[180,256],[0,180,0,256])
plt.imshow(hist,interpolation='nearest')
plt.title("2D Histogram")
plt.show()

cv2.imshow("image",src)
cv2.namedWindow("image",cv2.WINDOW_AUTOSIZE)
hist2d(src)
hist2d_1(src)
cv2.waitKey(0)
cv2.destroyAllWindows()
``````

##### Ⅱ直方图反向投影

`cv2.calcHist([roi_hsv],[0,1],None,[32,48],[0,180,0,256])`其中[32,48]表示bin的个数，可以修改，当然范围越小越精确

``````import cv2
import numpy as np
from matplotlib import pyplot as plt

def back_projection():
roi_hsv = cv2.cvtColor(sample,cv2.COLOR_BGR2HSV)
target_hsv = cv2.cvtColor(target,cv2.COLOR_BGR2HSV)

cv2.imshow("sample",sample)
cv2.imshow("target",target)

roiHist = cv2.calcHist([roi_hsv],[0,1],None,[32,48],[0,180,0,256])
cv2.normalize(roiHist,roiHist,0,255,cv2.NORM_MINMAX)
dst = cv2.calcBackProject([target_hsv],[0,1],roiHist,[0,180,0,256],1)
cv2.imshow("back_projection",dst)

back_projection()
cv2.waitKey(0)
cv2.destroyAllWindows()
``````

THE END