简体   繁体   English

使用python中的PIL裁剪具有相同裁剪大小的整个图像

[英]Crop entire image with the same cropping size with PIL in python

I have some problem with my logic on PIL python. 我对PIL python的逻辑有些疑问。 My goal is to crop one image entirely in 64x64 size from the left-top corner to botom-right corner position. 我的目标是从左上角到右下角位置完全以64x64大小裁剪一张图像。 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)). 在第一个循环中,我可以裁剪((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. 但是,然后我无法弄清楚循环部分用PIL将左下64x64移到底部。 As the first 2-tuple is the origin position point, the next tuple is for the cropping size. 由于第一个2元组是原点位置点,因此下一个元组用于裁剪大小。

any help will be really appreciated as I am starting to learn python. 当我开始学习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

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: 您可以使用range()函数为您执行步进(在这种情况下,以64为块),因此裁剪仅涉及简单的表达式:

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. 除此之外,您的代码可以按预期工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM