python - 如何避免 Pillow 在保存图像后稍微编辑我的图像?
问题描述
我正在尝试创建一个生成二进制 RGB 图像的脚本,所有像素必须是黑色(0,0,0)或白色(255,255,255)。问题是当脚本保存输出时,一些像素会有不同的黑白深浅的随机值,例如(14,14,14),(18,18,18),(241,241,241)。
#Code generated sample:
from PIL import Image
sample = Image.new('RGB', (2,2), color = (255,255,255))
#A four pixel image that will do just fine to this example
pixels = sample.load()
w, h = sample.size #width, height
str_pixels = ""
for i in range(w): #lines
for j in range(h): #columns
from random import randint
rand_bool = randint(0,1)
if rand_bool:
pixels[i,j] = (0,0,0)
str_pixels += str(pixels[i,j])
#This will be printed later as single block for readability
print("Code generated sample:") #The block above
print(str_pixels)
#Saved sample:
sample.save("sample.jpg")
saved_sample = Image.open("sample.jpg")
pixels = saved_sample.load()
w, h = saved_sample.size
str_pixels = ""
for i in range(w):
for j in range(h):
str_pixels += str(pixels[i,j])
print("Saved sample:")
print(str_pixels)
>> Code generated sample:
>>(255, 255, 255)(0, 0, 0)(0, 0, 0)(255, 255, 255)
>>Saved sample:
>>(248, 248, 248)(11, 11, 11)(14, 14, 14)(242, 242, 242)
一种解决方案是创建一个 philter,当这些值实际使用时将值更改为 0 或 255,但希望有更好的值。这是使用 Windows 测试的。
解决方案
这个问题源于使用.jpg
,它使用有损空间压缩。
我建议使用.png
,这是一种无损压缩,非常适合像您这样具有很少不同值的数据。您可以阅读有关.png
压缩算法的信息以了解更多信息。
推荐阅读
- aurelia - 手动激活 aurelia canDeactivate() 生命周期钩子
- elasticsearch - 慢速 ElasticSearch Serilog
- sql - PL/SQL 输出问题
- python - Python使用CDATA将数组转换为xml
- azure - 我们如何在 azure web 应用程序日志中的 python 烧瓶代码中处理异常
- r - R数据帧转换数据类型?
- python - 如何在 plotly.express.parallel_coordinates 中标记平行矩阵中的离散线
- hasura - 如何通过 HTTP 查询 Hasura API 以调用 SQL“WHERE LIKE”行为?
- javascript - 如何将多维数组保存到文件或mysql中
- reactjs - React Native如何创建一个删除不同元素以及自身的删除按钮