好的,我刚开始使用python,我需要将一个图像转换为4bpp的一个工具,我遇到了pypng,但我找不到如何只转换为深度为4的图像,所以这是我从几十个例子中得到的结果:
import png
import numpy as np
with open("temporarypng.png", 'wb') as f:
w_depth = png.Writer(im.shape[1], im.shape[0], bitdepth=16)
im_uint16 = np.round(im).astype(np.uint16)
w_depth.write(f, np.reshape(im_uint16, (-1, im.shape[1])))
f.close()不出所料,它不起作用。有人能帮帮我吗?
发布于 2020-07-07 12:03:20
如果您需要4bpp,那么您应该使用bitdepth=4,并且您必须使用值0..15创建array (对于灰度图像),并且还必须使用16个值(R,G,B)为palette创建数组(对于彩色图像)
我使用PIL加载RGB图像,并转换为16种颜色的图像/索引到16种颜色的调色板(RGB)
import png
import numpy as np
from PIL import Image
image = Image.open('zima-400x300.jpg')
# convert RGB to 16 colors
image = image.quantize(16)
# get palette as flat list [r, g, b, r, g, b, ...]
palette = image.getpalette()
# conver flat list to tupled [(r, g, b), (r, g, b), ...]
palette = [tuple(palette[x:x+3]) for x in range(0, len(palette), 3)]
#print(len(palette))
palette = palette[:16]
print(palette)
# get pixels/indexes as numpy array
im = np.array(image)
print(im)
with open('png-4bpp.png', 'wb') as f:
#png_writer = png.Writer(im.shape[1], im.shape[0], bitdepth=4) # without palette
png_writer = png.Writer(im.shape[1], im.shape[0], bitdepth=4, palette=palette) # with palette
png_writer.write(f, im)输入RGB图像

使用调色板输出4bpp

输出不带调色板的4bpp

https://stackoverflow.com/questions/62765455
复制相似问题