我正在用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/
答案 0 :(得分:1)
我看不出你没有理由不使用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)
可能会更短。