Search code examples
matlabyolov4matlab-table

Matlab add string variable as column in table


I'm trying to use YOLOv4 in MATLAB R2022b to carry out detections on all images in a directory, and append results to a text file.

I can append just the detection results to each line, but when I try to add the filename I get this error:

You might have intended to create a one-row table with the character vector '000001.jpg' as one of its variables. To store text data in a table, use a string array or a cell array of character vectors rather than character arrays. Alternatively, create a cell array with one row, and convert that to a table using CELL2TABLE.

I understand that the filename is a string, and the values returned by YOLO are a categorical array, but I don't understand the most efficient way to deal with this.

filesDir = dir("/home/ADL-Rundle-1/img1/");
for k=1:length(filesDir)
   baseFileName=filesDir(k).name
   fullFileName = fullfile(filesDir(k).folder, baseFileName);
   if isfile(fullFileName)
        img = imread(fullFileName);
        [bboxes,scores,labels] = detect(detector,img);
        T = table(baseFileName, labels, bboxes, scores); 
        writetable(T,'/home/tableDataPreTrained.txt','WriteMode','Append','WriteVariableNames',0);
   end
end

The format of results from YOLO is enter image description here

And I'd like a file with

000001.jpg, 1547.3, 347.35, 355.64, 716.94, 0.99729

000001.jpg, 717.81, 370.64, 76.444, 108.92, 0.61191

000002.jpg, 1, 569.5, 246.49, 147.25,0.56831


Solution

  • baseFileName is a char vector.

    The error message is telling you to use a cell array of char vectors:

    T = table({baseFileName}, labels, bboxes, scores); 
    

    or a string array:

    T = table(string(baseFileName), labels, bboxes, scores); 
    

    I would use the string array, it's the more modern MATLAB, and the table looks prettier when displayed. But both accomplish the same thing.

    Given that labels and the other two variables have multiple rows, you need to replicate the file name that number of times:

    frame = repmat(string(baseFileName), size(labels,1), 1);
    T = table(frame, labels, bboxes, scores);