Python像素操作返回灰色图像而不是反转图像

2024-06-25 22:33:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为一个项目做一些原型代码。我使用Pillow来打开图像和其他一些次要的事情,但是我想用像素值手动反转图像。我用了2的补码,希望能颠倒过来。但是,当我显示最终图像时,它是一个实心的灰色正方形,而不是反转的颜色。我刚用了一张负鼠的照片,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()

Tags: 图像imagenumpydataval像素outbits
1条回答
网友
1楼 · 发布于 2024-06-25 22:33:11

您可以很简单地用PIL/枕头翻转:

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

把莉娜变成否定的莉娜:

enter image description here


或者,如果你想更数学化一点:

^{pr2}$

如果你想象一个黑色的图像用(0,0,0)来表示,一个白色的图像用(255255255)来表示,希望不难看出颜色的反转是通过从255减去而不是使用二的补码来实现的。在

相关问题 更多 >