如何使用调色板信息编写图像?

2024-05-16 05:03:13 发布

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

我想用Python和/或pypng创建一个带有调色板信息的PNG图像文件

输入为:

  1. 调色板信息

    [[0, 128, 0],
     [0, 64, 128],
     [0, 128, 128],
     [0, 64, 0],
     [0, 64, 64],
     [128, 128, 0],
     ...
    ]
    
  2. 输入图像(numpy.ndarray

    img = cv2.imread("myimage.png")
    print(img)
    
    [[[0, 128, 0],
      [0, 128, 0],
      [0, 128, 0],
      ...
     ]
     [[0, 128, 0],
      [0, 64, 64],
      [0, 64, 0],
      ...
     ]
    ]
    

并且,输出是:

image = PIL.Image.open("output.png")
image = np.array(image)
print(image)

[[0, 0, 0, 0, ..... 5, 5, 5]
 [0, 4, 3, 3, ..... 4, 4, 4]
  ...
]

输入图像和输出图像在视觉上必须相同

在使用PIL.Image.open读取输出图像并将其更改为NumPy数组后,应如上所述输出该图像

有没有办法做到这一点


Tags: 图像imagenumpy信息imgpilpng图像文件
1条回答
网友
1楼 · 发布于 2024-05-16 05:03:13

下面是一些将现有RGB图像转换为indexed color image的演示代码。请记住,这个枕头只允许在一些调色板中存储256种不同的颜色,参见^{}。因此,请确保您的输入图像包含的颜色不超过256种

此外,我将假设调色板以前是已知的,并且现有RGB图像中的所有颜色都完全来自该调色板。否则,您需要添加代码来提取所有颜色,并预先设置适当的调色板

import cv2
import numpy as np
from PIL import Image

# Existing palette as nested list
palette = [
    [0, 128, 0],
    [0, 64, 128],
    [0, 128, 128],
    [0, 64, 0],
]

# Existing RGB image, read with OpenCV (Attention: Correct color ordering)
img = cv2.imread('myimage.png')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
h, w = img.shape[:2]
print(img)
# [[[  0 128   0]
#   [  0 128   0]
#   [  0 128   0]
#   ...
#   [  0 128 128]
#   [  0 128 128]
#   [  0 128 128]]

# Generate grayscale output image with replaced values
img_pal = np.zeros((h, w), np.uint8)
for i_p, p in enumerate(palette):
    img_pal[np.all(img == p, axis=2)] = i_p
cv2.imwrite('output.png', img_pal)

# Read grayscale image with Pillow
img_pil = Image.open('output.png')
print(np.array(img_pil))
# [[0 0 0 ... 2 2 2]
#  [0 0 0 ... 2 2 2]
#  [0 0 0 ... 2 2 2]
#  ...
#  [1 1 1 ... 3 3 3]
#  [1 1 1 ... 3 3 3]
#  [1 1 1 ... 3 3 3]]

# Convert to mode 'P', and apply palette as flat list
img_pil = img_pil.convert('P')
palette = [value for color in palette for value in color]
img_pil.putpalette(palette)

# Save indexed image for comparison
img_pil.save('output_indexed.png')

这是现有的RGB图像myimage.png

Input

这是中间色output.png–您很可能看不到不同的深灰色、近黑色:

Output

为了进行比较,这是转换为modeP并应用调色板后的索引彩色图像:

Indexed output

                    
System information
                    
Platform:      Windows-10-10.0.19041-SP0
Python:        3.9.1
PyCharm:       2021.1.1
NumPy:         1.19.5
OpenCV:        4.5.2
Pillow:        8.2.0
                    

相关问题 更多 >