Ошибка в draw.rectangle ([x1, y1, x2, y2], fill = Black) при рисовании прямоугольника с помощью PIL для изображений большого размера.

Я получаю ошибку в draw.rectangle ([x1, y1, x2, y2], fill = "Black") при рисовании прямоугольника с помощью библиотеки Python PIL для файла png большого размера (770x1024). Но это работает для изображений среднего размера.

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 Как я могу с этим справиться? Нужно ли мне изменять размер программно или какими-либо другими альтернативными решениями?

Вот StackTrace:

======================================================================
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)

person pforpraphul    schedule 22.04.2020    source источник
comment
Какая ошибка? Пожалуйста, предоставьте также трассировку стека   -  person h4z3    schedule 22.04.2020
comment
Напечатайте значения _1 _, _ 2 _, _ 3 _, _ 4_ непосредственно перед рисованием.   -  person Mark Setchell    schedule 22.04.2020
comment
Я обновил запрос с подробностями об ошибке @ h4z3   -  person pforpraphul    schedule 22.04.2020
comment
x1: 504.6949750185013 y1: 243.70870971679688 x2: 557.9484252631664 y2: 255.90338134765625 @MarkSetchell   -  person pforpraphul    schedule 22.04.2020


Ответы (1)


Я подозреваю, что проблема в том, что когда вы открываете маленькое изображение, оно имеет меньше пикселей и меньше цветов, и поэтому, скорее всего, это изображение с палитрой, а не полноцветное изображение RGB - см. здесь для объяснения.

Итак, я предлагаю вам изменить это в начале вашей программы:

# Open image and ensure it is 3-channel RGB, not palettised
img = Image.open(BytesIO(file_byte_string)).convert('RGB')
person Mark Setchell    schedule 22.04.2020
comment
background = Image.open (f '/ app / public {input}'). convert ('RGB') - person josuedjh; 27.10.2020