我需要将已在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))])
答案 0 :(得分: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文件,其文件名位于每列的顶部,并在其下方显示相应的数据。