我正在为项目做一些原型代码。我正在使用枕头打开图像和其他一些小东西,但是我想使用像素值手动反转图像。我使用了二进制补码,希望将其取反。但是,当我显示最终图像时,它是一个纯灰色的正方形,而不是反转的颜色。我只使用了275像素乘以183像素的负鼠图片。知道为什么它显示灰色块而不显示反转图像吗?
#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()
答案 0 :(得分:0)
您可以使用PIL / Pillow轻松地反转:
from PIL import Image, ImageChops
# Load image from disk and ensure RGB
im = Image.open('lena.png').convert('RGB')
# Invert image and save to disk
res = ImageChops.invert(im)
res.save('result.png')
将莉娜变成否定莉娜:
或者,如果您想对此进行更多的数学计算:
from PIL import Image
import numpy as np
im = Image.open('lena.png').convert('RGB')
# Make Numpy array
imnp = np.array(im)
# Invert
imnp = 255 - imnp
# Save
Image.fromarray(imnp).save('result.png')
如果您想象黑色图像由(0,0,0)表示而白色图像由(255,255,255)表示,则不难发现通过从255中减去而不是使用二进制补码来实现颜色反转