function to save image into database with labels from images names in matlab

Here's a simple function that takes in a folder path with images and their corresponding labels in the file name, and saves them into a database.

main.m
function saveImagesToDB(folderPath, dbName, tableName)
% folderPath - Path to folder containing images
% dbName - Name of SQLite database to create
% tableName - Name of table to create in database

% create database connection
conn = sqlite(dbName);

% create table in database
sqlQuery = ['CREATE TABLE IF NOT EXISTS ' tableName ' (id INTEGER PRIMARY KEY AUTOINCREMENT, img BLOB, label TEXT);'];
exec(conn, sqlQuery);

% get list of image files in folder
imageFiles = dir(fullfile(folderPath, '*.png'));

% loop through files and insert into database
for i=1:numel(imageFiles)
    % load image and label from filename
    filePath = fullfile(imageFiles(i).folder, imageFiles(i).name);
    img = imread(filePath);
    [~, label, ~] = fileparts(imageFiles(i).name);
    
    % insert into database
    sqlQuery = ['INSERT INTO ' tableName ' (img, label) VALUES (?, ?)'];
    statement = conn.prepareStatement(sqlQuery);
    blob = java.sql.Blob(img(:));
    statement.setBlob(1, blob);
    statement.setString(2, label);
    statement.execute();
end

% close database connection
close(conn);
end
1096 chars
35 lines

Here's an example of how the function can be called:

main.m
folderPath = 'path/to/folder';
dbName = 'my_images.db';
tableName = 'my_image_table';

saveImagesToDB(folderPath, dbName, tableName);
134 chars
6 lines

This function creates a new SQLite database (dbName) if it doesn't already exist, creates a table (tableName) in the database if it doesn't exist, and inserts each image in the folder (folderPath) with its label (extracted from the filename) as a new row in the table. The image data is stored as a binary large object (BLOB) in the database.

gistlibby LogSnag