我有12个,三个频道,RGB图片(.jpeg).我想把它们合并成一个独特的12个通道的图像使用Python .

我try 了以下代码,将每个图片转换为NumPyarray.我成功地创建了一个在轴2上有12个数组的3D数组,但PIL似乎不支持保存多通道图像:

from PIL import Image
import numpy as np

# Load the first image
path = 'test_img_0000_Ch1.jpeg'
img = Image.open(path)
arr = np.array(img.convert('L'))

for x in range(2, 13):
    path = '_test_img_0000_Ch{x}.jpeg'
    img = Image.open(path)
    array_stack = np.array(img.convert('L'))
    arr = np.dstack((arr, array_stack))

image = Image.fromarray(arr)
image.save("multichannel.jpeg")

推荐答案

您可以创建一个包含12个图像的"multi-page" TIFF,每个图像的宽度为640px,高度为480px,如下所示:

from tifffile import imwrite
import numpy as np

# Create stack of 12 images, each 640x480 pixels
data = np.zeros((12,480,640), np.uint8)

# Make first image fully black, 2nd image grey(20), 3rd image grey(40)
for i in range(12):
    data[i, :, :] = 20 * i

# Save as 12 image multi-page TIFF
imwrite('result.tif', data, photometric='minisblack')

如果您现在在macOS Preview图像查看器中打开它,您将看到单个TIFF文件包含12个图像,每个图像依次比前一个更亮:

enter image description here

如果你用ImageMagick判断它的内容,你会在单个TIFF中找到12个单独的图像:

identify result.tif

result.tif[0] TIFF 640x480 640x480+0+0 8-bit Grayscale Gray 3.51761MiB 0.000u 0:00.000
result.tif[1] TIFF 640x480 640x480+0+0 8-bit Grayscale Gray 0.000u 0:00.000
result.tif[2] TIFF 640x480 640x480+0+0 8-bit Grayscale Gray 0.000u 0:00.000
result.tif[3] TIFF 640x480 640x480+0+0 8-bit Grayscale Gray 0.000u 0:00.000
result.tif[4] TIFF 640x480 640x480+0+0 8-bit Grayscale Gray 0.000u 0:00.000
result.tif[5] TIFF 640x480 640x480+0+0 8-bit Grayscale Gray 0.000u 0:00.000
result.tif[6] TIFF 640x480 640x480+0+0 8-bit Grayscale Gray 0.000u 0:00.000
result.tif[7] TIFF 640x480 640x480+0+0 8-bit Grayscale Gray 0.000u 0:00.000
result.tif[8] TIFF 640x480 640x480+0+0 8-bit Grayscale Gray 0.000u 0:00.000
result.tif[9] TIFF 640x480 640x480+0+0 8-bit Grayscale Gray 0.000u 0:00.000
result.tif[10] TIFF 640x480 640x480+0+0 8-bit Grayscale Gray 0.000u 0:00.000
result.tif[11] TIFF 640x480 640x480+0+0 8-bit Grayscale Gray 0.000u 0:00.000

如果您现在想要将其读回,并将通道0、6和11作为R、G和B:

from tifffile import imread
from PIL import Image

im = imread('result.tif')
# Take channels 0, 6 and 11 as R, G and B
rgb = np.dstack((im[0], im[6], im[11]))
Image.fromarray(rgb).save('result.jpg')

红色通道是零,绿色通道是120,蓝色通道是220,所以结果基本上是蓝色的.

enter image description here

Python相关问答推荐

通过优化空间在Python中的饼图中添加标签

try 与gemini-pro进行多轮聊天时出错

点到面的Y距离

如何避免Chained when/then分配中的Mypy不兼容类型警告?

Python 约束无法解决n皇后之谜

切片包括面具的第一个实例在内的眼镜的最佳方法是什么?

为什么sys.exit()不能与subproccess.run()或subprocess.call()一起使用

加速Python循环

Python中绕y轴曲线的旋转

OR—Tools中CP—SAT求解器的IntVar设置值

DataFrames与NaN的条件乘法

如何启动下载并在不击中磁盘的情况下呈现响应?

如何使regex代码只适用于空的目标单元格

python sklearn ValueError:使用序列设置数组元素

并行编程:同步进程

根据客户端是否正在传输响应来更改基于Flask的API的行为

当HTTP 201响应包含 Big Data 的POST请求时,应该是什么?  

如果不使用. to_list()[0],我如何从一个pandas DataFrame中获取一个值?

两个名称相同但值不同的 Select 都会产生相同的值(discord.py)

使用Scikit的ValueError-了解