hanhuark's picture
Add files using upload-large-folder tool
b90e704 verified
Raw
History Blame Contribute Delete
8.77 kB
%% 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