Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I was doing a course which taught data science; it had a portion on using NumPy arrays for image inversion. It's able to invert jpg, but isn't able to invert PNG, I tried other images with the same extension, it doesn't work on those which have "png" extension (it only shows a transparent image).

What can be the problem? Thank you!

from PIL import Image
from IPython.display import display

#displaying the image
img = Image.open(r"./download.png")
display(img)

#converting the image into an array
imgArray = np.array(img)
imgArrayShape = imgArray.shape

#inverting the image
fullArray = np.full(imgArrayShape, 255)
invertedImageArray = abs(fullArray - imgArray) 
invertedImageArray = invertedImageArray.astype(np.uint8)

#displaying the inverted image
invertedImage = Image.fromarray(invertedImageArray)
display(invertedImage)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
413 views
Welcome To Ask or Share your Answers For Others

1 Answer

As far as I could tell, the problem was, that you inverted the Alpha Channel as well. The following code adaptation works on my end:

from PIL import Image
import numpy as np

#displaying the image
img = Image.open("test.png")
img.show()

#converting the image into an array
imgArray = np.array(img)
imgArrayShape = imgArray.shape

#inverting the image
fullArray = np.full(imgArrayShape, [255, 255, 255, 0])
invertedImageArray = abs(fullArray - imgArray) 
invertedImageArray = invertedImageArray.astype(np.uint8)

#displaying the inverted image
invertedImage = Image.fromarray(invertedImageArray)
invertedImage.show()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...