-1

I have a rectangular image. I need a way to use PIL or OpenCV to split it into sections of x many pixels tall. I have looked at the forms but all I could find are things to split into tiles. Does anybody know how to accomplish this?

Jack Adee
  • 73
  • 1
  • 1
  • 6
  • What code have you tried so far? – Poojan Oct 20 '19 at 21:45
  • Here's how you read pixels: https://stackoverflow.com/questions/11064786/get-pixels-rgb-using-pil. That should be enough info to create rows of pixels. – zvone Oct 20 '19 at 21:46
  • Use the crop method. It returns a new image so you can crop the same image many times to get each row – Oli Oct 20 '19 at 21:47
  • 1
    what is difference between `tiles` and `"sections of x many pixels tall"` ? – furas Oct 20 '19 at 23:31

1 Answers1

0

Here is some code that does what you asked: The split_into_rows function does all the actual splitting, and is a generator. It repeatedly uses the crop method to extract rectangular sections from the image and yield them.

from PIL import Image
import os

im = Image.open('input_image.png')

def split_into_rows(im, row_height):
    y = 0
    print(im.height)
    while y < im.height:
        top_left = (0, y)
        bottom_right = (im.width, min(y + row_height, im.height))
        yield im.crop((*top_left, *bottom_right))

        y += row_height

OUTPUT_DIR = 'output'

for i, row in enumerate(split_into_rows(im, 400)):
    save_path = os.path.join(OUTPUT_DIR, f'{i}.png')

    row.save(save_path)
    print(i)
Oli
  • 2,507
  • 1
  • 11
  • 23