我正在自学计算机图像处理的基础知识,同时我也在自学Python。
给定具有3个 channel 的大小为2048x1354的图像x
,可以有效地计算像素强度的直方图。
import numpy as np, cv2 as cv
img = cv.imread("image.jpg")
bins = np.zeros(256, np.int32)
for i in range(0, img.shape[0]):
for j in range(0, img.shape[1]):
intensity = 0
for k in range(0, len(img[i][j])):
intensity += img[i][j][k]
bins[intensity/3] += 1
print bins
我的问题是这段代码运行缓慢,大约需要30秒。我如何才能加快速度并提高Python风格?
最佳答案
您可以使用较新的OpenCV python接口(interface),该接口(interface) native 使用numpy数组,并使用matplotlib hist
绘制像素强度的直方图。在我的计算机上花费的时间不到一秒钟。
import matplotlib.pyplot as plt
import cv2
im = cv2.imread('image.jpg')
# calculate mean value from RGB channels and flatten to 1D array
vals = im.mean(axis=2).flatten()
# plot histogram with 255 bins
b, bins, patches = plt.hist(vals, 255)
plt.xlim([0,255])
plt.show()
更新:
超过指定数量的垃圾箱并不总能提供理想的结果,因为最小值和最大值是根据实际值计算得出的。此外,值254和255的计数在最后一个bin中求和。这是更新的代码,这些代码始终正确地绘制直方图,且条形图的中心位于值0..255
import numpy as np
import matplotlib.pyplot as plt
import cv2
# read image
im = cv2.imread('image.jpg')
# calculate mean value from RGB channels and flatten to 1D array
vals = im.mean(axis=2).flatten()
# calculate histogram
counts, bins = np.histogram(vals, range(257))
# plot histogram centered on values 0..255
plt.bar(bins[:-1] - 0.5, counts, width=1, edgecolor='none')
plt.xlim([-0.5, 255.5])
plt.show()