我试图通过矢量化它来使这段代码运行得更快,因为我相信 python 中的循环很慢。我不完全理解矢量化,所以 for 循环内的切片给我带来了麻烦。
注意:这是针对不允许任何非 numpy 库的分配。
self.gx = numpy.array([[1, 0, -1], [2, 0, -2], [1, 0, -1]])
self.gy = numpy.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]])
def create_vector(self, image):
"""Creates a gradient vector for each pixel in the image
Returns: vec_data: [mag, angle, avg_value]"""
vec_data = numpy.zeros((image.shape[0], image.shape[1], 3), dtype='float')
for y in xrange(1, image.shape[0]-1):
for x in xrange(1, image.shape[1]-1):
#Get 3x3 matrix around the pixel
subimage = image[y-1:y+2,x-1:x+2]
#Apply sobel operator
dx = (self.gx*subimage).sum()
dy = (self.gy*subimage).sum()
vec_data[y,x,0] = abs(dx) + abs(dy)
vec_data[y,x,1] = abs(math.atan2(dx,dy))
vec_data[y,x,2] = subimage.sum()/9 #Average of 3x3 pixels around x, y
return vec_data