【问题标题】:Apply function to each row of array with shape (28000,2304)将函数应用于形状为 (28000,2304) 的每一行数组
【发布时间】:2020-10-13 21:37:08
【问题描述】:

我有一个形状数组(28000、2304)。下面的代码是我想应用于每一行,然后返回一个最终数组,其大小为 (28000, 5625)

image_array = X_train[0]
img = image_array.reshape(48,48)
resized_width = 75
resized_height = 75
dimension = (resized_width, resized_height)

resized = cv2.resize(img, dimension, interpolation = cv2.INTER_CUBIC)
image_array = resized.flatten()

X_train 是我的形状数组(28000、2304)。 X_train[0] 将是 28000 数组中的第一行。上面的代码在展平调整大小的图像数组后返回一个长度为 (5625) 的向量。所以我想将上面的代码应用于所有 28000 行,而不仅仅是 X_train[0]。我将如何遍历或循环 X_train 并应用此代码以获得最终的形状数组(28000、5625)。谢谢。

【问题讨论】:

    标签: python numpy for-loop multidimensional-array iteration


    【解决方案1】:

    应该只是跨所有行的简单 for 循环,将值附加到结果数组将产生 28000 行,每行包含您的 image_array 元素

    result = []
    for image_row in X_train:
        image_array = image_row
        img = image_array.reshape(48,48)
        resized_width = 75
        resized_height = 75
        dimension = (resized_width, resized_height)
    
        resized = cv2.resize(img, dimension, interpolation = cv2.INTER_CUBIC)
        image_array = resized.flatten()
        result.append(image_array)
    

    【讨论】:

    • 非常感谢您的帮助。接下来我需要将每个通道从 1 个通道 (75,75,1) 转换为 3 个通道 (75,75,3)。这是使用 skimage.color 完成的
    【解决方案2】:

    这成功了...

    from skimage.color import grey2rgb
    resized_width = 75
    resized_height = 75
    
    X_train_resized = []
    for image_row in X_train:
        image_array = image_row
        img = image_array.reshape(48,48)
        dimension = (resized_width, resized_height)
        resized = cv2.resize(img, dimension, interpolation = cv2.INTER_CUBIC)
        img = resized
        rgb_img = grey2rgb(img)
        rgb_img = rgb_img.astype('uint8')
        X_train_resized.append(rgb_img)
    
    X_test_resized = []
    for image_row in X_test:
        image_array = image_row
        img = image_array.reshape(48,48)
        dimension = (resized_width, resized_height)
        resized = cv2.resize(img, dimension, interpolation = cv2.INTER_CUBIC)
        img = resized
        rgb_img = grey2rgb(img)
        rgb_img = rgb_img.astype('uint8')
        X_test_resized.append(rgb_img)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-06
      • 1970-01-01
      • 1970-01-01
      • 2013-03-18
      • 2014-04-30
      • 1970-01-01
      • 2021-01-11
      • 1970-01-01
      相关资源
      最近更新 更多