功能卡在无限循环中,找不到原因

时间:2017-11-22 14:02:12

标签: python python-3.x loops infinite-loop

代码应该取每个像素的rgb值并将其存储在2d数组中(例如像素[pixelNumber] [r,g,b]),然后将其发送到用户定义的方法,在这种情况下,模糊它(使用高斯模糊)。宽度和高度是从图像中获取的像素宽度和高度定义,半径是用户定义的半径,其中像素被平均化为模糊。

给了我0分之差
weight_r = pixels[j][0] * weight
weight_g = pixels[j][1] * weight
weight_b = pixels[j][2] * weight

之前我将total_weight从0更改为1,当在第一个for循环下方定义时,如果这有帮助

def blur(pixels, radius, width, height):
    for i in range(len(pixels)):
        total_weight = 1
        pix_weight = 0
        r_temp = radius
        pixels_2 = copy.deepcopy(pixels)
        x = i % width
        y = (i // width) + 1
        for j in range(len(pixels)):
            x_2 = j % width
            y_2 = (j // width) + 1
            dist = math.sqrt(((x_2 - x) ** 2) + ((y_2 - y) ** 2))
            while(r_temp > 0):
                if((x_2 - radius == x or x_2 + radius == x) and (y_2 - radius == y or y_2 + radius == y) and dist != 0):
                    weight = ((math.e ** (-((dist ** 2) / (2 * (radius ** 2))))) / (2 * math.pi * (radius ** 2)))
                    total_weight = total_weight + weight
                    weight_r = pixels[j][0] * weight
                    weight_g = pixels[j][1] * weight
                    weight_b = pixels[j][2] * weight
                    pix_weight = pix_weight + weight_r + weight_g + weight_b
                r_temp = r_temp - 1
        final_blur = int((pix_weight / total_weight) / 255)
        pixels_2[i][0] = int(pixels[i][0] * final_blur)
        pixels_2[i][1] = int(pixels[i][1] * final_blur)
        pixels_2[i][2] = int(pixels[i][2] * final_blur)
    return pixels_2

上面的方法,像素是一个二维数组,半径,宽度和高度都是整数。

1 个答案:

答案 0 :(得分:0)

我已经完全复制了你的代码,使用Python 2.7.11和下面的一些示例参数,我无法重现无限循环。对于哪些参数,您会看到无限循环行为?

In [13]: p = [[1, 1, 1, 1, 1], 
              [1, 1, 1, 1, 1], 
              [1, 1, 1, 1 ,1], 
              [1, 1, 1, 1, 1], 
              [1, 1, 1, 1, 1]]

In [14]: r = 3

In [15]: w, h = 5, 5

In [16]: blur(p, r, w, h)
Out[16]: 
[[1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1],
 [0, 0, 0, 1, 1]]

(另外注意,看起来你的模糊内核没有用相同的边缘条件处理不同的图像边界。)

添加了您在评论中提到的使用256x256图像的内容 - 而且还检查了我尝试使用256 ** 2条目(所有像素列表)的示例格式,其中每个像素是一个3元素列表。我现在看到这可能就是你想要的。

这些更改在此示例中:

In [19]: p = [[1, 1, 1] for _ in range(256 ** 2)]

In [20]: %timeit blur(p, 1, 256, 256)

这确实需要很长时间才能运行,我会在完成时更新时间信息。