将JPG,PNG等格式转换为PGM并创建一个数组:Python

问题描述 投票:0回答:1

我正在使用以下函数将.pgm图像转换为数组。但是现在我得到了所有格式的图像,如.jpg / png等,现在我想将所有内容转换为.pgm(没有节省),需要转换为数组。我正在使用以下函数转换为数组

def image_array(pgm):
    pic = image.load_img(pgm, target_size=(224, 224))
    x = image.img_to_array(pic)
    x = np.expand_dims(x, axis=0)
    x = preprocess_input(x)
    npfeatures = np.array(x)
    return npfeatures

我试过下面的方法,但无法将这些东西整合到上面的功能中。

image = cv2.imread('C:/Users/N/Desktop/Test.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

我使用的进口

  • 来自keras.preprocessing导入图片
  • 来自keras.applications.vgg16 import preprocess_input
  • 导入cv2
python-3.x keras computer-vision conv-neural-network
1个回答
0
投票

这应该与你的image_array函数给出相同的结果:

def image_array(filename):
    x = cv2.imread(filename)
    x = cv2.resize(x, (224, 224))
    x = np.expand_dims(x, axis=0)
    x = preprocess_input(x)
    npfeatures = np.array(x)
    return npfeatures

现在,如果你想要一个单通道图像,即(224,224)而不是(224,224,3),只需使用cv2.imread(filename, cv2.IMREAD_GRAYSCALE)

如果你想要它(224,224,3),但看起来是灰色的,即使所有3个颜色成分相等,请使用

    x = cv2.imread(filename, cv2.IMREAD_GRAYSCALE)
    x = cv2.resize(x, (224, 224))
    x = np.tile(np.expand_dims(x, 2), 3)
© www.soinside.com 2019 - 2024. All rights reserved.