保存图像期间 PIL 中出现“SystemError: tile cannot extend outside image”

新手上路,请多包涵

我有这张图片=>

在此处输入图像描述

这是上面黄色框的所有坐标,写在 3.txt 文件中。

 #Y   X Height     Width

46 135 158 118
46 281 163 104
67 494 188 83
70 372 194 101
94 591 207 98
252 132 238 123
267 278 189 105
320 741 69 141
322 494 300 135
323 389 390 124
380 726 299 157
392 621 299 108
449 312 227 93
481 161 425 150
678 627 285 91
884 13 650 437
978 731 567 158
983 692 60 43
1402 13 157 114

我的意图是裁剪这些框并将所有框保存为图像。我已经为此编写了代码但出现错误。

这是我的代码=>

 from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
from os import listdir
#from scipy.misc import imsave

ARR = np.empty([1,4])
# print(ARR)

i = 0
k = 0
img = Image.open('3.png')

fo = open("3.txt", "r")
for line in fo:
    if not line.startswith('#'):
        for word in line.split():

            ARR[0][i] = int(word)
            print(int(word))
            # ARR[0][i] = int(word)
            i = i +1

    img2 = img.crop((int(ARR[0][1]), int(ARR[0][0]), int(ARR[0][0] + ARR[0][2]), int(ARR[0][1] + ARR[0][3])))
    name = "new-img" + str(k) + ".png"
    img2.save(name)
    k = k + 1
    i = 0

我收到这些错误 =>

回溯(最近调用最后):文件“reshape.py”,第 26 行,in img2.save(name) 文件“/usr/lib/python2.7/dist-packages/PIL/Image.py”,第 1468 行,在保存 save_handler(self, fp, filename) 文件“/usr/lib/python2.7/dist-packages/PIL/PngImagePlugin.py”, line 624, in _save ImageFile._save(im, _idat(fp, chunk), [(“zip”, (0,0)+im.size, 0, rawmode)]) 文件“/usr/lib/python2.7/dist-packages/PIL/ImageFile.py”,第 462 行,在 _save e .setimage(im.im, b) SystemError: tile cannot extend outside image

我该如何解决这些问题?

原文由 Sudip Das 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.1k
2 个回答

参考评论,错误发生是由于不正确地将坐标传递给 PIL 的 crop() 函数。

As mentioned in the documentation , the function returns an image having taken in a tuple of four ( x , y , width and height ).

在给定的文本文件中,第一列中提到了 y x 坐标,第二列中提到了 --- 坐标。然而, crop() 函数接受值 x 坐标作为第一个参数, y 坐标作为第二个参数。

这同样适用于 OpenCV。

原文由 Jeru Luke 发布,翻译遵循 CC BY-SA 4.0 许可协议

网上提到的方式是这样的:

 imageScreenshot.crop((x, y, width, height))

但正确的做法是这样的:

 imageScreenshot.crop((x, y, x + width, y + height))

这意味着您应该 height x width y

这是一个简单的示例( driver 用于 python selenium):

 def screenShotPart(x, y, width, height) -> str:
    screenshotBytes = driver.get_screenshot_as_png()
    imageScreenshot = Image.open(BytesIO(screenshotBytes))
    imageScreenshot = imageScreenshot.crop((x, y, x + width, y + height))
    imagePath = pathPrefix + "_____temp_" + str(time.time()).replace(".", "") + ".png"
    imageScreenshot.save(imagePath)

希望能帮助到你。

原文由 Amir Hossein Baghernezad 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题