Problems dividing an image into squares in python

0

I'm trying to crop an image using python, but I do not understand why this code gives an error:

imagen = PIL.Image.open("imagen-entera.jpg")
ancho = int(imagen.size[0]/8)
alto = int(imagen.size[1]/8)
for si in range (8):
    for gh in range (8):
        caja = (gh*ancho, si*alto, ancho, alto)
        print (caja)
        print ('tamaño: ' + str(imagen.size))
        region = imagen.crop(caja)
        path = 'cuadrado'+str(si*gh+gh)+'.png'
        print (path)
        region.save(path)

The error it gives is this:

(0, 0, 225, 315)
tamaño: (2925, 1260)
cuadrado0.png
(225, 0, 225, 315)

tamaño: (2925, 1260)
cuadrado1.png
Traceback (most recent call last):
  File "/home/manu/.local/lib/python3.6/site-packages/PIL/ImageFile.py", line 481, in _save
    fh = fp.fileno()
AttributeError: '_idat' object has no attribute 'fileno'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "GUI.py", line 157, in <module>
    app = GUI(root)
  File "GUI.py", line 68, in __init__
    region.save(path)
  File "/home/manu/.local/lib/python3.6/site-packages/PIL/Image.py", line 1950, in save
    save_handler(self, fp, filename)
  File "/home/manu/.local/lib/python3.6/site-packages/PIL/PngImagePlugin.py", line 823, in _save
    [("zip", (0, 0)+im.size, 0, rawmode)])
  File "/home/manu/.local/lib/python3.6/site-packages/PIL/ImageFile.py", line 489, in _save
    e.setimage(im.im, b)
SystemError: tile cannot extend outside image
    
asked by Universal_learner 05.08.2018 в 19:35
source

1 answer

1

You have the problem in the calculation of the area to be cut, according to the documentation of crop() the area is defined as box – The crop rectangle, as a (left, upper, right, lower)-tuple. :

caja = (gh*ancho, si*alto, ancho, alto)

Here the parameters rigth , lower will always be the same, so an error occurs with the second cut since the coordinates would be inconsistent. What we should do is indicate the coordinates relative to each clipping, for something like this:

caja = (gh*ancho, si*alto, (gh*ancho) + ancho, (si*alto) + alto)
    
answered by 05.08.2018 / 20:03
source