I'm doing some prototype code for a project. I'm using Pillow to open the image and other minor things, but I want to invert the image manually using its pixel values. I used two's complement in hopes of inverting it. However, when I display the final image, it's a solid grey square instead of inverted colors. I just used a picture of a possum, 275 pixels by 183 pixels. Any idea why it displays grey block and not an inverted image?
#importing Image module
from PIL import Image
import numpy
#sets numpy to print out full array
numpy.set_printoptions(threshold=numpy.inf)
def twos_comp(val, bits):
"""compute the 2's complement of int value val"""
if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255
val = val - (1 << bits) # compute negative value
return val
im = Image.open('possum.jpg')
#im.show()
data = numpy.asarray(im)
#print(data)
#print("FINISHED PRINTING")
#print('NOW PRINTING BINARY')
data_binary = numpy.unpackbits(data)
data_binary.ravel()
#print(data_binary)
#print('FINISHED PRINTING')
#getting string of binary array
binaryString = numpy.array2string(data_binary)
binaryString = ''.join(binaryString.split())
binaryString = binaryString[:-1]
binaryString = binaryString[1:]
#print("Binary String: " + binaryString)
out = twos_comp(int(binaryString,2), len(binaryString))
#print('Now printing twos:')
#print(out)
#formatting non-binary two's comp as binary
outBinary = "{0:b}".format(out)
#print('Now printing binary twos: ' + outBinary)
outBinary = outBinary.encode('utf-8')
a_pil_image = Image.frombytes('RGB', (275, 183), outBinary)
a_pil_image.show()