代码之家  ›  专栏  ›  技术社区  ›  Whoami

显示图像时大小无效

  •  1
  • Whoami  · 技术社区  · 6 年前

    我一直在尝试检索VGG16的隐藏层,并在Keras中显示功能图。我想做的是 block1_conv1 功能图并显示出来。但不幸的是,我得到了以下错误:

    TypeError: Invalid dimensions for image data
    

    请找到以下代码:

    from keras.applications.vgg16 import VGG16
    from keras.preprocessing import image
    from keras.applications.vgg16 import preprocess_input
    from keras.models import Model
    import matplotlib.pyplot as plt
    import numpy as np
    from keras import backend as K
    
    
    img_path = "bombiliki.jpeg"
    img = image.load_img (img_path, target_size=(224,224))
    imgArr = image.img_to_array (img)
    imgArr = np.expand_dims(imgArr, axis=0)
    img = preprocess_input (imgArr)
    
    
    model = VGG16(weights='imagenet', include_top=False)
    layer_name = 'block1_conv1'
    
    interMediateOutput = Model(inputs=model.inputs, outputs=model.get_layer(layer_name).output)
    features = interMediateOutput.predict (img)
    print ("Shape of the feature is ", features.shape)
    pic = features[:,:,:,1]
    print ("pic shape ", pic.shape)
    data = np.asarray(pic)
    print ("Data Dimension is ", data.ndim)
    
    plt.imshow (pic)
    plt.show()
    

    输出:

    ('Shape of the feature is ', (1, 224, 224, 64))
    ('pic shape ', (1, 224, 224))
    ('Data Dimension is ', 3)
    Traceback (most recent call last):
      File "vgg16.py", line 28, in <module>
        plt.imshow (pic)
      File "/home/navals/anaconda2/envs/musarni/lib/python2.7/site-packages/matplotlib/pyplot.py", line 3205, in imshow
        **kwargs)
      File "/home/navals/anaconda2/envs/musarni/lib/python2.7/site-packages/matplotlib/__init__.py", line 1855, in inner
        return func(ax, *args, **kwargs)
      File "/home/navals/anaconda2/envs/musarni/lib/python2.7/site-packages/matplotlib/axes/_axes.py", line 5487, in imshow
        im.set_data(X)
      File "/home/navals/anaconda2/envs/musarni/lib/python2.7/site-packages/matplotlib/image.py", line 653, in set_data
        raise TypeError("Invalid dimensions for image data")
    TypeError: Invalid dimensions for image data
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   today    6 年前

    这个 predict 方法将返回形状的输出 (n_samples, model_output_shape...) .因此,如果你给它一个样本,为了得到对给定样本的预测,你必须这样做:

    pic = features[0]
    

    具体来说,在示例中,如果要选择特定过滤器的输出,则需要将其索引指定为第四个轴:

    pic = features[0, :, :, desired_filter_index]
    

    你可以很容易地绘制出:

    plt.imshow(pic)