Trying to save image from numpy array with PIL, getting errors

Viewed 292

trying to save an inverted image, saved inverted RGB colour data in array pixelArray, then converted this to a numpy array. Not sure what is wrong but any help is appreciated.

from PIL import Image
import numpy as np

img = Image.open('image.jpg')
pixels = img.load()
width, height = img.size

pixelArray = []

for y in range(height):
    for x in range(width):
        r, g, b = pixels[x, y]
        pixelArray.append((255-r,255-b,255-g))

invertedImageArray = np.array(pixelArray, dtype=np.uint8)

invertedImage = Image.fromarray(invertedImageArray, 'RGB')
invertedImage.save('inverted-image.jpeg')
img.show()

getting error code "ValueError : not enough image data"

2 Answers

Your np.array creates an array shape (4000000, 3) instead of (2000, 2000, 3).

Also, you may find that directly mapping the subtraction to the NumPy array is faster and easier

from PIL import Image
import numpy as np

img = Image.open('image.jpg')

pixelArray = np.array(img)
pixelArray = 255 - pixelArray

invertedImageArray = np.array(pixelArray, dtype=np.uint8)

invertedImage = Image.fromarray(invertedImageArray, 'RGB')
invertedImage.save('inverted-image.jpeg')

PIL already provides an easier way to invert the image colours with the ImageOps module.

from PIL import Image, ImageOps

img = Image.open('image.jpg')

invertedImage = ImageOps.invert(img)
invertedImage.save('inverted-image.jpeg')
Related