2016-12-02 54 views
0

我正在处理一个csv文件,该文件在一列中包含图像(矢量化)。这里是the csv file ~240MB数组和字符串的长度在来回转换时不匹配

我想将图像字符串转换为一个整数列表,重塑成矩阵,翻转,并将其重新整形回列表,然后最终转换回长字符串。但事情并非如我所料。下面是我的代码:

import pandas as pd 
import numpy as np 
df = pd.read_csv('training.csv') 
img = df['Image'][0] # take the first row as example 
img_int = np.fromstring(img, sep=' ') # img_int.shape --> (9216,), good. 
img_matrix = img_int.reshape(96,96) 
img_matrix_flipped = np.fliplr(img_matrix) # img_matrix_flipped.shape --> (96,96), good 
img_matrix_flipped_vector = img_matrix_flipped.reshape(1, 9216) # img_matrix_flipped_vector.shape --> (1, 9216), good 
img_matrix_flipped_vector_str = str(img_matrix_flipped_vector) # len(img_matrix_flipped_vector_str) --> 44, NOT GOOD!!! 

我感到困惑,为什么LEN(img_matrix_flipped_vector_str)为44.如果不是字符串包含所有在它的9216点的整数?请帮助!

+0

据我所知,你的代码没有问题。在你的数组中使用'tostring()'方法可能是一个更好的主意,不能获得所有的数组符号和换行符。 – Dschoni

回答

1

基于@Dschoni的回答,我认为我不应该使用str()方法。然后我发现another topic,这帮助我找到解决方案:

img_matrix_flipped_vector = img_matrix_flipped.reshape(9216) 
list = img_matrix_filpped_vector.tolist() 
str_I_want = ' '.join([str(i) for i in list]) 
+0

只需添加以下内容:您可以直接遍历平展数组以节省内存,而不是遍历列表。根据你称之为连接方法的字符串,这将成为分隔符。 – Dschoni

0

我刚刚发现: 数组上的string()方法返回可打印的字符串表示形式。如果你打印这个字符串,你会看到数字,可能在中间被缩短为'...'。 要将numpy数组转换为字符串,请在阵列上使用tostring()tobytes()方法。 您也可能想要将其重新整形为1维阵列,而不是2维阵列,其中一个轴的大小为1 (array.reshape(9216)而不是array.reshape(1,9216)),具体取决于您要瞄准的目标。

+0

嗨@Dschoni,你说得对,'''str()'''方法是罪魁祸首!但'''tostring()'''''''tobytes()'''不会给我我想要的东西... – user3768495

+0

使用''''x000 \ x0000'''时, ''tostring()''''''tobytes()'''。 – user3768495