如何在不使用 numpy 直方图的情况下制作直方图
How can I make histogram without using numpy histogram
import cv2
import numpy as np
import matplotlib.pyplot as plt
def my_histogram(img, bins, range):
hist =
return hist
我需要在不使用 np.histogram 或其他直方图函数的情况下填写 hist
img = cv2.imread('sample.jpg')
img_g = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
hist = my_histogram(img_g, 256, [0,256])
plt.plot(hist)
plt.xlim([0,256])
plt.show()
np.unique
是一个效率较低的直方图实用程序,因为它对数据进行排序而不是直接处理数据:
bins, hist = np.unique(img.ravel(), return_counts=True)
我不会为您提供确切的答案,因为这看起来像是一项作业。基本上,灰度图像中的每个像素都有一个与之关联的数字,范围从 0 到 255。您想要做的是对具有相同值的像素数求和(有多少值为 0,有多少值为 1 ,有多少值为 2,等等)。您可能可以使用 numpy 来帮助您,而无需调用直方图函数(例如,看看这个 link)。
然后您可以使用 matplotlib 绘制条形图,以显示直方图。
import cv2
import numpy as np
import matplotlib.pyplot as plt
def my_histogram(img, bins, range):
hist =
return hist
我需要在不使用 np.histogram 或其他直方图函数的情况下填写 hist
img = cv2.imread('sample.jpg')
img_g = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
hist = my_histogram(img_g, 256, [0,256])
plt.plot(hist)
plt.xlim([0,256])
plt.show()
np.unique
是一个效率较低的直方图实用程序,因为它对数据进行排序而不是直接处理数据:
bins, hist = np.unique(img.ravel(), return_counts=True)
我不会为您提供确切的答案,因为这看起来像是一项作业。基本上,灰度图像中的每个像素都有一个与之关联的数字,范围从 0 到 255。您想要做的是对具有相同值的像素数求和(有多少值为 0,有多少值为 1 ,有多少值为 2,等等)。您可能可以使用 numpy 来帮助您,而无需调用直方图函数(例如,看看这个 link)。
然后您可以使用 matplotlib 绘制条形图,以显示直方图。