gpt4 book ai didi

python - 使用 PIL 为高维图像绘制矩形时 draw.rectangle([x1, y1, x2, y2], fill ="Black") 出错

转载 作者:行者123 更新时间:2023-12-01 21:40:53 25 4
gpt4 key购买 nike

在使用 PIL python 库为高维 png 文件 (770x1024) 绘制矩形时,我在 draw.rectangle([x1, y1, x2, y2], fill="Black") 中遇到错误。但它适用于中等尺寸的图像。

img = Image.open(BytesIO(file_byte_string))
width, height = img.size
.
.
if(doc.pages):
page = doc.pages[0]
.
.
for field in page.form.fields:
if(field.key and field.value):

.
.
x1 = field.value.geometry.boundingBox.left*width
y1 = field.value.geometry.boundingBox.top*height-2
x2 = x1 + (field.value.geometry.boundingBox.width*width)+5
y2 = y1 + (field.value.geometry.boundingBox.height*height)+2
draw = ImageDraw.Draw(img)
draw.rectangle([x1, y1, x2, y2], fill="Black")
.
.

样本 x1, y1, x2, y2 抛出错误:x1: 504.6949750185013 y1: 243.70870971679688 x2: 557.9484252631664 y2: 255.90338134765625我该如何处理?我是否需要以编程方式或任何其他替代解决方案调整大小?

这是堆栈跟踪:

======================================================================
ERROR: testDataPull (__main__.TestLambda)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Python\Python38\lib\site-packages\PIL\ImagePalette.py", line 99, in getcolor
return self.colors[color]
KeyError: (0, 0, 0)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "c:\TestLambda\lambda_test.py", line 22, in testDataPull
lambda_handler(event, "")
File "c:\TestLambda\lambda_function.py", line 21, in lambda_handler
ret_str = redact_go(my_bucket,my_key)
File "c:\TestLambda\redact.py", line 63, in redact_go
draw.rectangle([x1, y1, x2, y2], fill="Black")
File "C:\Python\Python38\lib\site-packages\PIL\ImageDraw.py", line 246, in rectangle
ink, fill = self._getink(outline, fill)
File "C:\Python\Python38\lib\site-packages\PIL\ImageDraw.py", line 118, in _getink
fill = self.palette.getcolor(fill)
File "C:\Python\Python38\lib\site-packages\PIL\ImagePalette.py", line 109, in getcolor
self.palette[index + 256] = color[1]
IndexError: bytearray index out of range

----------------------------------------------------------------------
Ran 1 test in 20.892s

FAILED (errors=1)

最佳答案

我怀疑问题在于,当您打开一个较小的图像时,它的像素和颜色较少,因此更可能是调色图像而不是全彩色 RGB 图像 - 请参阅 here进行解释。

因此,我建议您在程序开始时更改为:

# Open image and ensure it is 3-channel RGB, not palettised
img = Image.open(BytesIO(file_byte_string)).convert('RGB')

关于python - 使用 PIL 为高维图像绘制矩形时 draw.rectangle([x1, y1, x2, y2], fill ="Black") 出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61359713/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com