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的图像来说是强制性的,但是我想以更通用的方式编写上面的代码,以便可以将其用于较大的图像(例如30x30px),而无需添加32个新的for循环.
解决方法:
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)
并使用putpixel作为
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])