如何从多个灰度图像为 CNN 创建三波段组合图像

How to create three band combination images from multiple gray scale images for CNN

我在 Keras 中使用 CNN。我有 21 个灰度 GeoTiff 图像,需要创建 450 个三层波段组合以用作下面代码中的 'rgb'。

前5张灰度图像为主数据,其余为辅助图像。组合成员具有 a) 主图像中的一个成员和辅助图像中的两个成员或 b) 主图像中的两个成员和辅助图像中的一个成员。

可以在下面找到从两个列表创建可能的三层组合的代码。

我的问题是如何将它应用于图像并创建由三个灰度图像组成的波段组合?

image1 = Image.open('ras1.tif')
# convert first image to numpy array
img1 = asarray(image1)
.
.
.
image21 = Image.open('ras21.tif')
# convert last image to numpy array
img21 = asarray(image21)

from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rescale=1./255)

img_train_generator = train_datagen.flow_from_directory(
                "train/image/",
                target_size=(64, 64),
                batch_size=batch_size,
                class_mode= None,
                color_mode='rgb',
                shuffle=False)

正在测试 5 张图像的解决方案:

import os
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt

path= 'C:/dataset/test'
os.chdir(path)

primary   = list(range(1,4))           # primary = [1, 2, 3]
ancillary = list(range(4,6))          # ancillary = [4, 5]

# Make empty list of images
images = []

# Load all images, primary and ancillary
for i in [*primary, *ancillary]:
    filename = f'ras{i}.tif'
    print(filename)
    im = np.array(Image.open(filename))
    images.insert(i,im)

result:

ras1.tif
ras2.tif
ras3.tif
ras4.tif
ras5.tif

def apply_op(primary, ancillary):
    ret = []
    for i in range(len(primary)):
        for j in range(i + 1, len(primary)):
            for k in range(len(ancillary)):
                ret.append((primary[i], primary[j], ancillary[k]))
    for i in range(len(primary)):
        for j in range(len(ancillary)):
            for k in range(j + 1, len(ancillary)):
                ret.append((primary[i], ancillary[j], ancillary[k]))
    return ret

print(apply_op(primary, ancillary))

result:

[(1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5), (2, 3, 4), (2, 3, 5), (1, 4, 5), (2, 4, 5), (3, 4, 5)]

merged = np.dstack((1, 2, 5))

plt.imshow(merged)
plt.show()

不太确定你的哪一部分有困难,但这里有一些想法。


首先,制作主要列表和辅助列表以与其他链接问题中的代码一起使用:

primary   = list(range(1,6))           # primary = [1, 2, 3, 4, 5]
ancillary = list(range(6,22))          # ancillary = [6, 7, ..., 20, 21]

现在,与其编写 21 次代码来读取图像,不如使用如下循环:

# Make empty list of images
images = []

# Load all images, primary and ancillary
for i in [*primary, *ancillary]:
    filename = f'ras{i}.tif'
    print(filename)
    im = np.array(Image.open(filename))
    images.insert(i,im)

接下来,调用您链接到的代码(传递 primaryancillary)以获得所需的组合并在循环中迭代它们。


对于每个组合,将所需的三个单通道图像(channel1channel2channel3)合并为一个 3 通道图像:

import numpy as np

merged = np.dstack((channel1, channel2, channel3))