2

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"

1
  • 2
    No need for lists or for loops, just use Numpy im = 255-im Commented Mar 7, 2022 at 21:22

2 Answers 2

1

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')
Sign up to request clarification or add additional context in comments.

1 Comment

thank you VicLobato, I am now able to reprogram the whole internet with my eyes closed thanks to your help
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.