0

我正在用 Python 编写一个函数来像素化图像,但由于某种原因 xx 和 x 不会增加。两个变量始终保持值 0,并且没有任何反应。

xx = 0
yy = 0

while xx < width:
    while yy < height:
        print ("---", xx, yy)
        offsetX = xx + block_size_half
        offsetY = yy + block_size_half

        while (xx + offsetX >= width):
            offsetX -= 1
        while (yy + offsetY >= height):
            offsetY -= 1

        r, g, b = matrix[xx + offsetX][yy + offsetY]

        x = xx
        y = yy
        while x < xx + block_size and x < width:
            while y < yy + block_size and y < height:
                print (x, y)
                matrix[x][y] = (r, g, b)
                y += 1

            x += 1

        yy += block_size

    xx += block_size

感谢@Elazar 的帮助!这是整个工作功能:

def pixelate(matrix, block_size):
    width = len(matrix)
    height = len(matrix[0])
    block_size_half = int(block_size / 2)

    for xx in range(0, width, block_size):
        for yy in range(0, height, block_size):

            offsetX = min(xx + block_size_half, width - 1)
            offsetY = min(yy + block_size_half, height - 1)

            r, g, b = matrix[offsetX][offsetY]

            for x in range(xx, min(xx + block_size, width)):
                for y in range(yy, min(yy + block_size, height)):
                    matrix[x][y] = (r, g, b)

我从这个 C# 实现中获得了算法的灵感:http: //notes.ericwillis.com/2009/11/pixelate-an-image-with-csharp/

4

1 回答 1

1

我看不出你为什么不使用xrange()(or range())

for xx in range(0, width, block_size):
    for yy in range(0, height, block_size):
        ...

[编辑]

重写整个例子,你会得到类似的东西:

for xx in range(0, width, block_size):
    for yy in range(0, height, block_size):
        print ("---", xx, yy)
        offsetX = min(width, xx + block_size_half)
        offsetY = min(height, yy + block_size_half)

        r, g, b = matrix[xx + offsetX][yy + offsetY]

        for x in range(xx, min(xx + block_size, width)):
            for y in range(yy, min(yy + block_size, height)):
                print (x, y)
                matrix[x][y] = (r, g, b)

这可能会变得更短。

于 2013-04-26T05:22:40.830 回答