保存图像期间在PIL中出现“ SystemError:图块无法扩展到外部图像”

Sud*_*Das 3 python image image-processing computer-vision

我有这张图片=>

在此处输入图片说明

这是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 
Run Code Online (Sandbox Code Playgroud)

我的目的是裁剪这些框并将所有框另存为Image。我已经为此写了一个代码,但是出错了。

这是我的代码=>

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
Run Code Online (Sandbox Code Playgroud)

我收到这些错误=>

追溯(最近一次呼叫最近):在img2.save(name)中的文件“ reshape.py”,第26行,文件“ /usr/lib/python2.7/dist-packages/PIL/Image.py”,第1468行,在save save_handler(self,fp,filename)文件“ /usr/lib/python2.7/dist-packages/PIL/PngImagePlugin.py”的第624行中,在_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:图块无法扩展到外部图像

我该如何解决?

Ami*_*ein 7

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

imageScreenshot.crop((x, y, width, height))
Run Code Online (Sandbox Code Playgroud)

但正确的方法是这样的:

imageScreenshot.crop((x, y, x + width, y + height))
Run Code Online (Sandbox Code Playgroud)

这意味着你应该添加xwidthyheight
这是一个简单的例子(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)
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你。


Jer*_*uke 5

参考注释,由于坐标不正确地传递给PIL crop()函数而发生错误。

正如所提到的文档,则该函数返回具有取入的4元组的图像(xywidthheight)。

在给定的文本文件y中,第一列提到x坐标,第二列提到坐标。crop()但是,该函数将x座标值作为第一个参数,将y座标值作为第二个参数。

同样适用于OpenCV

这是与此有关的另一篇文章

  • 指出对我来说阿米尔侯赛因的答案实际上是正确的。参数是 `imageScreenshot.crop((x, y, x + width, y + height))` 而不是 `imageScreenshot.crop((x, y, width, height))` (2认同)