0

我需要将已在 Python 中处理的图像名称附加到输出 .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))])
4

1 回答 1

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 文件,文件名位于每列的顶部,相应的数据位于其下方。

于 2013-07-01T20:52:23.027 回答