用PIL将不同像素保存的图像复制到原始图像

2024-04-18 16:45:05 发布

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

我需要复制一个图像来操作它,但是保存原始图像和打开复制图像的像素值似乎有所不同:

from PIL import Image

# Open original image
img = Image.open("mountain.jpg")
data = img.load()

# Display individual pixels
print("Pixel 1: {}".format(data[0,0]))
print("Pixel 2: {}".format(data[0,1]))
print("Pixel 3: {}".format(data[0,2]))

# Makes a copy of the input image and loads the copied image's pixel map
copyImage = img.copy()

copyImage.save('copy.jpg')
copyImage.close()

# Opens the copied image that was saved earlier and its pixel map
copy = Image.open("copy.jpg")
copy_data = copy.load()

print()

# Display copied images' individual pixels
print("Pixel 1 (copy): {}".format(copy_data[0,0]))
print("Pixel 2 (copy): {}".format(copy_data[0,1]))
print("Pixel 3 (copy): {}".format(copy_data[0,2]))

copy.close()

其输出为:

^{pr2}$

最初,我认为PIL可能会将R、G和B通道中的每个通道的所有像素值更改2个值(如前两个像素所示),但是第三个像素对每个通道有3个值的更改。在

如果复制的图像的起始像素与原始图像相同,如何才能对图像进行可靠的复制以更改其像素?在

注: 我试过其他的图片山.jpg但所有这些似乎都引起了同样的问题。在


Tags: the图像imageformatimgdatapil像素
2条回答

*.jpgcompressed image format。通过再次保存jpg,您可以为jpg writer使用不同的默认质量 因此结果像素值不同。在

有关可以传递给image.save()的参数,请参见image file format params for jpg

quality
The image quality, on a scale from 1 (worst) to 95 (best). The default is 75. Values above 95 should be avoided; 100 disables portions of the JPEG compression algorithm, and results in large files with hardly any gain in image quality.

或者

相关:

问题是将图像另存为JPG。试着用PNG来做。 通过将图像保存为JPG,就可以进行JPG压缩。这会改变像素。做这个

copyImage.save('copy.png')
copyImage.close()

以及

^{pr2}$

注意:

您可能想看看JPG和PNG之间的区别。在

JPG是以丢失数据为代价的压缩

PNG是一种不丢失数据的压缩

JPG会导致图像的大小非常小,但每次保存图像时,都会不断地对其进行基本的压缩。总体质量较低

PNG将导致相当大的尺寸,但保存和加载图像不会导致任何像素变化。在

相关问题 更多 >