我正在用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/
我看不出你为什么不使用xrange()
(或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)
可以更短