【问题标题】:Crop entire image with the same cropping size with PIL in python在 python 中使用 PIL 以相同的裁剪大小裁剪整个图像
【发布时间】:2019-04-29 06:59:56
【问题描述】:

我在 PIL python 上的逻辑有些问题。我的目标是从左上角到右下角位置完全以 64x64 大小裁剪一张图像。我可以进行一次裁剪操作,但是当我尝试完全使用循环裁剪图像时,我被中间的循环案例卡住了。

在第一个循环中,我可以裁剪 ((0, 0, 64, 64))。但后来我无法计算循环部分以使用 PIL 将下一个 64x64 移到左侧和底部。由于第一个 2 元组是原点位置,下一个元组用于裁剪大小。

当我开始学习 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

【问题讨论】:

    标签: python image python-imaging-library


    【解决方案1】:

    您可以使用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
    

    除此之外,您的代码按预期工作。

    【讨论】:

    • 谢谢,这正是我需要的。所以最后一个参数 w 'in range(0, width, w)' 用于步进循环,使循环更简洁。
    猜你喜欢
    • 2011-11-11
    • 1970-01-01
    • 2010-10-24
    • 2012-12-22
    • 1970-01-01
    • 2013-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多