I'm writing a function in Python to pixelate an image, but for some reason xx and x doesn't increment. Both variables keep the value 0 throughout and nothing happens.
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
Thanks to @Elazar for help! Here is the entire working function:
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)
I got inspiration for the algorithm from this C# implementation: http://notes.ericwillis.com/2009/11/pixelate-an-image-with-csharp/
I can see no reason why you wouldn't use xrange()
(or range()
)
for xx in range(0, width, block_size):
for yy in range(0, height, block_size):
...
[EDIT]
rewriting the whole example, you will get something like:
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)
which can probably get even shorter.