# 5.3. 直方图-3:2D直方图¶

## 5.3.3. OpenCV中的二维直方图¶

• channels = [0,1] because we need to process both H and S plane.

• bins = [180,256] 180 for H plane and 256 for S plane.

• range = [0,180,0,256] Hue value lies between 0 and 180 & Saturation lies between 0 and 256.

>>> import cv2
>>> import numpy as np
>>>
>>> hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
>>>
>>> hist = cv2.calcHist([hsv], [0, 1], None, [180, 256], [0, 180, 0, 256])

>>> from matplotlib import pyplot as plt

>>> plt.imshow(hist)

<matplotlib.image.AxesImage at 0x7fc610537828>


## 5.3.4. Numpy中的二维直方图¶

Numpy还为此提供了一个特定的函数： np.histogram2d（） . （记住，对于一维直方图，我们使用 直方图（）

>>> import cv2
>>> import numpy as np
>>> from matplotlib import pyplot as plt
>>>
>>> hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)

>>> hsv.shape

(384, 512, 3)

>>> h = hsv[0]

>>> s = hsv[1]

>>> v = hsv[2]

>>> hist, xbins, ybins = np.histogram2d(h.ravel(),s.ravel(),[180,256],[[0,180],[0,256]])


## 5.3.5. 绘制二维直方图¶

### 方法-2:使用Matplotlib¶

>>> import cv2
>>> import numpy as np
>>> from matplotlib import pyplot as plt
>>>
>>> hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
>>> hist = cv2.calcHist( [hsv], [0, 1], None, [180, 256], [0, 180, 0, 256] )
>>>
>>> plt.imshow(hist,interpolation = 'nearest')
>>> plt.show()