Python 为什么在尝试将图像分成两半时出现 tile 无法扩展外部图像错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36492263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why am I getting tile cannot extend outside image error when trying to split image in half
提问by Keatinge
My program is supposed to take an image and split it vertically into n sections, then save the sections as individual png files. It should look something like this for 2 sections
我的程序应该拍摄一张图像并将其垂直拆分为 n 个部分,然后将这些部分保存为单独的 png 文件。对于 2 个部分,它应该看起来像这样
I'm having problems right now, what I'm getting is the first half of my image get saved properly, and then I'm getting the following error when it tries to crop the second half:
SystemError: tile cannot extend outside image
我现在遇到了问题,我得到的是图像的前半部分被正确保存,然后在尝试裁剪后半部分时出现以下错误:
SystemError: tile cannot extend outside image
The image I'm working with has
我正在使用的图像有
- Width: 1180px
- Height: 842px
- 宽度:1180px
- 高度:842px
The rectangles it calculates to crop is:
它计算裁剪的矩形是:
(0.0, 0, 590.0, 842)
- this works properly(590.0, 0, 590.0, 842)
- this crashes the program
(0.0, 0, 590.0, 842)
- 这工作正常(590.0, 0, 590.0, 842)
- 这会导致程序崩溃
My questions is: Why is this sub rectangle out of bounds and how can I fix it to properly slice my image in half like shown in picture?
我的问题是:为什么这个子矩形越界,我如何修复它以正确地将我的图像切成两半,如图所示?
from PIL import Image, ImageFilter
im = Image.open("image.png")
width, height = im.size
numberOfSplits = 2
splitDist = width / numberOfSplits #how many pixels each crop should be in width
print(width, height) #prints 1180, 842
for i in range(0, numberOfSplits):
x = splitDist * i
y = 0
w = splitDist
h = height
print(x, y, w, h)
#first run through prints 0.0, 0, 590.0, 842
#second run through prints 590.0, 0, 590.0, 842 then crashes
croppedImg = im.crop((x,y,w,h)) #crop the rectangle into my x,y,w,h
croppedImg.save("images\new-img" + str(i) + ".png") #save to file
回答by supreeth manyam
All the coordinates of box (x, y, w, h) are measured from the top left corner of the image.
box (x, y, w, h) 的所有坐标都是从图像的左上角开始测量的。
so the coordinates of the box should be (x, y, w+x, h+y). Make the following changes to the code.
所以盒子的坐标应该是(x,y,w+x,h+y)。对代码进行以下更改。
for i in range(0, numberOfSplits):
x = splitDist * i
y = 0
w = splitDist+x
h = height+y