如何在txt文件中为文件夹的所有图像写入特征向量,以便将来进行TSNE处理

2024-10-03 00:23:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我用Pythorch中的resnet50创建图像特征向量。 每个特征向量的长度为2048。当我想把它写入一个txt文件时,我必须把它转换成str,就像我在下面的代码中所做的那样。问题是,长度为2048的向量中只有几个数字保存在txt文件中。我该怎么解决这个问题?在

另外,我的每个文件名(图像)都有一个1到9(9个类)的标签。在

下面的代码是对这个repo的修改:https://github.com/christiansafka/img2vec

import numpy as np
import sys
import os
sys.path.append("..")  # Adds higher directory to python modules path.
from img_to_vec import Img2Vec
from PIL import Image
from sklearn.metrics.pairwise import cosine_similarity
import glob


input_path = "my image folder**"
img2vec = Img2Vec()
vector_fh = open('resnet50_feature_vectors.txt', 'w+')


# For each test image, we store the filename and vector as key, value in a dictionary
pics = {}

filenames = glob.glob(input_path + "/*.*")

for filename in filenames:
    print(filename)
    img = Image.open(filename)
    nd_arr = img2vec.get_vec(img)
    #str_arr = nd_arr.tostring()
    str_arr = np.array2string(nd_arr, formatter={'float_kind':lambda x: "%.2f" % x})
    vector_fh.write(str_arr+"\n")

以下是我收到的结果:

$head resnet50_功能_向量.txt在

^{pr2}$

如何修复特征向量在txt文件中的保存方式?在

我试图遵循教程here,其中有一个包含每个特征向量的.txt文件和一个包含每个特征向量标签的txt文件。在

我说的是MNIST数据集https://lvdmaaten.github.io/tsne/code/tsne_python.zip教程中的Python部分


Tags: 文件pathfromimporttxtimgfilenameglob