2016-04-26 30 views
1

我正在計算從目錄讀取的圖像的功能,我想將圖像路徑和相應的功能寫入文件中,並用空格分隔。輸出期望以這種方式如何在文件中編寫一個字符串和一個numpy數組?

/path/to/img1.jpg 1 0 0 1 3.5 0.2 0 
/path/to/img2.jpg 0 0 0.5 2.1 0 0.7 
... 

以下是我的代碼

features.open('file.txt', 'w') 
for fname in fnmatch.filter(fileList, '*.jpg'): 
    image = '/path/to/image' 
    # All the operations are here 
    myarray = [......] # array of dimensions 512x512 
    myarray.reshape(1, 512*512) # Reshape to make it a row vector 
    features.write(image + ' '.join(str(myarray))) 
features.write('\n') 
features.close() 

一部分,但輸出來作爲

/path/to/img1.jpg[[0 0 1.0 2 3]] 
/path/to/img2.jpg[[1.2 0 1.0 2 0.3]] 
+2

您能否定義「不正確?」一點也不?輸出如何? – tfv

+0

編輯帖子。 –

回答

4

你的問題出在下面的語句:

>>> ' '.join(str(np.array([1,2,3]))) 
'[ 1 2 3 ]' 

你先轉身e數組轉換爲字符串格式

>>> str(np.array([1,2,3])) 
'[1 2 3]' 

然後再加入字符串(單個字符)的元素與中間的空格。


相反,你需要使用map打開numpy的數組的單個元素轉換爲字符串列表,例如。

>>> map(str, np.array([1,2,3])) 
['1', '2', '3'] 

只有這樣,你應該加入生成的字符串列表中的元素:

>>> ' '.join(map(str, np.array([1,2,3]))) 
'1 2 3' 

下一個問題將來自於事實,你有numpy的陣列實際上是二維:

這很容易解決,因爲您已經使用將它變成單行。因此,只需將map應用於第一行:

>>> ' '.join(map(str, np.array([[1,2,3]])[0])) 
'1 2 3' 
相關問題