循环后的变量变化

时间:2017-02-09 02:10:24

标签: python loops

我有以下代码:

    """
    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

我试图执行Cross Correlation in 2D using this formula。我无法弄清楚为什么我的号码被莫名其妙地四舍五入。我对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")

1 个答案:

答案 0 :(得分:1)

请注意,在此循环中提取代码:

avg = 0
for kr in range(kernel.shape[0]):
    for kc in range(kernel.shape[1]):
        avg += image[r][c] * kernel[kr][kc]

avg将总是加起来[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)

我还没有测试过我的代码,但我认为你可能只需要很小的调整