| Title: | Standardized Processing and Analysis of Thermal Imaging Data in Animal Studies |
|---|---|
| Description: | A modular framework for standardized analysis of thermal imaging data in animal experimentation. The package integrates thermographic data import (FLIR, raw, CSV), automated region of interest (ROI) segmentation based on 'EBImage' (Pau et al., 2010 <doi:10.1093/bioinformatics/btq046>), interactive ROI refinement, and high-throughput batch processing. |
| Authors: | BeiHao Li [aut, cre] |
| Maintainer: | BeiHao Li <[email protected]> |
| License: | GPL (>= 3) |
| Version: | 0.1.1 |
| Built: | 2026-05-31 09:28:32 UTC |
| Source: | https://github.com/rightsz/biothermr |
Collapses technical replicates (e.g., multiple thermal images taken of the same animal) into a single biological data point per subject. This step is crucial for avoiding pseudoreplication in downstream statistical analyses (e.g., t-tests, ANOVA).
aggregate_replicates(data, id_col, method = "mean", keep_cols = NULL)aggregate_replicates(data, id_col, method = "mean", keep_cols = NULL)
data |
A data frame. Typically the output from |
id_col |
String. The column name representing the unique Biological Subject ID (e.g., "MouseID", "Subject_No"). Rows sharing this ID will be condensed into one. |
method |
String. The mathematical function used for aggregation: either |
keep_cols |
Vector of strings. Names of non-numeric metadata columns to preserve in the final output (e.g., "Group", "Genotype", "Sex", "Treatment"). |
A data frame with exactly one row per unique ID. The column order is reorganized to place
ID and metadata first, followed by the aggregated thermal statistics and the n_replicates count.
# Create a toy dataset with repeated measurements df_raw <- data.frame( SampleID = rep(paste0("M", 1:3), each = 3), Group = rep(c("ND", "HFD", "ND"), each = 3), Sex = rep("M", 9), Median = runif(9, 33, 36), IQR = runif(9, 0.5, 1.5) ) df <- aggregate_replicates( data = df_raw, id_col = "SampleID", method = "median", keep_cols = c("Group", "Sex") )# Create a toy dataset with repeated measurements df_raw <- data.frame( SampleID = rep(paste0("M", 1:3), each = 3), Group = rep(c("ND", "HFD", "ND"), each = 3), Sex = rep("M", 9), Median = runif(9, 33, 36), IQR = runif(9, 0.5, 1.5) ) df <- aggregate_replicates( data = df_raw, id_col = "SampleID", method = "median", keep_cols = c("Group", "Sex") )
Computes a detailed set of summary statistics from the thermal matrix. Metrics include ROI size (Pixels), central tendency (Mean, Median, Peak Density), dispersion (SD, IQR, CV), and range (Min, Max, Quantiles). NA values (background) are automatically excluded.
analyze_thermal_stats(img_obj, use_processed = TRUE)analyze_thermal_stats(img_obj, use_processed = TRUE)
img_obj |
A 'BioThermR' object. |
use_processed |
Logical. If |
The function calculates the following metrics:
Pixels: Number of valid non-NA pixels included in the analysis.
Min/Max: Extremities of the temperature distribution.
Mean/Median: Measures of central tendency.
SD (Standard Deviation): Absolute measure of spread.
Q25/Q75: The 25th and 75th percentiles of the temperature distribution.
IQR (Interquartile Range): Robust measure of spread (Q75 - Q25).
CV (Coefficient of Variation): Relative measure of spread (SD / Mean), useful for assessing thermal heterogeneity.
Peak_Density: The temperature value corresponding to the peak of the kernel density estimate.
A 'BioThermR' object with the stats slot updated containing a data frame of results.
img_obj <- system.file("extdata", "C05.raw", package = "BioThermR") img <- read_thermal_raw(img_obj) img <- analyze_thermal_stats(img)img_obj <- system.file("extdata", "C05.raw", package = "BioThermR") img <- read_thermal_raw(img_obj) img <- analyze_thermal_stats(img)
Extracts the thermal matrix (raw or processed) from a 'BioThermR' object and converts it into an 'EBImage' class object. This conversion is essential for applying advanced morphological operations (e.g., thresholding, watershed, labeling) provided by the 'EBImage' package.
as_EBImage(img_obj, use_processed = TRUE, replace_na = 0, normalize = FALSE)as_EBImage(img_obj, use_processed = TRUE, replace_na = 0, normalize = FALSE)
img_obj |
A 'BioThermR' object. |
use_processed |
Logical. If |
replace_na |
Numeric. The value to replace |
normalize |
Logical. If |
An Image object (defined in the 'EBImage' package).
# Load data mat <- matrix(runif(160*120, 20, 40), nrow = 120, ncol = 160) obj <- create_BioThermR(mat, name = "Simulation_01") # Convert to EBImage format with normalization (for thresholding) eb_norm <- as_EBImage(obj, normalize = TRUE) # Convert preserving temperature values (for calculation) eb_temp <- as_EBImage(obj, normalize = FALSE)# Load data mat <- matrix(runif(160*120, 20, 40), nrow = 120, ncol = 160) obj <- create_BioThermR(mat, name = "Simulation_01") # Convert to EBImage format with normalization (for thresholding) eb_norm <- as_EBImage(obj, normalize = TRUE) # Convert preserving temperature values (for calculation) eb_temp <- as_EBImage(obj, normalize = FALSE)
Evaluates the statistical consistency and reliability of repeated thermal measurements. The function calculates the Intraclass Correlation Coefficient (ICC) and performs variance decomposition using Linear Mixed Models (LMM) to assess the proportion of variance attributable to between-subject differences versus measurement error.
assess_replicates( data, id_col, metrics, replicate_col = NULL, sort_cols = NULL, methods = "icc", return_models = FALSE, quiet = FALSE )assess_replicates( data, id_col, metrics, replicate_col = NULL, sort_cols = NULL, methods = "icc", return_models = FALSE, quiet = FALSE )
data |
A data.frame containing the thermal metrics and identifier columns. |
id_col |
A single character string specifying the column name for subject IDs. |
metrics |
A character vector specifying the column names of the thermal metrics to be assessed. |
replicate_col |
A single character string specifying the column name for the replicate index. Default is |
sort_cols |
A character vector specifying the columns to sort the data by before inferring replicate indices. Default is |
methods |
A character vector specifying the statistical methods to apply. Valid options include |
return_models |
Logical. If |
quiet |
Logical. If |
This function requires the psych package for ICC calculations and the lme4 package for variance decomposition and LMM fitting. Ensure these packages are installed before selecting the respective methods.
An object of class BioThermR_replicate_assessment, which is a list containing:
settings |
A list of the input parameters used for the assessment. |
icc |
A data.frame containing ICC results (if |
variance |
A data.frame containing variance decomposition results (if |
lmm |
A data.frame containing fixed effects and variance components from LMM (if |
models |
A list of fitted |
## Not run: # Assuming df is a data.frame with columns: Sample, Rep, Mean res <- assess_replicates( data = df, id_col = "Sample", metrics = "Mean", replicate_col = "Rep", methods = c("icc", "variance") ) print(res$icc) ## End(Not run)## Not run: # Assuming df is a data.frame with columns: Sample, Rep, Mean res <- assess_replicates( data = df, id_col = "Sample", metrics = "Mean", replicate_col = "Rep", methods = c("icc", "variance") ) print(res$icc) ## End(Not run)
Iterates through a list of 'BioThermR' objects, extracts the pre-calculated statistics
(from analyze_thermal_stats), and aggregates them into a single summary data frame.
This function transforms the nested list structure into a flat, tabular format (Tidy Data)
suitable for downstream statistical analysis (ANOVA, t-test) or visualization.
compile_batch_stats(img_list)compile_batch_stats(img_list)
img_list |
A list of 'BioThermR' objects (typically the output of a batch processing workflow).
Note: |
A data.frame where:
Rows represent individual images.
Columns include 'Filename' and all metrics computed by analyze_thermal_stats
(e.g., Min, Max, Mean, Median, SD, IQR, CV, Peak_Density).
# 1. Import and Process img_obj_list <- system.file("extdata",package = "BioThermR") img_list <- read_thermal_batch(img_obj_list) img_list <- lapply(img_list, analyze_thermal_stats) # 2. Compile Results df_results <- compile_batch_stats(img_list)# 1. Import and Process img_obj_list <- system.file("extdata",package = "BioThermR") img_list <- read_thermal_batch(img_obj_list) img_list <- lapply(img_list, analyze_thermal_stats) # 2. Compile Results df_results <- compile_batch_stats(img_list)
Computes pairwise correlations between a set of thermal variables and a set of external variables. It handles missing data gracefully, performs multiple testing corrections, and returns detailed statistical summaries along with correlation and p-value matrices.
correlate_thermal_traits( data, thermal_vars, external_vars, method = "spearman", adjust_method = "BH", use = "complete.obs" )correlate_thermal_traits( data, thermal_vars, external_vars, method = "spearman", adjust_method = "BH", use = "complete.obs" )
data |
A 'data.frame' containing the variables to be analyzed. |
thermal_vars |
A character vector specifying the column names of the thermal variables in 'data'. |
external_vars |
A character vector specifying the column names of the external variables in 'data'. |
method |
A character string indicating which correlation coefficient to compute. Can be either '"spearman"' (default) or '"pearson"'. |
adjust_method |
A character string specifying the method for multiple testing correction. Options are '"holm"', '"hochberg"', '"hommel"', '"bonferroni"', '"BH"' (default), '"BY"', '"fdr"', or '"none"'. |
use |
A character string indicating how to handle missing values. Can be '"complete.obs"' (default, uses only rows with complete data across all selected variables) or '"pairwise.complete.obs"' (uses complete cases on a pair-by-pair basis). |
A list containing the following elements:
A data frame with detailed pairwise statistics including variable names, sample size ('n'), correlation coefficient ('cor'), raw p-value ('p'), adjusted p-value ('p_adj'), direction, significance label, and any warnings.
A numeric matrix of the calculated correlation coefficients.
A numeric matrix of the raw p-values.
A numeric matrix of the adjusted p-values.
The correlation method used.
The p-value adjustment method used.
The missing data handling method used.
A descriptive note regarding how missing data was actually handled.
set.seed(1234) df <- data.frame( Max = rnorm(50, 35, 2), Min = rnorm(50, 15, 3), Weight = rnorm(50, 20, 5), Glu = runif(50, 5, 8) ) # Introduce a few NA values to test missing data handling df$Weight[c(2, 10)] <- NA # Run the correlation analysis res <- correlate_thermal_traits( data = df, thermal_vars = c("Max", "Min"), external_vars = c("Weight", "Glu"), method = "spearman", adjust_method = "BH", use = "pairwise.complete.obs" ) # View the detailed results data frame head(res$results) # View the correlation matrix print(res$cor_matrix)set.seed(1234) df <- data.frame( Max = rnorm(50, 35, 2), Min = rnorm(50, 15, 3), Weight = rnorm(50, 20, 5), Glu = runif(50, 5, 8) ) # Introduce a few NA values to test missing data handling df$Weight[c(2, 10)] <- NA # Run the correlation analysis res <- correlate_thermal_traits( data = df, thermal_vars = c("Max", "Min"), external_vars = c("Weight", "Glu"), method = "spearman", adjust_method = "BH", use = "pairwise.complete.obs" ) # View the detailed results data frame head(res$results) # View the correlation matrix print(res$cor_matrix)
Manually creates a BioThermR object from a numeric matrix or data frame. Useful for converting data loaded from other formats (Excel, CSV, txt) or simulation data.
create_BioThermR(data, name = "Sample")create_BioThermR(data, name = "Sample")
data |
A numeric matrix or data frame representing the thermal image grid (rows x cols). |
name |
String. An identifier for this sample (e.g., filename or sample ID). Default is "Sample". |
A 'BioThermR' object.
mat <- matrix(runif(160*120, 20, 40), nrow = 120, ncol = 160) obj <- create_BioThermR(mat, name = "Simulation_01") plot_thermal_heatmap(obj)mat <- matrix(runif(160*120, 20, 40), nrow = 120, ncol = 160) obj <- create_BioThermR(mat, name = "Simulation_01") plot_thermal_heatmap(obj)
Converts an 'EBImage' class object back into the 'BioThermR' framework. This function is designed to integrate results from external morphological operations (e.g., watershed segmentation, filtering) back into the standard BioThermR analytical workflow.
from_EBImage( eb_img, template_obj = NULL, name = "Imported_EBImage", mask_zero = FALSE )from_EBImage( eb_img, template_obj = NULL, name = "Imported_EBImage", mask_zero = FALSE )
eb_img |
An |
template_obj |
Optional. An existing 'BioThermR' object to update.
Providing this ensures that original metadata (like filenames and original raw data)
is retained. Default is |
name |
String. The name assigned to the new object (used only if |
mask_zero |
Logical. If |
This function supports two modes:
Update Mode: If template_obj is provided, the input image replaces
the processed matrix of the template. Metadata (filename, path) is preserved.
Statistics are reset to NULL as the data has changed.
Create Mode: If template_obj is NULL, a new 'BioThermR' object is created
from scratch using the input matrix.
If the input eb_img has more than 2 dimensions (e.g., color/RGB), only the first channel
is utilized, and a warning is issued.
A 'BioThermR' object with the imported matrix stored in the processed slot.
# Load data mat <- matrix(runif(160*120, 20, 40), nrow = 120, ncol = 160) obj <- create_BioThermR(mat, name = "Simulation_01") # Convert to EBImage format with normalization eb_obj <- as_EBImage(obj, normalize = TRUE) # Convert to BioThermR from EBImage new_obj <- from_EBImage(eb_obj)# Load data mat <- matrix(runif(160*120, 20, 40), nrow = 120, ncol = 160) obj <- create_BioThermR(mat, name = "Simulation_01") # Convert to EBImage format with normalization eb_obj <- as_EBImage(obj, normalize = TRUE) # Convert to BioThermR from EBImage new_obj <- from_EBImage(eb_obj)
Restores a previously saved 'BioThermR' object or a list of objects from a .rds file.
This function is the counterpart to save_biothermr and allows you to
resume analysis from a saved checkpoint.
load_biothermr(file_path)load_biothermr(file_path)
file_path |
String. The full path to the .rds file (e.g., "results/experiment_data.rds"). |
Upon loading, the function performs an automatic validation check to ensure the file contains a valid 'BioThermR' class instance (or a list of them). It provides feedback to the console regarding the type and quantity of objects loaded.
A single 'BioThermR' object or a list of 'BioThermR' objects, depending on the structure of the saved data.
Merges the compiled thermal statistics with an external clinical dataset based on filenames/IDs. Automatically handles column name conflicts (removes .x/.y suffixes).
merge_clinical_data( thermal_df, clinical_df, thermal_id = "Filename", clinical_id = "Filename", clean_ids = TRUE )merge_clinical_data( thermal_df, clinical_df, thermal_id = "Filename", clinical_id = "Filename", clean_ids = TRUE )
thermal_df |
Data frame. The output from compile_batch_stats(). |
clinical_df |
Data frame. Your external clinical data. |
thermal_id |
String. Column name in thermal_df to merge on. Default is "Filename". |
clinical_id |
String. Column name in clinical_df to merge on. Default is "Filename". |
clean_ids |
Logical. If TRUE, automatically removes file paths and extensions for matching. Default is TRUE. |
A merged data frame.
Visually compares two segmentation masks (ROIs) by overlaying them on the original thermal image. This function is primarily used for validation purposes: to compare an automated segmentation (filled layer) against a manual ground truth (contour line). It automatically calculates and displays the Dice Similarity Coefficient (DSC) in the title.
plot_roi_overlap( img_obj1, img_obj2, title = NULL, color = "green", alpha = 0.5, line_color = "white", palette = "inferno" )plot_roi_overlap( img_obj1, img_obj2, title = NULL, color = "green", alpha = 0.5, line_color = "white", palette = "inferno" )
img_obj1 |
A 'BioThermR' object. Typically the Automated/Predicted segmentation. This object must contain the raw thermal matrix. Its mask will be plotted as a filled area. |
img_obj2 |
A 'BioThermR' object. Typically the Manual/Ground Truth segmentation.
Its mask will be plotted as a contour outline. Dimensions must match |
title |
String. Custom title for the plot. If |
color |
String. Fill color for the |
alpha |
Numeric. Transparency level for the |
line_color |
String. Line color for the |
palette |
String. Color palette for the background thermal image (passed to |
The visualization consists of three layers:
Background: The raw thermal image from img_obj1.
Prediction (img_obj1): The processed mask from the first object, rendered as a semi-transparent filled raster (default green).
Ground Truth (img_obj2): The processed mask from the second object, rendered as a contour outline (default white).
The function calculates the Dice Similarity Coefficient (DSC) using the formula:
where X and Y are the set of pixels in the two masks. A DSC of 1 indicates perfect overlap.
A ggplot object showing the overlay.
#' # Load raw data img_obj <- system.file("extdata", "C05.raw", package = "BioThermR") img <- read_thermal_raw(img_obj) # Apply automated segmentation img1 <- roi_segment_ebimage(img, keep_largest = TRUE) # Simple background removal: Keep everything above 24 degrees img2 <- roi_filter_threshold(img, threshold = c(33, Inf)) # Compare them plot_roi_overlap(img_obj1 = img1, img_obj2 = img2)#' # Load raw data img_obj <- system.file("extdata", "C05.raw", package = "BioThermR") img <- read_thermal_raw(img_obj) # Apply automated segmentation img1 <- roi_segment_ebimage(img, keep_largest = TRUE) # Simple background removal: Keep everything above 24 degrees img2 <- roi_filter_threshold(img, threshold = c(33, Inf)) # Compare them plot_roi_overlap(img_obj1 = img1, img_obj2 = img2)
Generates a rotatable, interactive 3D surface plot using the 'plotly' engine. This visualization maps temperature to the Z-axis, allowing users to intuitively explore the thermal topology, gradients, and intensity of hotspots.
plot_thermal_3d(img_obj, use_processed = TRUE)plot_thermal_3d(img_obj, use_processed = TRUE)
img_obj |
A 'BioThermR' object. |
use_processed |
Logical. If |
3D visualization is particularly powerful for:
Quality Control: Quickly identifying noise spikes or "cold" artifacts that flat heatmaps might hide.
Gradient Analysis: Visualizing how heat dissipates from a central source (e.g., a tumor or inflammation site).
Presentation: Creating engaging, interactive figures for HTML reports or Shiny dashboards.
The output is an HTML widget that allows zooming, panning, and hovering to see specific pixel values.
A plotly object (HTML widget).
# Load raw data img_obj <- system.file("extdata", "C05.raw", package = "BioThermR") img <- read_thermal_raw(img_obj) # Apply automated segmentation img <- roi_segment_ebimage(img, keep_largest = TRUE) # 3d plot plot_thermal_3d(img)# Load raw data img_obj <- system.file("extdata", "C05.raw", package = "BioThermR") img <- read_thermal_raw(img_obj) # Apply automated segmentation img <- roi_segment_ebimage(img, keep_largest = TRUE) # 3d plot plot_thermal_3d(img)
Arranges a collection of segmented thermal objects into an organic, spiral "cloud" formation. Unlike a rigid grid, this layout uses a golden-angle spiral (phyllotaxis) algorithm to cluster subjects efficiently. This is particularly effective for visualizing the diversity of thermal phenotypes in large datasets or creating artistic figures for presentations and covers.
plot_thermal_cloud( img_list, spread_factor = 1.1, jitter_factor = 0.5, palette = "inferno", text_color = "black", text_size = 3, show_labels = TRUE )plot_thermal_cloud( img_list, spread_factor = 1.1, jitter_factor = 0.5, palette = "inferno", text_color = "black", text_size = 3, show_labels = TRUE )
img_list |
A list of 'BioThermR' objects. For best results, these should be pre-processed
(e.g., background removed via |
spread_factor |
Numeric. Multiplier for the distance between objects. Values > 1.0 increase spacing (airier cloud), values < 1.0 pack objects tighter. Default is 1.1. |
jitter_factor |
Numeric. Introduces random noise to the placement coordinates to break perfect symmetry and create a more natural look. Default is 0.5. |
palette |
String. The color palette from the 'viridis' package. Default is "inferno". |
text_color |
String. Color of the filename labels. Default is "black". |
text_size |
Integer. Font size for the labels. Default is 3. |
show_labels |
Logical. If |
The function performs object-centric rendering:
Extraction: For each image, it extracts only the valid foreground pixels (non-NA), ignoring the original frame dimensions.
Re-centering: Each object is mathematically centered at (0,0) relative to its own coordinate system.
Placement: Objects are placed along a spiral path defined by the Golden Angle (~137.5 degrees).
The spacing and randomness of the spiral can be tuned using spread_factor and jitter_factor.
A ggplot object with a white background and void theme.
# Load a batch of images img_obj_list <- system.file("extdata",package = "BioThermR") batch <- read_thermal_batch(img_obj_list) batch <- lapply(batch, roi_segment_ebimage) # Create an artistic thermal cloud p_cloud <- plot_thermal_cloud(batch, spread_factor = 1.5, jitter_factor = 2.0)# Load a batch of images img_obj_list <- system.file("extdata",package = "BioThermR") batch <- read_thermal_batch(img_obj_list) batch <- lapply(batch, roi_segment_ebimage) # Create an artistic thermal cloud p_cloud <- plot_thermal_cloud(batch, spread_factor = 1.5, jitter_factor = 2.0)
Generates a probability density plot of the temperature values within the image. This visualization is critical for assessing the homogeneity of the subject's temperature and identifying potential artifacts (e.g., bimodal distributions often indicate poor background removal).
plot_thermal_density( img_obj, use_processed = TRUE, show_peak = TRUE, show_max = TRUE, show_min = TRUE, digits = 2, color = "skyblue", point_size = 2, point_color = "red", point_label_color = "black", point_label_size = 2 )plot_thermal_density( img_obj, use_processed = TRUE, show_peak = TRUE, show_max = TRUE, show_min = TRUE, digits = 2, color = "skyblue", point_size = 2, point_color = "red", point_label_color = "black", point_label_size = 2 )
img_obj |
A 'BioThermR' object. |
use_processed |
Logical. If |
show_peak |
Logical. If |
show_max |
Logical. If |
show_min |
Logical. If |
digits |
Integer. Number of decimal places to round the labels to. Default is 2. |
color |
String. Fill color for the density area curve. Default is "skyblue". |
point_size |
Numeric. Size of the points marking Peak/Min/Max. Default is 2. |
point_color |
String. Color of the points marking Peak/Min/Max. Default is "red". |
point_label_color |
String. Color of the text labels. Default is "black". |
point_label_size |
Numeric. Size of the text labels. Default is 2. |
The function computes the kernel density estimate of the valid pixels (ignoring NAs). It can optionally annotate key statistical landmarks:
Peak: The mode of the distribution (most frequent temperature).
Max/Min: The hottest and coldest points in the ROI.
Text labels are automatically repelled using 'ggrepel' to ensure they do not overlap.
A ggplot object. Layers can be added subsequently.
# Load raw data img_obj <- system.file("extdata", "C05.raw", package = "BioThermR") img <- read_thermal_raw(img_obj) # Apply automated segmentation img <- roi_segment_ebimage(img, keep_largest = TRUE) # Density plot plot_thermal_density(img)# Load raw data img_obj <- system.file("extdata", "C05.raw", package = "BioThermR") img <- read_thermal_raw(img_obj) # Apply automated segmentation img <- roi_segment_ebimage(img, keep_largest = TRUE) # Density plot plot_thermal_density(img)
Generates a high-quality raster plot of the thermal data using the 'ggplot2' framework. This function allows for quick visualization of raw or processed matrices with customizable perceptually uniform color scales (viridis).
plot_thermal_heatmap(img_obj, use_processed = TRUE, palette = "inferno")plot_thermal_heatmap(img_obj, use_processed = TRUE, palette = "inferno")
img_obj |
A 'BioThermR' object. |
use_processed |
Logical. If |
palette |
String. The color map option from the 'viridis' package.
Options include: |
The function performs the following steps:
Converts the thermal matrix into a long-format data frame suitable for ggplot.
Renders the image using geom_raster.
Maps temperature to color using the specified 'viridis' palette.
Ensures the aspect ratio is preserved (coord_fixed) so the image does not appear distorted.
Sets NA values (masked background) to transparent.
Since the output is a standard ggplot object, layers can be added subsequently (e.g., new titles or annotations).
A ggplot object.
# Load raw data img_obj <- system.file("extdata", "C05.raw", package = "BioThermR") img <- read_thermal_raw(img_obj) # Apply automated segmentation img <- roi_segment_ebimage(img, keep_largest = TRUE) # Standard plot plot_thermal_heatmap(img)# Load raw data img_obj <- system.file("extdata", "C05.raw", package = "BioThermR") img <- read_thermal_raw(img_obj) # Apply automated segmentation img <- roi_segment_ebimage(img, keep_largest = TRUE) # Standard plot plot_thermal_heatmap(img)
Combines a list of 'BioThermR' objects into a single, high-resolution grid plot (montage). Unlike standard faceting, this function uses a custom integer-coordinate system to center each subject within a uniform grid cell, ensuring pixel-perfect alignment without the visual artifacts (white gaps) often seen in R raster plots.
plot_thermal_montage( img_list, ncol = NULL, padding = 10, palette = "inferno", text_color = "black", text_size = 4 )plot_thermal_montage( img_list, ncol = NULL, padding = 10, palette = "inferno", text_color = "black", text_size = 4 )
img_list |
A list of 'BioThermR' objects (e.g., output from |
ncol |
Integer. The number of columns in the grid. If |
padding |
Integer. The size of the whitespace gap (in pixels) between grid cells. Default is 10. |
palette |
String. The color palette to use (from 'viridis' package). Default is "inferno". |
text_color |
String. Color of the filename labels. Default is "black". |
text_size |
Integer. Font size for the filename labels. Default is 4. |
The function executes a two-pass algorithm:
Scan Pass: Iterates through all objects to calculate the bounding box dimensions of the largest subject. This defines the uniform cell size for the grid.
Layout Pass: Calculates the integer offsets required to center each smaller subject within the master cell. It merges all pixel data into a single master data frame.
The result is rendered using geom_tile(width=1, height=1) to guarantee continuous, gap-free visualization.
A ggplot object representing the combined montage.
# Load a batch of images img_obj_list <- system.file("extdata",package = "BioThermR") batch <- read_thermal_batch(img_obj_list) # Create a montage with 4 columns p <- plot_thermal_montage(batch, ncol = 4, padding = 20)# Load a batch of images img_obj_list <- system.file("extdata",package = "BioThermR") batch <- read_thermal_batch(img_obj_list) # Create a montage with 4 columns p <- plot_thermal_montage(batch, ncol = 4, padding = 20)
Scans a folder and imports all matching .raw files into a list.
read_thermal_batch(folder_path, pattern = "\\.raw$", recursive = FALSE, ...)read_thermal_batch(folder_path, pattern = "\\.raw$", recursive = FALSE, ...)
folder_path |
String. Path to the folder. |
pattern |
String. Regex pattern. Default is "\.raw$". |
recursive |
Logical. Default is FALSE. |
... |
Additional arguments passed to |
A named list of "BioThermR" objects.
# Example using raw thermal files img_obj_list <- system.file("extdata",package = "BioThermR") img_list <- read_thermal_batch(img_obj_list)# Example using raw thermal files img_obj_list <- system.file("extdata",package = "BioThermR") img_list <- read_thermal_batch(img_obj_list)
Reads a FLIR radiometric JPG file, parses the embedded metadata (emissivity, distance, Planck constants, atmospheric parameters), converts the raw sensor data to temperature (Celsius), and constructs a 'BioThermR' object.
read_thermal_flir(file_path, exiftoolpath = "installed")read_thermal_flir(file_path, exiftoolpath = "installed")
file_path |
String. The full path to the FLIR radiometric .jpg file. |
exiftoolpath |
String. Path to the ExifTool executable. Default is "installed" (assumes it is available in the system PATH). |
This function relies on the 'Thermimage' package and the external tool 'ExifTool'. It automatically extracts calibration constants (Planck R1, B, F, O, R2) and environmental parameters to ensure accurate physical temperature conversion. Please ensure 'ExifTool' is installed and added to your system PATH.
A list object of class "BioThermR" containing:
raw |
The calculated temperature matrix in degrees Celsius. |
processed |
A copy of the raw matrix, intended for subsequent ROI filtering or masking. |
meta |
A list containing metadata: |
# Example using a flir thermal file img_obj <- system.file("extdata", "IR_2412.jpg", package = "Thermimage") img <- read_thermal_flir(img_obj)# Example using a flir thermal file img_obj <- system.file("extdata", "IR_2412.jpg", package = "Thermimage") img <- read_thermal_flir(img_obj)
Reads a binary .raw file (typically 32-bit floating point), converts it into a matrix, and constructs a 'BioThermR' object containing raw data and metadata.
read_thermal_raw(file_path, width = 160, height = 120, rotate = TRUE)read_thermal_raw(file_path, width = 160, height = 120, rotate = TRUE)
file_path |
String. The full path to the .raw file. |
width |
Integer. The width of the thermal sensor (number of columns). Default is 160. |
height |
Integer. The height of the thermal sensor (number of rows). Default is 120. |
rotate |
Logical. Whether to rotate the image 90 degrees counter-clockwise. Default is TRUE (corrects orientation for many standard sensor exports). |
A list object of class "BioThermR" containing:
raw |
The original temperature matrix (numeric). |
processed |
A copy of the raw matrix, intended for subsequent ROI filtering or masking. |
meta |
A list containing metadata: |
img_obj <- system.file("extdata", "C05.raw", package = "BioThermR") img <- read_thermal_raw(img_obj)img_obj <- system.file("extdata", "C05.raw", package = "BioThermR") img <- read_thermal_raw(img_obj)
Launches a Shiny GUI application that allows users to interactively refine regions of interest (ROI) for a batch of thermal images. Key features include dynamic temperature thresholding and an automated "Clean Noise" tool that removes artifacts by retaining only the largest connected object (e.g., the mouse).
roi_filter_interactive(img_input, start_index = 1, use_processed = TRUE)roi_filter_interactive(img_input, start_index = 1, use_processed = TRUE)
img_input |
A single 'BioThermR' object OR a list of 'BioThermR' objects (e.g., from |
start_index |
Integer. The index of the image to start viewing. Default is 1. Useful for resuming work on a large batch. |
use_processed |
Logical. If |
This function opens a local web server (Shiny App). The workflow is as follows:
Navigate: Use "Prev/Next" buttons to browse the image batch.
Threshold: Adjust the slider to set the min/max temperature range. Real-time feedback is shown on the plot.
Denoise: Toggle the "Remove Noise" button. This applies a topological filter (Connected Component Analysis) that identifies the largest contiguous heat source and removes all smaller isolated islands (e.g., urine spots, reflections).
Confirm: Click "Confirm" to lock in the settings for the current image and auto-advance.
Export: Click "Finish & Export Data" to close the app and return the processed object list to the R console.
The modified 'BioThermR' object (or list of objects). Note: You must assign the result
of this function to a variable (e.g., data <- roi_filter_interactive(data)) to save the changes.
Masks the thermal image by retaining only pixels that fall within a specified
temperature window. Pixels outside this range are set to NA (background).
roi_filter_threshold(img_obj, threshold, use_processed = FALSE)roi_filter_threshold(img_obj, threshold, use_processed = FALSE)
img_obj |
A 'BioThermR' object. |
threshold |
Numeric vector of length 2, e.g., |
use_processed |
Logical.
|
This is the most fundamental segmentation method for thermal images.
Since animals are typically warmer than their environment, a simple low-pass filter
(e.g., keep > 22 degrees Celsius) is often sufficient to separate the subject from the cage.
Open boundaries can be defined using Inf or -Inf.
A 'BioThermR' object with the processed matrix updated.
# Load raw data img_obj <- system.file("extdata", "C05.raw", package = "BioThermR") img <- read_thermal_raw(img_obj) # Simple background removal: Keep everything above 24 degrees img <- roi_filter_threshold(img, threshold = c(24, Inf))# Load raw data img_obj <- system.file("extdata", "C05.raw", package = "BioThermR") img <- read_thermal_raw(img_obj) # Simple background removal: Keep everything above 24 degrees img <- roi_filter_threshold(img, threshold = c(24, Inf))
Performs automated background removal using a hybrid pipeline of global thresholding (Otsu's method), morphological operations, and connected component analysis.
roi_segment_ebimage( img_obj, method = "otsu", keep_largest = TRUE, morphology = TRUE )roi_segment_ebimage( img_obj, method = "otsu", keep_largest = TRUE, morphology = TRUE )
img_obj |
A 'BioThermR' object. |
method |
String. The thresholding algorithm. Currently, only |
keep_largest |
Logical. If |
morphology |
Logical. If |
The segmentation pipeline consists of four steps:
Normalization: The temperature matrix is scaled to [0, 1] to be compatible with 'EBImage'.
Thresholding: Otsu's method is used to calculate an optimal global threshold that separates the foreground (subject) from the background based on histogram bimodality.
Morphology: A disc-shaped brush (size=5) is used for 'Opening' (to remove salt noise) and 'Closing' (to fill small holes inside the subject).
Component Filter: If keep_largest is TRUE, the function labels all
connected regions and retains only the largest one (assuming the animal is the largest heat source),
effectively removing smaller artifacts like bedding noise or reflections.
A 'BioThermR' object where the processed matrix has been masked
(background pixels are set to NA).
# Load raw data img_obj <- system.file("extdata", "C05.raw", package = "BioThermR") img <- read_thermal_raw(img_obj) # Apply automated segmentation img <- roi_segment_ebimage(img, keep_largest = TRUE)# Load raw data img_obj <- system.file("extdata", "C05.raw", package = "BioThermR") img <- read_thermal_raw(img_obj) # Apply automated segmentation img <- roi_segment_ebimage(img, keep_largest = TRUE)
Serializes and saves a single 'BioThermR' object or a list of objects to a compressed .rds file. This ensures that all components—raw temperature matrices, processed masks, metadata, and calculation stats—are preserved accurately.
save_biothermr(img_input, file_path)save_biothermr(img_input, file_path)
img_input |
A single 'BioThermR' class object or a list of 'BioThermR' objects
(e.g., the output from |
file_path |
String. The destination path (e.g., "results/obj.rds"). If the directory structure does not exist, it will be created automatically. |
None (invisible NULL). Prints a success message to the console upon completion.
# Load data mat <- matrix(runif(160*120, 20, 40), nrow = 120, ncol = 160) obj <- create_BioThermR(mat, name = "Simulation_01") # Save a single object to a temporary directory out_file <- file.path(tempdir(), "mouse_01.rds") save_biothermr(obj, out_file)# Load data mat <- matrix(runif(160*120, 20, 40), nrow = 120, ncol = 160) obj <- create_BioThermR(mat, name = "Simulation_01") # Save a single object to a temporary directory out_file <- file.path(tempdir(), "mouse_01.rds") save_biothermr(obj, out_file)
Generates a publication-ready correlation heatmap from the results of thermal and external trait correlation analysis. The plot features customizable color gradients, adjustable significance labels, and a clean, fixed-aspect-ratio layout suitable for academic reporting.
viz_cor_heatmap( cor_result, use_adjusted = TRUE, show_significance = TRUE, sig_levels = c(0.05, 0.01, 0.001), sig_ns_label = "", low = "#346888", mid = "#FFFFFF", high = "#D56B4A", midpoint = 0, limits = c(-1, 1), tile_color = "white", tile_size = 0.4, rotate_x = 45, text_size = 4, na_fill = "grey95" )viz_cor_heatmap( cor_result, use_adjusted = TRUE, show_significance = TRUE, sig_levels = c(0.05, 0.01, 0.001), sig_ns_label = "", low = "#346888", mid = "#FFFFFF", high = "#D56B4A", midpoint = 0, limits = c(-1, 1), tile_color = "white", tile_size = 0.4, rotate_x = 45, text_size = 4, na_fill = "grey95" )
cor_result |
A 'thermal_correlation_result' object or a 'data.frame' containing the correlation results. Must contain at least 'thermal_var', 'external_var', and 'cor' columns. |
use_adjusted |
A logical value indicating whether to use adjusted p-values ('p_adj') for generating significance labels. Defaults to 'TRUE'. |
show_significance |
A logical value indicating whether to overlay significance stars (*, **, ***) on the heatmap tiles. Defaults to 'TRUE'. |
sig_levels |
A numeric vector of length 3 defining the p-value thresholds for *, **, and *** significance labels, respectively. Defaults to 'c(0.05, 0.01, 0.001)'. |
sig_ns_label |
A character string to display when the correlation is not statistically significant. Defaults to '""' (empty string). |
low |
A character string specifying the color for strong negative correlations. Defaults to '"#346888"' (dark blue). |
mid |
A character string specifying the color for zero correlation. Defaults to '"#FFFFFF"' (white). |
high |
A character string specifying the color for strong positive correlations. Defaults to '"#D56B4A"' (dark orange). |
midpoint |
A numeric value specifying the midpoint for the color gradient. Defaults to 0. |
limits |
A numeric vector of length 2 defining the scale limits of the correlation coefficient. Defaults to 'c(-1, 1)'. |
tile_color |
A character string specifying the border color of the individual tiles. Defaults to '"white"'. |
tile_size |
A numeric value defining the border thickness of the tiles. Defaults to 0.4. |
rotate_x |
A numeric value indicating the rotation angle for the x-axis text labels. Defaults to 45. |
text_size |
A numeric value specifying the font size of the significance text labels. Defaults to 4. |
na_fill |
A character string specifying the fill color for missing (NA) correlation values. Defaults to '"grey95"'. |
A 'ggplot' object representing the correlation heatmap.
# Generate a dummy dataset representing correlation results df_res <- data.frame( thermal_var = rep(c("Max", "Min"), each = 3), external_var = rep(c("Weight", "Glucose", "Survival"), times = 2), cor = c(0.85, -0.42, 0.2, -0.96, 0.95, 0.05), p_adj = c(0.0005, 0.02, 0.5, 0.008, 0.04, 0.8) ) # Render the heatmap viz_cor_heatmap( cor_result = df_res, use_adjusted = TRUE, show_significance = TRUE, rotate_x = 45 )# Generate a dummy dataset representing correlation results df_res <- data.frame( thermal_var = rep(c("Max", "Min"), each = 3), external_var = rep(c("Weight", "Glucose", "Survival"), times = 2), cor = c(0.85, -0.42, 0.2, -0.96, 0.95, 0.05), p_adj = c(0.0005, 0.02, 0.5, 0.008, 0.04, 0.8) ) # Render the heatmap viz_cor_heatmap( cor_result = df_res, use_adjusted = TRUE, show_significance = TRUE, rotate_x = 45 )
Generates a customizable scatter plot integrated with a fitted linear regression line, confidence intervals, and correlation statistics (such as R and p-value). It supports optional grouping for stratified analysis.
viz_cor_scatter( data, x_col, y_col, group_col = NULL, point_shape = 21, point_fill = "#E8B671", point_color = "black", point_size = 3.5, point_alpha = 0.8, smooth_alpha = 0.3, smooth_linetype = 2, smooth_size = 1, cor_method = "spearman", cor_pos = "top_left", cor_size = 3, x_label = NULL, y_label = NULL, title = NULL )viz_cor_scatter( data, x_col, y_col, group_col = NULL, point_shape = 21, point_fill = "#E8B671", point_color = "black", point_size = 3.5, point_alpha = 0.8, smooth_alpha = 0.3, smooth_linetype = 2, smooth_size = 1, cor_method = "spearman", cor_pos = "top_left", cor_size = 3, x_label = NULL, y_label = NULL, title = NULL )
data |
A data.frame containing the variables to be plotted. |
x_col |
A character string specifying the column name for the x-axis. |
y_col |
A character string specifying the column name for the y-axis. |
group_col |
A character string specifying the grouping variable. Default is NULL. |
point_shape |
A numeric value defining the shape of the scatter points. Default is 21. |
point_fill |
A character string defining the fill color of the points. Default is "#E8B671". |
point_color |
A character string defining the border color of the points. Default is "black". |
point_size |
A numeric value defining the size of the points. Default is 3.5. |
point_alpha |
A numeric value defining the transparency of the points. Default is 0.8. |
smooth_alpha |
A numeric value defining the transparency of the confidence interval band. Default is 0.3. |
smooth_linetype |
A numeric value defining the line type of the regression line. Default is 2. |
smooth_size |
A numeric value defining the width of the regression line. Default is 1. |
cor_method |
A character string specifying the correlation coefficient method ("pearson", "kendall", or "spearman"). Default is "spearman". |
cor_pos |
A character string specifying the position of the correlation labels ("top_left", "top_right", "bottom_left", "bottom_right"). Default is "top_left". |
cor_size |
A numeric value defining the size of the correlation text. Default is 3. |
x_label |
A character string for custom x-axis label. If NULL, x_col is used. Default is NULL. |
y_label |
A character string for custom y-axis label. If NULL, y_col is used. Default is NULL. |
title |
A character string for the plot title. Default is NULL. |
A ggplot object representing the correlation scatter plot.
# Generate a dummy dataset set.seed(123) data <- data.frame( Weight = rnorm(50, mean = 25, sd = 10), Mean = rnorm(50, mean = 30, sd = 5) ) # Create the correlation scatter plot viz_cor_scatter( data = data, x_col = "Weight", y_col = "Mean", x_label = "Body Weight (g)", y_label = "Thermal Metric: Mean", title = "Correlation Analysis Example" )# Generate a dummy dataset set.seed(123) data <- data.frame( Weight = rnorm(50, mean = 25, sd = 10), Mean = rnorm(50, mean = 30, sd = 5) ) # Create the correlation scatter plot viz_cor_scatter( data = data, x_col = "Weight", y_col = "Mean", x_label = "Body Weight (g)", y_label = "Thermal Metric: Mean", title = "Correlation Analysis Example" )
Creates a high-quality bar plot to compare thermal metrics across experimental groups. The visualization includes bars representing the mean, customizable error bars (SD or SE), and overlaid individual data points to show biological variation.
viz_thermal_barplot( data, y_var, x_var, fill_var = NULL, error_bar = "mean_sd", add_points = TRUE, point_size = 1.5, point_alpha = 0.6, palette = "npg" )viz_thermal_barplot( data, y_var, x_var, fill_var = NULL, error_bar = "mean_sd", add_points = TRUE, point_size = 1.5, point_alpha = 0.6, palette = "npg" )
data |
Data frame. The merged dataset (e.g., output from |
y_var |
String. The name of the numeric column to plot (e.g., "Max_Temp", "Mean_Temp"). |
x_var |
String. The name of the categorical column for the X-axis groupings (e.g., "Treatment", "Genotype"). |
fill_var |
String. The name of the variable used for fill colors. Default is |
error_bar |
String. The type of error bar to display. Options:
|
add_points |
Logical. If |
point_size |
Numeric. The size of the individual jitter points. Default is 1.5. |
point_alpha |
Numeric. The transparency of the jitter points (0 = transparent, 1 = opaque). Default is 0.6 to handle overlapping points. |
palette |
String or Vector.
|
This function is designed to produce figures that are immediately suitable for scientific manuscripts. Key features include:
Automatic Statistics: Calculates Mean and SD/SE internally using stat_summary.
Smart Coloring: Supports scientific palettes ("npg", "jco"). If the number of groups exceeds the palette size, it automatically interpolates to generate distinct colors.
Layout: Uses theme_classic() and automatically expands the Y-axis limit
by 15% to ensure error bars and significance annotations fit comfortably.
A ggplot object. Can be further customized with standard ggplot2 functions.
df_bio <- data.frame( Treatment = rep(c("ND", "HFD"), each = 5), Mean = c(runif(5, 33, 35), runif(5, 34, 36)) ) # Boxplot with individual points p <- viz_thermal_barplot(df_bio,y_var="Mean",x_var="Treatment",error_bar = "mean_se") pdf_bio <- data.frame( Treatment = rep(c("ND", "HFD"), each = 5), Mean = c(runif(5, 33, 35), runif(5, 34, 36)) ) # Boxplot with individual points p <- viz_thermal_barplot(df_bio,y_var="Mean",x_var="Treatment",error_bar = "mean_se") p
Creates a high-quality box-and-whisker plot to visualize the distribution of thermal metrics across groups. This function is ideal for displaying median values, quartiles, and range, while optionally overlaying individual data points to reveal the underlying sample distribution.
viz_thermal_boxplot( data, y_var, x_var, fill_var = NULL, add_points = TRUE, point_size = 1.5, point_alpha = 0.6, palette = "npg" )viz_thermal_boxplot( data, y_var, x_var, fill_var = NULL, add_points = TRUE, point_size = 1.5, point_alpha = 0.6, palette = "npg" )
data |
Data frame. The merged dataset (e.g., output from |
y_var |
String. The name of the numeric column to plot (e.g., "Max", "Mean"). |
x_var |
String. The name of the categorical column for the X-axis groupings. |
fill_var |
String. The name of the variable used for fill colors. Default is |
add_points |
Logical. If |
point_size |
Numeric. The size of the individual jitter points. Default is 1.5. |
point_alpha |
Numeric. The transparency of the jitter points (0 to 1). Default is 0.6. |
palette |
String or Vector.
|
This function includes several automated optimizations for scientific reporting:
Smart Outlier Handling: If add_points is TRUE, the function automatically hides
the standard boxplot outliers (outlier.shape = NA) to avoid plotting the same data point twice
(once as an outlier, once as a jittered point).
Palette Expansion: Like the barplot function, it automatically interpolates colors if the number of experimental groups exceeds the palette's limit.
Layout: Uses theme_classic() for a clean, academic look.
A ggplot object. Can be further customized with standard ggplot2 functions (e.g., + ylim(20, 40)).
df_bio <- data.frame( Treatment = rep(c("ND", "HFD"), each = 5), Mean = c(runif(5, 33, 35), runif(5, 34, 36)) ) # Boxplot with individual points p <- viz_thermal_boxplot(df_bio, y_var = "Mean", x_var = "Treatment") pdf_bio <- data.frame( Treatment = rep(c("ND", "HFD"), each = 5), Mean = c(runif(5, 33, 35), runif(5, 34, 36)) ) # Boxplot with individual points p <- viz_thermal_boxplot(df_bio, y_var = "Mean", x_var = "Treatment") p
Combines multiple BioThermR objects into a single plot (a montage/collage). Images are laid out in a grid, and filenames are labeled above each image. Uses the 'processed' matrix (NA values are transparent).
viz_thermal_montage2( img_list, ncol = NULL, padding = 10, palette = "inferno", text_color = "white", text_size = 4 )viz_thermal_montage2( img_list, ncol = NULL, padding = 10, palette = "inferno", text_color = "white", text_size = 4 )
img_list |
A list of 'BioThermR' objects. |
ncol |
Integer. Number of columns in the grid. If NULL, tries to create a roughly square grid. |
padding |
Integer. Pixel gap between images. Default is 10. |
palette |
String. Color palette for temperature. Default is "inferno". |
text_color |
String. Color of the filename labels. Default is "white" (good contrast on dark backgrounds). |
text_size |
Integer. Font size of the labels. Default is 4. |
A ggplot object.
# Load a batch of images img_obj_list <- system.file("extdata",package = "BioThermR") batch <- read_thermal_batch(img_obj_list) # Create a montage2 with 4 columns p <- viz_thermal_montage2(batch, ncol = 4, padding = 20)# Load a batch of images img_obj_list <- system.file("extdata",package = "BioThermR") batch <- read_thermal_batch(img_obj_list) # Create a montage2 with 4 columns p <- viz_thermal_montage2(batch, ncol = 4, padding = 20)