【问题标题】:How to reshape an ndarray to fir prediction model?如何将 ndarray 重塑为 fir 预测模型?
【发布时间】:2021-08-03 13:19:23
【问题描述】:

我需要读取两个图像,将它们转换为 150x150 的大小,并将它们添加到一个数组中,该数组需要重新整形为 (2, 150, 150, 3) 的形状以适合 keras 模型。我无法理解 numpy 的 reshape 方法的工作原理以及我需要如何使用它。

我的代码:

import cv2
import numpy

def loadAndReshape(target, path):
    targetImage = cv2.imread(path)
    targetImage = cv2.cvtColor(targetImage, cv2.COLOR_BGR2RGB)
    targetImage = cv2.resize(targetImage, dsize=(150, 150)) / 255
    targetImage = targetImage.reshape(1, 150, 150, 3).astype('float32')
    numpy.append(target, targetImage)

targetImages = numpy.ndarray((2, 150, 150, 3))
loadAndReshape(targetImages, './/test1.jpg')
loadAndReshape(targetImages, './/test2.jpg')

重塑targetImage 没有问题,但最终targetImages 仍然是一个空的ndarray。如何输出模型所需的数组?

【问题讨论】:

    标签: python numpy keras cv2


    【解决方案1】:

    numpy.append 返回一个副本,见https://numpy.org/doc/stable/reference/generated/numpy.append.html

    你可以试试这个:

    import cv2
    import numpy
    
    def loadAndReshape(path):
        targetImage = cv2.imread(path)
        targetImage = cv2.cvtColor(targetImage, cv2.COLOR_BGR2RGB)
        targetImage = cv2.resize(targetImage, dsize=(150, 150)) / 255
        targetImage = targetImage.reshape(1, 150, 150, 3).astype('float32')
        return targetImage
    
    li = []
    li.append(loadAndReshape('.//test1.jpg'))
    li.append(loadAndReshape('.//test2.jpg'))
    targetImages = np.array(li)
    

    【讨论】:

    • 非常感谢,不知怎的我错过了它没有到位。
    【解决方案2】:

    函数 'numpy.append' 不能像我想的那样就地工作。 相反,你可以这样做:

    mport cv2
    import numpy as np
    
    def loadAndReshape(image_list, path):
        targetImage = cv2.imread(path)
        targetImage = cv2.cvtColor(targetImage, cv2.COLOR_BGR2RGB)
        targetImage = cv2.resize(targetImage, dsize=(150, 150)) / 255
        targetImage = targetImage.reshape(1, 150, 150, 3).astype('float32')
        image_list.append(targetImage)
    
    targetImages = []
    loadAndReshape(targetImages, './/test1.jpg')
    loadAndReshape(targetImages, './/test2.jpg')
    .
    .
    .
    targetImages = np.concatenate(targetImages)
    

    【讨论】:

      猜你喜欢
      • 2019-03-14
      • 1970-01-01
      • 2017-11-05
      • 1970-01-01
      • 2023-03-12
      • 2021-09-04
      • 1970-01-01
      • 2016-07-07
      • 2023-03-19
      相关资源
      最近更新 更多