i = 0
for x in range(0, 5):
for y in range(0, 5):
if 0 == outputAfterLearning[i]:
image.putpixel((x, y), (0, 0, 0))
elif 1 == outputAfterLearning[i]:
image.putpixel((x, y), (255, 255, 255))
i += 1
for x in range(0, 5):
for y in range(5, 10):
if 0 == outputAfterLearning[i]:
image.putpixel((x, y), (0, 0, 0))
elif 1 == outputAfterLearning[i]:
image.putpixel((x, y), (255, 255, 255))
i += 1
for x in range(5, 10):
for y in range(0, 5):
if 0 == outputAfterLearning[i]:
image.putpixel((x, y), (0, 0, 0))
elif 1 == outputAfterLearning[i]:
image.putpixel((x, y), (255, 255, 255))
i += 1
for x in range(5, 10):
for y in range(5, 10):
if 0 == outputAfterLearning[i]:
image.putpixel((x, y), (0, 0, 0))
elif 1 == outputAfterLearning[i]:
image.putpixel((x, y), (255, 255, 255))
i += 1
如您所见,我正在使用5x5px正方形在图像上迭代并在其中设置像素。
上面的代码对于尺寸为10x10px的图像是显而易见的,但是我想用一种更通用的方式编写上面的代码,这样我就可以在不增加32个for循环的情况下使用它来处理更大的图像(比如30x30px)。
最佳答案
xdim, ydim = 10, 10
xblocksize, yblocksize = 5, 5
for xblock in range(0, xdim, xblocksize):
for yblock in range(0, ydim, yblocksize):
for x in range(xblock, xblock+xblocksize):
for y in range(yblock, yblock+yblocksize):
# the common code.
但我会为块迭代创建一个生成器:
def blocked(xdim, ydim, xblocksize, yblocksize):
for xblock in range(0, xdim, xblocksize):
for yblock in range(0, ydim, yblocksize):
for x in range(xblock, xblock+xblocksize):
for y in range(yblock, yblock+yblocksize):
yield (x, y)
使用putpoixel作为
color = [(0,0,0),(255,255,255)]
for colorcode, pixelloc in zip(outputAfterLearning, blocked(10, 10, 5, 5)):
if 0 <= colorcode < len(color):
# ^ omit this if outputAfterLearning[i] is always valid
image.putpixel(pixelloc, color[colorcode])
关于python - 如何以更简单的方式编写,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4158045/