MATLAB从struct转换为table并输出为csv

时间:2014-02-07 11:28:10

标签: matlab csv image-processing

作为使用Matlab中的'regionprops'的图像处理管道的一部分,我生成结构:

vWFfeatures = 


1631x1 struct array with fields:

Area
Centroid
MajorAxisLength
MinorAxisLength
Eccentricity
EquivDiameter

其中'Centroid'是包含[x,y]的Vector,例如[12.4,26.2]。我想将此结构转换为表并保存为CSV文件。目标是将“Centroid”向量分为两列,例如Centroid_X和Centroid_Y。我不知道如何实现这一点。

到目前为止,我已经使用'struct2table'函数进行了调查。这将'Centroid'作为一列输出。另外,当我尝试将输出分配给变量时,我得到一个错误:

table = struct2table(vWFfeatures)
Error using struct2table
Too many output arguments.

我无法理解这一点,请帮忙吗?

2 个答案:

答案 0 :(得分:1)

由于您无法使用原始struct2table,因此您可能希望专门实施自己尝试实现的行为。
在这种情况下,这意味着提取要保存的值(拆分数组),然后保存数据:

data_Centroid = vertcat(vWFfeatures.Centroid); %// contains the centroid data
Centroid_X = data_Centroid(:,1); %// The first column is X
Centroid_Y = data_Centroid(:,2); %// the second column is Y
csvwrite('centroid.csv',data_Centroid); %// writes values into csv

如果你想要csv中的列标题,它会变得复杂,因为csvwrite只能处理数值数组:

celldata = num2cell(num2str(data_Centroid)); %// create cell array
celldata(:,3) = celldata(:,4); %// copy col 4 (y data) into col 3 (spaces)
for i=1:length(celldata)
    celldata{i,2} = ','; %// col 2 has commas
    celldata{i,4} = '\n'; %// col 4 has newlines
end
celldata = celldata'; %'// transpose to make the entries come columnwise
strdata = ['Centroid_X,Centroid_Y\n',celldata{:}]; %// contains all as string

fid = fopen('centroid.csv','w'); % writing the string into the csv
fprintf(fid,strdata);
fclose(fid);

答案 1 :(得分:0)

这就是我最终解决它的方法:从结构中使用horzcat提取每个字段以连接到一个新数组然后定义标题并使用csvwrite_with_headers来输出到csv。

wpbFeatures = regionprops(vWFlabelled, 'Area','Centroid', 'MajorAxisLength', 'MinorAxisLength', 'Eccentricity', 'EquivDiameter');
wpbArea = vertcat(wpbFeatures.Area);
wpbCentroid = vertcat(wpbFeatures.Centroid);
wpbCentroidX = wpbCentroid(:,1);
wpbCentroidY = wpbCentroid(:,2);
wpbFeret = max(imFeretDiameter(vWFlabelled, linspace(0,180,201)), [], 2);
wpbMajorAxisLength = vertcat(wpbFeatures.MajorAxisLength);
wpbMinorAxisLength = vertcat(wpbFeatures.MinorAxisLength);
wpbEccentricity = vertcat(wpbFeatures.Eccentricity);
wpbEquivDiameter = vertcat(wpbFeatures.EquivDiameter);
wpbFeatures = horzcat(wpbArea, wpbCentroidX, wpbCentroidY, wpbFeret, wpbMajorAxisLength, wpbMinorAxisLength, wpbEccentricity, wpbEquivDiameter);
headers = {'Area','CentroidX','CentroidY', 'Feret', 'MajorAxisLength', 'MinorAxisLength', 'Eccentricity', 'EquivDiameter'};
csvwrite_with_headers(strcat(PlateName, '_ResultsFeatures.csv'),wpbFeatures,headers);