本文介绍了使用自定义颜色将 numpy 数组另存为单通道 png的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个整数 numpy 数组,表示图像的值很少(大约 2-5).我想将它保存到带有每个值的自定义颜色的 png 文件中.我是这样尝试的:

I have an integer numpy array representing image with few values (about 2-5). And I would like to save it to png file with custom color for every value.I was trying it like this:

import numpy as np
from PIL import Image

array = np.zeros([100, 200, 4], dtype=np.uint8)
array[:,:100] = [255, 128, 0, 255] #Orange left side
array[:,100:] = [0, 0, 255, 255]   #Blue right side

img = Image.fromarray(array)
img.save(r'D:\test.png')

结果还可以,但它有 4 个通道.我需要结果是具有自定义颜色的单通道.

The result is ok, but it has 4 channels. I need the result to be single channel with custom colors.

我是这样尝试的:

array = np.zeros([100, 200], dtype=np.uint8)
array[:,:100] = 1
array[:,100:] = 0

结果是单通道,但当然是graysale.我不知道如何将颜色分配给值 1 和 0 并将其保存为单通道.正在尝试使用 matplotlib 颜色图,但没有成功.

the result is single channel, but it is of course graysale. I can't figure out how to assign color to values 1 and 0 and save it as single channel. Was trying play around with matplotlib colormaps, but with no success.

任何帮助将不胜感激

推荐答案

您可以像这样制作调色板图像:

You can make a palette image like this:

#!/usr/bin/env python3

from PIL import Image
import numpy as np

# Make image with small random numbers
im = np.random.randint(0,5, (4,8), dtype=np.uint8)

# Make a palette
palette = [255,0,0,    # 0=red
           0,255,0,    # 1=green
           0,0,255,    # 2=blue
           255,255,0,  # 3=yellow
           0,255,255]  # 4=cyan
# Pad with zeroes to 768 values, i.e. 256 RGB colours
palette = palette + [0]*(768-len(palette))

# Convert Numpy array to palette image
pi = Image.fromarray(im,'P')

# Put the palette in
pi.putpalette(palette)

# Display and save
pi.show()
pi.save('result.png')

这篇关于使用自定义颜色将 numpy 数组另存为单通道 png的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 14:16
查看更多