Crop entire image with the same cropping size with

2020-03-30 08:57发布

问题:

I have some problem with my logic on PIL python. My goal is to crop one image entirely in 64x64 size from the left-top corner to botom-right corner position. I can do one time cropping operation, but when I tried to crop an image entirely with looping, I am stuck with the looping case in the middle.

In the first looping, I can crop ((0, 0, 64, 64)). But then I cannot figure the looping part to get the next 64x64s to the left and to the bottom with PIL. As the first 2-tuple is the origin position point, the next tuple is for the cropping size.

any help will be really appreciated as I am starting to learn python.

import os
from PIL import Image

savedir = "E:/Cropped/OK"
filename = "E:/Cropped/dog.jpg"
img = Image.open(filename)
width, height = img.size

start_pos = start_x, start_y = (0,0)  
cropped_image_size = w, h = (64, 64) 

frame_num = 1
for col_i in range (width):
    for row_i in range (height):
        x = start_x + col_i*w
        y = start_y + row_i*h
        crop = img.crop((x, y, x+w*row_i, y+h*col_i))
        save_to= os.path.join(savedir, "counter_{:03}.jpg")
        crop.save(save_to.format(frame_num))
        frame_num += 1

回答1:

You can use the range() function to do the stepping for you (in blocks of 64 in this case), so that your cropping only involves simple expressions:

import os
from PIL import Image

savedir = "E:/Cropped/OK"
filename = "E:/Cropped/dog.jpg"
img = Image.open(filename)
width, height = img.size

start_pos = start_x, start_y = (0, 0)
cropped_image_size = w, h = (64, 64)

frame_num = 1
for col_i in range(0, width, w):
    for row_i in range(0, height, h):
        crop = img.crop((col_i, row_i, col_i + w, row_i + h))
        save_to= os.path.join(savedir, "counter_{:03}.jpg")
        crop.save(save_to.format(frame_num))
        frame_num += 1

Other than that, your code works as expected.