使用python中的PIL裁剪具有相同裁剪大小的整个图像 [英] Crop entire image with the same cropping size with PIL in python
问题描述
我对PIL python的逻辑有些疑问.我的目标是从左上角到右下角位置完全以64x64大小裁剪一张图像.我可以进行一次裁剪操作,但是当我尝试完全通过循环裁剪图像时,我陷入了中间的循环情况.
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.
在第一个循环中,我可以裁剪((0,0,64,64)).但是,然后我无法弄清楚循环部分用PIL将左下64x64移到底部.由于第一个2元组是原点位置点,因此下一个元组用于裁剪大小.
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.
在我开始学习python时,我们将不胜感激.
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
推荐答案
您可以使用range()
函数为您执行步进(在这种情况下,以64为块),因此您的裁剪仅涉及简单的表达式:
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.
这篇关于使用python中的PIL裁剪具有相同裁剪大小的整个图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!