2013-07-01 110 views
0

我需要將已經在Python中處理過的圖像的名稱追加到輸出.csv文件中。並將下一個圖像處理的結果放到另一個.csv垂直列或水平行。如何將處理後的圖像的名稱添加到.csv輸出文件?

怎麼樣?下面是代碼:

def humoments(self):    #function for HuMoments computation 
    for filename in glob.iglob ('*.tif'): 
     img = cv.LoadImageM(filename, cv.CV_LOAD_IMAGE_GRAYSCALE) 
     cancer = cv.GetHuMoments(cv.Moments(img)) 
     #arr = cancer 
     arr = numpy.array([cancer]) 
    with open('hu.csv', 'wb') as csvfile: #puts the array to file 
     for elem in arr.flat[:50]: 
      writer = csv.writer(csvfile, delimiter=' ', quotechar='|',  quoting=csv.QUOTE_MINIMAL) 
      writer.writerow([('{}\t'.format(elem))]) 

回答

0

做到這一點,最好的方法是收集在一個列表或陣列中的所有數據,然後通過行其寫入csv文件一行。這裏有一個例子:

import csv 
import numpy 

allFileNames = []; 
allArrs = []; 
for i in range(10): 
    arr = i * numpy.ones((5,5)) # fake data as an example 
    filename = 'file ' + str(i) # fake file names 

    allFileNames.append(filename) # keep track of the file name 
    allArrs.append(list(arr.flatten())) # keep track of the data 

with open('hu.csv', 'wb') as csvfile: #puts the array to file 
    writer = csv.writer(csvfile) 

    # write file names to the first row 
    writer.writerow(allFileNames) 

    # transpose arrs so each list corresponds to a column of the csv file. 
    rows = map(list, zip(*allArrs)) 

    #write array to file 
    writer.writerows(rows) 

這會給你的文件名的CSV文件在每列的頂部和下面的相應數據。

相關問題