How to write it easier

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

As you can see, I am repeating the image using 5x5px squares and setting pixels in them.

The above code is obviosuly for an image with dimensions of 10x10px, but I would like to write the code in a more general way, so I can use it for large images (say 30x30px) without adding 32 new loops.

+3
source share
1 answer
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.

But I would create a generator to iterate the block:

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)

and use putpixel as

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])
+4
source

Source: https://habr.com/ru/post/1774374/


All Articles