File size: 8,774 Bytes
b90e704
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
%% bubbles_annotator
%{
Version: v6
Description: 
This script provides a user interface to manually draw bubble contours on a 
sequence of images. It allows the user to define regions of interest (ROIs) 
interactively. The contour data for all processed images is then aggregated 
and can be exported to a single, structured JSON file.

Instructions:
1. Run this script in MATLAB.
2. A dialog will appear. Select the folder containing your images.
3. For each image, a figure window will open.
   - Left-click to place the vertices of a polygon around a bubble.
   - Keyboard backspace to undo a click point.
   - Double-click to finalize the shape. The bubble will be drawn in red.
4. After each bubble, a dialog will ask for your next action.
   - 'Define more': Draw another bubble on the same image.
   - 'Redefine last bubble': Erase the last bubble you just drew.
   - 'Reset all': Clear all bubbles on the current image and start over.
   - 'Next image': Move to the next image in the folder.
   - 'Stop defining': End the annotation session.
5. At the end, you will be prompted to save all collected data to a JSON file.

Last modified: 2025/10/08
Author: Lige Zhang
Reference: International Journal of Heat and Mass Transfer 255 (2026): 127894.
%}
%% ------------------- Setup -------------------
clear, clc
close all
format long
%% --------------------- SCRIPT INITIALIZATION ---------------------
% Let the user interactively select the folder containing the images
imageFolderDIR = uigetdir('', 'Select the folder containing your SOURCE images');
if imageFolderDIR == 0
    disp('Source folder selection cancelled. Script terminated.');
    return;
end

% --- Automatically create a subfolder for the images results ---
outputFolderDIR = fullfile(imageFolderDIR, 'annotated_results');
if ~exist(outputFolderDIR, 'dir')
    mkdir(outputFolderDIR);
end

% User-configurable settings
img_type = '.jpg';
output_json_filename = 'bubble_labeled_data.json';

% Get a list of all image files of the specified type in the folder
im_files = dir(fullfile(imageFolderDIR, ['*' img_type]));
if isempty(im_files)
    disp(['No images of type "' img_type '" found in the source folder.']);
    return;
end

% Initialize a master struct to store data for all images
allFramesData = struct;
disp(['Found ' num2str(length(im_files)) ' images to process.']);

%% --------------------- MAIN PROCESSING LOOP ---------------------
for j = 1:length(im_files)
    
    imageFileName = im_files(j).name;
    
    % Create a custom, MATLAB-compatible struct field name
    imageName = strrep(imageFileName, img_type, '');
    imageName = strrep(imageName, '.', 'd');
    imageName = strrep(imageName, '-', '');
    if isstrprop(imageName(1), 'digit')
        imageName = ['Image' imageName];
    end
    
    % Call the interactive drawing function for the current image
    [stop_processing, imageBubblesData] = drawROI(imageFolderDIR, imageFileName); 
    
    % Store the data for the current image in the master struct
    allFramesData.(imageName) = imageBubblesData;
    
    % --- NEW: Save the annotated image ---
    if ~isempty(fieldnames(imageBubblesData.Bubbles))
        % Load the original image again
        I = imread(fullfile(imageFolderDIR, imageFileName));
        % Create a new figure, but keep it invisible
        fig_to_save = figure('Visible', 'off');
        imshow(I);
        hold on;
        
        % Get the names of the bubbles to draw
        bubble_names = fieldnames(imageBubblesData.Bubbles);
        for i = 1:length(bubble_names)
            bubble_data = imageBubblesData.Bubbles.(bubble_names{i});
            plot(bubble_data.x_coordinate, bubble_data.y_coordinate, 'r--', 'LineWidth', 2);
        end
        hold off;
        
        % Save the figure to the selected output directory
        output_image_path = fullfile(outputFolderDIR, imageFileName);
        saveas(fig_to_save, output_image_path);
        close(fig_to_save); % Close the invisible figure
    end
    
    % Display progress to the user
    remaining = length(im_files) - j;
    disp(['Number of images remaining to process: ' num2str(remaining)])
    
    if stop_processing
        disp('User stopped the process.');
        break
    end
