我想編寫能夠在不使用內置Matplotlib hist函數的情況下顯示圖像直方圖的代碼。在Python中手動高效地創建圖像直方圖
這裏是我的代碼:
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
def manHist(img):
row, col = img.shape # img is a grayscale image
y = np.zeros((256), np.uint64)
for i in range(0,row):
for j in range(0,col):
y[img[i,j]] += 1
x = np.arange(0,256)
plt.bar(x,y,color="gray",align="center")
plt.show()
def main():
img = cv.imread("C:/Users/Kadek/Documents/MATLAB/2GS.jpg")
manHist(img)
main()
我的問題是,有沒有比較有效的方式,使像素值頻率的陣列,而不使用循環?
沒有其他的比遍歷圖像中的每個值,儘管是矢量化的numpy的解決方案將快一些數量級 –
因此,您沒有使用第三軸通道:'y [img [i,j]]'? – Divakar
你可以使用'collections.Counter'來做這件事,儘管這可能對你來說不夠「手動」。 – kindall