I am creating an image using pillow and imageDraw.Draw pixel for pixel. In the start when i initialize the image with image.New it uses 9gb of memory. That is ok and no problem. During the process when the script is adding the correct pixel values to each pixel it still uses 9gb of memory but exactly when it is going to save the image it gets terminated for using too much memory. The image is 60000 by 40000 i'm using debian and it only says killed but when I check logs it says it used to much memory. Any tips? Here is the relevant code.
WIDTH, HEIGHT = 60000, 40000
im = Image.new('HSV', (WIDTH, HEIGHT), (0, 0, 0))
draw = ImageDraw.Draw(im)
# some processing
for x in range(WIDTH):
for y in range(HEIGHT):
draw.point([x, y], (hue, saturation, value))
im.convert('RGB').save('output.png', 'PNG')
My first tip would be not to process images in Python with for
loops - they are very slow, inefficient and error-prone. Use built-in, vectorised or Numpy functions instead.
The actual issue is probably that you create your image as HSV and then convert it to RGB in the last line. As that operation returns a new PIL Image
, it instantly doubles the memory demand since both the old (HSV) and new (RGB) objects exist at the same time.
As your question gives little indication of what you are trying to achieve, or what the omitted processing involves it is hard to help any further. If you insist on processing with for
loops, you might consider creating your image as RGB in the first place and converting each calculated HSV value to RGB "on the fly" so you don't need to hold to both entire images in memory at the same time.
Another option might be to use the OpenCV function cvtColor to do an "in situ" transformation from HSV to RGB.