【发布时间】:2018-09-05 13:24:06
【问题描述】:
from os import listdir
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from keras.applications.vgg19 import preprocess_input
from keras.applications.vgg19 import decode_predictions
from keras.applications.vgg19 import VGG19
from keras.preprocessing import image
from keras.models import Model
from PIL import Image
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
import numpy as np
import os
import time
import matplotlib.pyplot as plt
import csv
from pickle import dump
import xlsxwriter
from sklearn.feature_extraction import DictVectorizer
import pandas as pd
import os
from openpyxl import load_workbook
import xlsxwriter
import pickle
# load an image from file
path1 = '/home/mclab/Desktop/Test' #path of folder of images
# extract features from each photo in the directory
def extract_features(directory):
# load the model
model = VGG16()
# re-structure the model
model.layers.pop()
model = Model(inputs=model.inputs, outputs=model.layers[-1].output)
# summarize
print(model.summary())
# extract features from each photo
features = dict()
for name in listdir(directory):
# load an image from file
filename = directory + '/' + name
image = load_img(filename, target_size=(224, 224))
# convert the image pixels to a numpy array
image = img_to_array(image)
# reshape data for the model
image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))
# prepare the image for the VGG model
image = preprocess_input(image)
# get features
feature = model.predict(image, verbose=0)
# get image id
image_id = name.split('.')[0]
# store feature
features[image_id] = feature
print('>%s' % name)
return features
# extract features from all images
directory = path1
features = extract_features(directory)
print('Extracted Features: %d' % len(features))
print (features)
我从给定目录中的数据中为 4 个输入图像运行此代码。我的字典是这种形式的
特征 = {'1': array([[0. , 4.845782 , 0. , ..., 2.6509986, 0. ,
0. ]], dtype=float32), '3': 数组([[0. , 0.5562537, 0. , ..., 1.1013255, 0. ,
0. ]], dtype=float32), '2': 数组([[0.11465299, 0., 3.7899919, ..., 0., 0.,
0. ]], dtype=float32), '4': 数组([[0. , 0. , 0. , ..., 0. , 2.6636925,
0.]], dtype=float32)}
我注意到字典中的每个值都由关键图像的特征数组表示。我的问题是:如何将输入图像的特征数组保存在 excel 文件中,以便将这些特征用于回归问题。
【问题讨论】:
-
@Georgy,我认为
dict的结构实际上与您的副本非常不同。 OP 的字典实际上更容易处理,因为我们可以聚合到一个numpy数组中,这实际上是您在这种情况下应该执行的操作。 -
@jpp 除了链接帖子中的数据结构比较复杂之外,问题基本相同,所以我认为应该标记为重复。但我可能错了,这就是为什么它说“可能重复”。 :) 尽管如此,您的答案更适合这种特殊情况,并且绝对应该保留,这就是我赞成它的原因。
-
@Georgy,不是批评,我自己也经常犯同样的错误:)。我只是担心用户会去另一个帖子并尝试逐行编写。
标签: python arrays python-2.7 csv dictionary