[英]Variable changes after loop
我有以下代码:
"""
Parameters
----------
image : numpy.ndarray(dtype=np.uint8)
A grayscale image represented in a numpy array.
kernel : numpy.ndarray
A kernel represented in a numpy array of size (k, k) where k is an odd
number strictly greater than zero.
Returns
-------
output : numpy.ndarray(dtype=np.float64)
The output image. The size of the output array should be smaller than
the original image size by k-1 rows and k-1 columns, where k is the
size of the kernel.
"""
#kernel is of shape (K x K), square
K = kernel.shape[0]
#create a result array with K+1 rows and columns
result = np.zeros([image.shape[0] - K + 1, image.shape[1] - K + 1], dtype=np.float64)
#loop through the image
for r in range(result.shape[0]):
for c in range(result.shape[1]):
avg = 0 #running average for this image pixel
#loop through the kernel
for kr in range(kernel.shape[0]):
for kc in range(kernel.shape[1]):
avg += image[r][c] * kernel[kr][kc]
print avg #values are as expected
print avg #values are rounded (i.e. no decimals)
result[r][c] = avg
return result
我正在尝试使用此公式在2D中执行互相关 。 我不知道为什么我的数字会被莫名其妙地四舍五入。 我对Python有点陌生,所以也许我做错了。
我将不胜感激。
编辑:我希望我的输出等于以下cv2函数调用的输出:
GAUSSIAN_KERNEL = np.array([[ 1, 4, 6, 4, 1],
[ 4, 16, 24, 16, 4],
[ 6, 24, 36, 24, 6],
[ 4, 16, 24, 16, 4],
[ 1, 4, 6, 4, 1]], dtype=np.float64) / 256.
N = GAUSSIAN_KERNEL.shape[0] // 2
tested = a4.crossCorrelation2D(self.testImage, GAUSSIAN_KERNEL)
goal = cv2.filter2D(self.testImage, cv2.CV_64F, GAUSSIAN_KERNEL)[N:-N, N:-N]
assert np.testing.assert_array_equal(tested, goal, "Arrays were not equal")
请注意,在从您的代码中提取的此循环中:
avg = 0
for kr in range(kernel.shape[0]):
for kc in range(kernel.shape[1]):
avg += image[r][c] * kernel[kr][kc]
由于您正在执行操作,因此avg总是加到image [r] [c]
image[r][c] * kernel[0][0] + image[r][c] * kernel[0][1] + image[r][c] * kernel[0][2]...
等于
image[r][c] * (kernel[0][0] + kernel[0][1] + kernel[0][2]...)
等于
image[r][c] * sum-of-all-kernel-elements
等于
image[r][c] * 1.0
正确的循环应该是这样的:
for r in range(result.shape[0]):
for c in range(result.shape[1]):
avg = 0.0
for kr in range(kernel.shape[0]):
for kc in range(kernel.shape[1]):
avg += kernel[kr][kc] * image[r+kr][c+kc]
result[r][c] = np.uint(avg)
我尚未测试我的代码,但我认为您可能只需要少量调整即可
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.