opencv Python -图像的二维(2D)强度直方图

egdjgwm8  于 2023-02-05  发布在  Python
关注(0)|答案(1)|浏览(166)

我想显示图形的二维直方图,但我不知道opencv或matplotlib支持哪个函数。请告诉我是哪个函数,谢谢大家。我想显示看起来像Thế describe image的结果

sbtkgmzw

sbtkgmzw1#

opencv和numpy都包含计算图像直方图的实现,请参见opencv docs
下面是一个简单的例子,说明如何使用opencv计算图像的2D直方图。

  • 将图像转换为HSV空间
  • 使用opencv calcHist计算色调和饱和度之间的2D直方图
  • 色调范围为0-180
  • 饱和度范围为0-256
  • 将直方图转换为HSV颜色并显示

下面是生成的直方图:

import numpy as np
import cv2
import matplotlib.pyplot as plt

# read image
image = cv2.imread(r"path\to\image")
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

# compute 2D histograms in HSV space
hist = cv2.calcHist([hsv], [0, 1], None, [180, 256], [0, 180, 0, 256])

# get HSV map to display histogram in HSV color
hsv_map = np.zeros((180, 256, 3), np.uint8)
h, s = np.indices(hsv_map.shape[:2])
hsv_map[:,:,0] = h
hsv_map[:,:,1] = s
hsv_map[:,:,2] = 255
hsv_map = cv2.cvtColor(hsv_map, cv2.COLOR_HSV2BGR)

# rescale and convert to HSV space
hist_scale = 10
hist = np.clip(hist*0.005*hist_scale, 0, 1)
vis = hsv_map*hist[:,:,np.newaxis] / 255.0

# display
plt.imshow(vis)
plt.title("HSV Histogram")
plt.xlabel("Saturation")
plt.ylabel("Hue")
plt.show();

您还可以沿着成对的颜色通道制作直方图,如下所示:

# Blue Green histogram (opencv reads images as BGR)
hist = cv2.calcHist([image], [0,1], None, [256, 256], [0, 256, 0, 256])

资料来源:

相关问题