end

%% --------------------- EXPORT TO JSON FILE ---------------------
if ~isempty(fieldnames(allFramesData))
    jsonText = jsonencode(allFramesData, "PrettyPrint", true);
    
    promptMessage = 'Save the collected bubble data to a JSON file?';
    titleBarCaption = 'Export Data';
    button = questdlg(promptMessage, titleBarCaption, 'Save', 'Do Not Save', 'Save');
    
    if strcmpi(button, 'Save')
        % --- CHANGE: Save JSON to the selected output directory ---
        json_output_path = fullfile(outputFolderDIR, output_json_filename);
        fileID = fopen(json_output_path, 'w');
        fprintf(fileID, jsonText);
        fclose(fileID);
        disp(['Data successfully saved to: ' json_output_path]);
    else
        disp('Data not saved.');
    end
end

disp('Annotation process finished.');


%% #################### LOCAL FUNCTION: drawROI (Unchanged) ####################
function [stop_define, imageBubblesData] = drawROI(imageFolderDIR, imageFileName)
    
    stop_define = false;
    ImageFile = fullfile(imageFolderDIR, imageFileName);
    
    I = imread(ImageFile);
    if size(I, 3) == 3
        I = rgb2gray(I);
    end
    
    regionsOfInterests = struct;
    
    fig = figure(1);
    imshow(I);
    title({imageFileName, 'Left-click to draw; Keyboard backspace to undo a click point; Double-click to finish a bubble.'}, 'Interpreter', 'none');
    hold on;
    
    while true
        roi = drawpolygon('Color','g');
        
        xi = round(roi.Position(:,1));
        yi = round(roi.Position(:,2));
        
        plot(xi, yi, 'r--', 'LineWidth', 2);
        
        num_regions = length(fieldnames(regionsOfInterests)) + 1;
        bubble_name = ['b' sprintf('%04d', num_regions)];
        bubble_data = struct('x_coordinate', xi, 'y_coordinate', yi);
        regionsOfInterests.(bubble_name) = bubble_data;

        promptMessage = 'What to do next?';
        titleBarCaption = 'Action';
        choices = {'Define more', 'Redefine last bubble', 'Reset all', 'Next image', 'Stop defining'};
        
        [indx, tf] = listdlg('PromptString', promptMessage, ...
                           'SelectionMode', 'single', ...
                           'ListString', choices, ...
                           'Name', titleBarCaption, ...
                           'ListSize', [250, 120]);
        
        if ~tf
            choice = 'Next image';
        else
            choice = choices{indx};
        end
        
        switch choice
            case 'Define more'
                continue;
                
            case 'Redefine last bubble'
                disp('Removing the last drawn bubble.');
                bubble_names = fieldnames(regionsOfInterests);
                if ~isempty(bubble_names)
                    last_bubble_name = bubble_names{end};
                    regionsOfInterests = rmfield(regionsOfInterests, last_bubble_name);
                    cla;
                    imshow(I);
                    title({imageFileName, 'REDEFINE LAST: Left-click to draw, Double-click to finish.'}, 'Interpreter', 'none');
                    hold on;
                    remaining_bubble_names = fieldnames(regionsOfInterests);
                    for i = 1:length(remaining_bubble_names)
                        bubble_data = regionsOfInterests.(remaining_bubble_names{i});
                        plot(bubble_data.x_coordinate, bubble_data.y_coordinate, 'r--', 'LineWidth', 2);
                    end
                else
                    disp('No bubbles to redefine.');
                end
                continue;

            case 'Reset all'
                disp('Clearing all bubbles for this image. Please start again.');
                regionsOfInterests = struct;
                cla; 
                imshow(I);
                title({imageFileName, 'RESET: Left-click to draw, Double-click to finish.'}, 'Interpreter', 'none');
                continue;
                
            case 'Next image'
                break;
                
            case 'Stop defining'
                stop_define = true;
                break;
        end
    end
    
    close(fig);
    
    imageBubblesData = struct;
    imageBubblesData.FileName = imageFileName;
    imageBubblesData.Bubbles = regionsOfInterests;
end