使用PyPng转换图像的位深度

2024-05-23 18:21:13 发布

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

好的,我刚开始使用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()

毫不奇怪,它不起作用。有人能帮我吗


Tags: 工具图像importnumpy示例pngaspypng
1条回答
网友
1楼 · 发布于 2024-05-23 18:21:13

如果您需要4bpp,那么您应该使用bitdepth=4,并且您必须使用值0..15(对于灰度图像)创建array,对于palette(对于彩色图像)创建16个值(R,G,B)的数组

我使用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图像

enter image description here

用调色板输出4bpp

enter image description here

不带调色板的输出4bpp

enter image description here

相关问题 更多 >