我在Python中使用numpy数组使用open cv制作直方图。代码如下:
#finding histogram of an image
import numpy as np
import cv2
img = cv2.imread("cr7.jpg")
gry_img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
a=np.zeros((1,256),dtype=np.uint8)
#finding how many times a particular pixel intensity repeats
for x in range (0,183): #size of gray_img is (184,275)
for y in range (0,274):
g=gry_ img[x,y]
a[g]=a[g]+1
print(a)
错误如下:
IndexError:索引150超出轴0的大小为1
答案 0 :(得分:0)
由于您还没有提供图像,因此只能猜测您的图像尺寸似乎已经出错了。或者,问题完全在于结果数组a
的形状。
您拥有的代码相当脆弱,这是一种更清晰的图像交互方式。我使用opencv数据目录中的图像:aero1.jpg。 这里的代码解决了上面列出的潜在问题,无论是哪一个:
fname = 'aero1.jpg'
im = cv2.imread(fname)
gry_img = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
gry_img.shape
>>> (480, 640)
# note that the image is 640pix wide by 480 tall;
# the numpy array shows the number of rows first.
# rows are in y / columns are in x
# NOTE the results array `a` need only be 1-dimensional, not 2d (1x256)
a=np.zeros((256, ), dtype=np.uint8)
# iterating over all pixels, whatever the shape of the image.
height, width = gry_img.shape
for x in xrange(width):
for y in xrange(height):
g = gry_img[y, x] # NOTE y, x not x, y
a[g] += 1
但是请注意,你也可以使用numpy函数np.histogram
(docs)轻松实现这一点,并小心处理bin边缘。
histb, bin_edges = np.histogram(gry_img.reshape(-1), bins=xrange(0, 257))
# check that we arrived at the same result as iterating manually:
(a == histb).all()
>>> True