cellects.utils.load_display_save
cellects.utils.load_display_save
This script contains functions and classes to load, display and save various files For example: - PickleRick: to write and read files without conflicts - See: Display an image using opencv - write_video: Write a video on hard drive
PickleRick
A class to handle safe file reading and writing operations using pickle.
This class ensures that files are not being accessed concurrently by creating a lock file (PickleRickX.pkl) to signal that the file is open. It includes methods to check for the lock file, write data safely, and read data safely.
Source code in src/cellects/utils/load_display_save.py
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 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 | |
__init__(pickle_rick_number='')
Initialize a new instance of the class.
This constructor sets up initial attributes for tracking Rick's state, including a boolean flag for waiting for Pickle Rick, a counter, the provided pickle Rick number, and the time when the first check was performed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pickle_rick_number
|
str
|
The number associated with Pickle Rick. Defaults to an empty string. |
''
|
Source code in src/cellects/utils/load_display_save.py
read_file(file_name)
Reads the contents of a file using pickle and returns it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_name
|
str
|
The name of the file to be read. |
required |
Returns:
| Type | Description |
|---|---|
Union[Any, None]
|
The content of the file if successfully read; otherwise, |
Raises:
| Type | Description |
|---|---|
Exception
|
If there is an error reading the file. |
Notes
This function attempts to read a file multiple times if it fails.
If the number of attempts exceeds 1000, it logs an error and returns None.
Examples:
Source code in src/cellects/utils/load_display_save.py
write_file(file_content, file_name)
Write content to a file with error handling and retry logic.
This function attempts to write the provided content into a file. If it fails, it retries up to 100 times with some additional checks and delays. Note that the content is serialized using pickle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_content
|
Any
|
The data to be written into the file. This will be pickled. |
required |
file_name
|
str
|
The name of the file where data should be written. |
required |
Returns:
| Type | Description |
|---|---|
None
|
|
Raises:
| Type | Description |
|---|---|
Exception
|
If the file cannot be written after 100 attempts, an error is logged. |
Notes
This function uses pickle to serialize the data, which can introduce security risks
if untrusted content is being written. It performs some internal state checks,
such as verifying that the target file isn't open and whether it should delete
some internal state, represented by _delete_pickle_rick.
The function implements a retry mechanism with a backoff strategy that can include random delays, though the example code does not specify these details explicitly.
Examples:
Source code in src/cellects/utils/load_display_save.py
create_empty_videos(image_list, cr, lose_accuracy_to_save_memory, already_greyscale, csc_dict)
Create empty video arrays based on input parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image_list
|
list
|
List of images. |
required |
cr
|
list
|
Crop region defined by [x_start, y_start, x_end, y_end]. |
required |
lose_accuracy_to_save_memory
|
bool
|
Boolean flag to determine if memory should be saved by using uint8 data type. |
required |
already_greyscale
|
bool
|
Boolean flag indicating if the images are already in greyscale format. |
required |
csc_dict
|
dict
|
Dictionary containing color space conversion settings, including 'logical' key. |
required |
Returns:
| Type | Description |
|---|---|
tuple
|
A tuple containing three elements:
- |
Notes
Performance considerations:
- If lose_accuracy_to_save_memory is True, the function uses np.uint8 for memory efficiency.
- If already_greyscale is False, additional arrays are created to store RGB data.
Source code in src/cellects/utils/load_display_save.py
display_boxes(binary_image, box_diameter, show=True)
Display grid lines on a binary image at specified box diameter intervals.
This function displays the given binary image with vertical and horizontal
grid lines drawn at regular intervals defined by box_diameter. The function
returns the total number of grid lines drawn.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
binary_image
|
ndarray
|
Binary image on which to draw the grid lines. |
required |
box_diameter
|
int
|
Diameter of each box in pixels. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
line_nb |
int
|
Number of grid lines drawn, both vertical and horizontal. |
Examples:
>>> import numpy as np
>>> binary_image = np.random.randint(0, 2, (100, 100), dtype=np.uint8)
>>> display_boxes(binary_image, box_diameter=25)
Source code in src/cellects/utils/load_display_save.py
display_network_methods(network_detection, save_path=None)
Display segmentation results from a network detection object.
Extended Description
Plots the binary segmentation results for various methods stored in network_detection.all_results.
Highlights the best result based on quality metrics and allows for saving the figure to a file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
network_detection
|
object
|
An object containing segmentation results and quality metrics. |
required |
save_path
|
str
|
Path to save the figure. If |
None
|
Source code in src/cellects/utils/load_display_save.py
extract_time(pathway='', image_list=None, raw_images=False)
Extract timestamps from a list of images.
This function extracts the DateTimeOriginal or datetime values from the EXIF data of a list of image files, and computes the total time in seconds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pathway
|
str
|
Path to the directory containing the images. Default is an empty string. |
''
|
image_list
|
list of str
|
List of image file names. |
None
|
raw_images
|
bool
|
If True, use the exifread library. Otherwise, use the exif library. Default is False. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
time |
ndarray of int64
|
Array containing the total time in seconds for each image. |
Examples:
>>> pathway = Path(__name__).resolve().parents[0] / "data" / "single_experiment"
>>> image_list = ['image1.tif', 'image2.tif']
>>> time = extract_time(pathway, image_list)
>>> print(time)
array([0, 0])
Source code in src/cellects/utils/load_display_save.py
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 | |
get_h5_keys(file_name)
Retrieve all keys from a given HDF5 file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_name
|
str
|
The path to the HDF5 file from which keys are to be retrieved. |
required |
Returns:
| Type | Description |
|---|---|
list of str
|
A list containing all the keys present in the specified HDF5 file. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the specified HDF5 file does not exist. |
Source code in src/cellects/utils/load_display_save.py
get_mpl_colormap(cmap_name)
Returns a linear color range array for the given matplotlib colormap.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cmap_name
|
str
|
The name of the colormap to get. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
A 256x1x3 array of bytes representing the linear color range. |
Examples:
Source code in src/cellects/utils/load_display_save.py
is_raw_image(image_path)
Determine if the image path corresponds to a raw image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image_path
|
str
|
The file path of the image. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the image is considered raw, False otherwise. |
Examples:
Source code in src/cellects/utils/load_display_save.py
list_image_dir(path_to_images='', img_extension='', img_radical='')
List files in an image directory based on optional naming patterns (extension and/or radical).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path_to_images
|
optional
|
The path to the directory containing images. Default is an empty string. |
''
|
img_extension
|
str
|
The file extension of the images to be listed. Default is an empty string. When let empty, use the extension corresponding to the most numerous image file in the folder. |
''
|
img_radical
|
str
|
The radical part of the filenames to be listed. Default is an empty string. |
''
|
Returns:
| Type | Description |
|---|---|
list
|
A list of image filenames that match the specified criteria, sorted in a natural order. |
Notes
This function uses the natsorted and insensitive_glob utilities to ensure
that filenames are sorted in a human-readable order.
Examples:
>>> pathway = Path(__name__).resolve().parents[0] / "data" / "single_experiment"
>>> image_list = list_image_dir(pathway)
>>> print(image_list)
Source code in src/cellects/utils/load_display_save.py
movie(video, increase_contrast=True)
Summary
Processes a video to display each frame with optional contrast increase and resizing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
video
|
ndarray
|
The input video represented as a 3D NumPy array. |
required |
increase_contrast
|
bool
|
Flag to increase the contrast of each frame (default is True). |
True
|
Other Parameters:
| Name | Type | Description |
|---|---|---|
keyboard |
int
|
Key to wait for during the display of each frame. |
increase_contrast |
bool
|
Whether to increase contrast for the displayed frames. |
Returns:
| Type | Description |
|---|---|
None
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Notes
This function uses OpenCV's imshow to display each frame. Ensure that the required
OpenCV dependencies are met.
Examples:
>>> movie(video)
Processes and displays a video with default settings.
>>> movie(video, keyboard=0)
Processes and displays a video waiting for the SPACE key between frames.
>>> movie(video, increase_contrast=False)
Processes and displays a video without increasing contrast.
Source code in src/cellects/utils/load_display_save.py
read_and_rotate(image_name, prev_img=None, raw_images=False, is_landscape=True, crop_coord=None)
Read and rotate an image based on specified parameters.
This function reads an image from the given file name, optionally rotates
it by 90 degrees clockwise or counterclockwise based on its dimensions and
the is_landscape flag, and applies cropping if specified. It also compares
rotated images against a previous image to choose the best rotation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image_name
|
str
|
Name of the image file to read. |
required |
prev_img
|
ndarray
|
Previous image for comparison. Default is |
None
|
raw_images
|
bool
|
Flag to read raw images. Default is |
False
|
is_landscape
|
bool
|
Flag to determine if the image should be considered in landscape mode.
Default is |
True
|
crop_coord
|
ndarray
|
Coordinates for cropping the image. Default is |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Rotated and optionally cropped image. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the specified image file does not exist. |
Examples:
>>> pathway = Path(__name__).resolve().parents[0] / "data" / "single_experiment"
>>> image_name = 'image1.tif'
>>> image = read_and_rotate(pathway /image_name)
>>> print(image.shape)
(245, 300, 3)
Source code in src/cellects/utils/load_display_save.py
read_h5(file_name, key='data')
Read data array from an HDF5 file.
This function reads a specific dataset from an HDF5 file using the provided key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_name
|
str
|
The path to the HDF5 file. |
required |
key
|
str
|
The dataset name within the HDF5 file. |
'data'
|
Returns:
| Type | Description |
|---|---|
ndarray
|
The data array from the specified dataset in the HDF5 file. |
Source code in src/cellects/utils/load_display_save.py
read_one_arena(arena_label, already_greyscale, csc_dict, videos_already_in_ram=None, true_frame_width=None, vid_name=None, background=None, background2=None)
Read a single arena's video data, potentially converting it from color to greyscale.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arena_label
|
int
|
The label of the arena. |
required |
already_greyscale
|
bool
|
Whether the video is already in greyscale format. |
required |
csc_dict
|
dict
|
Dictionary containing color space conversion settings. |
required |
videos_already_in_ram
|
ndarray
|
Pre-loaded video frames in memory. Default is None. |
None
|
true_frame_width
|
int
|
The true width of the video frames. Default is None. |
None
|
vid_name
|
str
|
Name of the video file. Default is None. |
None
|
background
|
ndarray
|
Background image for subtractions. Default is None. |
None
|
background2
|
ndarray
|
Second background image for subtractions. Default is None. |
None
|
Returns:
| Type | Description |
|---|---|
tuple
|
A tuple containing: - visu: np.ndarray or None, the visual frame. - converted_video: np.ndarray or None, the video data converted as needed. - converted_video2: np.ndarray or None, additional video data if necessary. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the specified video file does not exist. |
ValueError
|
If the video data shape is invalid. |
Notes
This function assumes that video2numpy is a helper function available in the scope.
For optimal performance, ensure all video data fits in RAM.
Source code in src/cellects/utils/load_display_save.py
1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 | |
read_rotate_crop_and_reduce_image(image_name, prev_img=None, crop_coord=None, cr=None, raw_images=False, is_landscape=True, reduce_image_dim=False)
Reads, rotates, crops (if specified), and reduces image dimensionality if required.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image_name
|
str
|
Name of the image file to read. |
required |
prev_img
|
NDArray
|
Previous image array used for rotation reference or state tracking. |
None
|
crop_coord
|
list
|
List of four integers [x_start, x_end, y_start, y_end] specifying cropping region. If None, no initial crop is applied. |
None
|
cr
|
list
|
List of four integers [x_start, x_end, y_start, y_end] for final cropping after rotation. |
None
|
raw_images
|
bool
|
Flag indicating whether to process raw image data (True) or processed image (False). |
False
|
is_landscape
|
bool
|
Boolean determining if the image is landscape-oriented and requires specific rotation handling. |
True
|
reduce_image_dim
|
bool
|
Whether to reduce the cropped image to a single channel (e.g., grayscale from RGB). |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
img |
NDArray
|
Processed image after rotation, cropping, and optional dimensionality reduction. |
prev_img |
NDArray
|
Copy of the image immediately after rotation but before any cropping operations. |
Examples:
>>> import numpy as np
>>> img = np.random.rand(200, 300, 3)
>>> new_img, prev = read_rotate_crop_and_reduce_image("example.jpg", img, [50, 150, 75, 225], [20, 180, 40, 250], False, True, True)
>>> new_img.shape == (160, 210)
True
>>> prev.shape == (200, 300, 3)
True
Source code in src/cellects/utils/load_display_save.py
read_tif_stack(vid_name, expected_channels=1)
Read video array from a tif file.
This function reads a specific dataset from a tif file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vid_name
|
str
|
The path to the tif stack file. |
required |
expected_channels
|
int
|
The number of channel. |
1
|
Returns:
| Type | Description |
|---|---|
ndarray
|
The data array from the tif file. |
Source code in src/cellects/utils/load_display_save.py
readim(image_path, raw_image=False)
Read an image from a file and optionally process it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image_path
|
str
|
Path to the image file. |
required |
raw_image
|
bool
|
If True, logs an error message indicating that the raw image format cannot be processed. Default is False. |
False
|
Returns:
| Type | Description |
|---|---|
ndarray
|
The decoded image represented as a NumPy array of shape (height, width, channels). |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If |
Notes
Although raw_image is set to False by default, currently it does not perform any raw image processing.
Examples:
[[ 0, 255, 0],
[ 0, 255, 0]],
[[ 0, 0, 255],
[ 0, 0, 255]]], dtype=np.uint8)
Source code in src/cellects/utils/load_display_save.py
remove_h5_key(file_name, key='data')
Remove a specified key from an HDF5 file.
This function opens an HDF5 file in append mode and deletes the specified key if it exists. It handles exceptions related to file not found and other runtime errors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_name
|
str
|
The path to the HDF5 file from which the key should be removed. |
required |
key
|
str
|
The name of the dataset or group to delete from the HDF5 file. Default is "data". |
'data'
|
Returns:
| Type | Description |
|---|---|
None
|
|
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the specified file does not exist. |
RuntimeError
|
If any other error occurs during file operations. |
Notes
This function modifies the HDF5 file in place. Ensure you have a backup if necessary.
Source code in src/cellects/utils/load_display_save.py
save_fig(img, full_path, cmap=None)
Save an image figure to a file with specified options.
This function creates a matplotlib figure from the given image, optionally applies a colormap, displays it briefly, saves the figure to disk at high resolution, and closes the figure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img
|
array_like(M, N, 3)
|
Input image to be saved as a figure. Expected to be in RGB format. |
required |
full_path
|
str
|
The complete file path where the figure will be saved. Must include extension (e.g., '.png', '.jpg'). |
required |
cmap
|
str or None
|
Colormap to be applied if the image should be displayed with a specific
color map. If |
None
|
Returns:
| Type | Description |
|---|---|
None
|
This function does not return any value. It saves the figure to disk at the specified location. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the directory in |
Examples:
>>> img = np.random.rand(100, 100, 3) * 255
>>> save_fig(img, 'test.png')
Creates and saves a figure from the random image to 'test.png'.
>>> save_fig(img, 'colored_test.png', cmap='viridis')
Creates and saves a figure from the random image with 'viridis' colormap
to 'colored_test.png'.
Source code in src/cellects/utils/load_display_save.py
show(img, interactive=True, cmap=None, show=True)
Display an image using Matplotlib with optional interactivity and colormap.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img
|
ndarray
|
The image data to be displayed. |
required |
interactive
|
bool
|
If |
True
|
cmap
|
str or Colormap
|
The colormap to be used. If |
None
|
Other Parameters:
| Name | Type | Description |
|---|---|---|
interactive |
bool
|
If |
cmap |
str or Colormap
|
The colormap to be used. If |
Returns:
| Name | Type | Description |
|---|---|---|
fig |
Figure
|
The Matplotlib figure object containing the displayed image. |
ax |
AxesSubplot
|
The axes on which the image is plotted. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Notes
If interactive mode is enabled, the user can manipulate the figure window interactively.
Examples:
>>> img = np.random.rand(100, 50)
>>> fig, ax = show(img)
>>> print(fig)
<Figure size ... with ... Axes>
Source code in src/cellects/utils/load_display_save.py
967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 | |
video2numpy(vid_name, conversion_dict=None, background=None, background2=None, true_frame_width=None)
Convert a video file to a NumPy array.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vid_name
|
str
|
The path to the video file. Can be a |
required |
conversion_dict
|
dict
|
Dictionary containing color space conversion parameters. |
None
|
background
|
NDArray
|
Background image for processing. |
None
|
background2
|
NDArray
|
Second background image for processing. |
None
|
true_frame_width
|
int
|
True width of the frame. If specified and the current width is double this value, adjusts to true_frame_width. |
None
|
Returns:
| Type | Description |
|---|---|
NDArray or tuple of NDArrays
|
If conversion_dict is None, returns the video as a NumPy array. Otherwise, returns a tuple containing the original video and converted video. |
Notes
This function uses OpenCV to read the contents of a .mp4 video file.
Source code in src/cellects/utils/load_display_save.py
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 | |
video_writing_decision(arena_nb, im_or_vid, overwrite_unaltered_videos)
Determine whether to write videos based on existing files and user preferences.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arena_nb
|
int
|
Number of arenas to analyze. |
required |
im_or_vid
|
int
|
Indicates whether the analysis should be performed on images or videos. |
required |
overwrite_unaltered_videos
|
bool
|
Flag indicating whether existing unaltered videos should be overwritten. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if videos should be written, False otherwise. |
Source code in src/cellects/utils/load_display_save.py
vstack_h5_array(file_name, table, key='data')
Stack tables vertically in an HDF5 file.
This function either appends the input table to an existing dataset in the specified HDF5 file or creates a new dataset if the key doesn't exist.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_name
|
str
|
Path to the HDF5 file. |
required |
table
|
NDArray[uint8]
|
The table to be stacked vertically with the existing data. |
required |
key
|
str
|
Key under which the dataset will be stored. Defaults to 'data'. |
'data'
|
Examples:
Source code in src/cellects/utils/load_display_save.py
write_h5(file_name, table, key='data')
Write a file using the h5 format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_name
|
str
|
Name of the file to write. |
required |
table
|
NDArray[]
|
An array. |
required |
key
|
str
|
The identifier of the data in this h5 file. |
'data'
|
Source code in src/cellects/utils/load_display_save.py
write_video(np_array, vid_name, is_color=True, fps=40)
Write video from numpy array.
Save a numpy array as a video file. Supports .h5 format for saving raw numpy arrays and various video formats (mp4, avi, mkv) using OpenCV. For video formats, automatically selects a suitable codec and handles file extensions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
np_array
|
ndarray of uint8
|
Input array containing video frames. |
required |
vid_name
|
str
|
Filename for the output video. Can include extension or not (defaults to .mp4). |
required |
is_color
|
bool
|
Whether the video should be written in color. Defaults to True. |
True
|
fps
|
int
|
Frame rate for the video in frames per second. Defaults to 40. |
40
|
Examples:
>>> video_array = np.random.randint(0, 255, size=(10, 100, 100, 3), dtype=np.uint8)
>>> write_video(video_array, 'output.mp4', True, 30)
Saves `video_array` as a color video 'output.mp4' with FPS 30.
>>> video_array = np.random.randint(0, 255, size=(10, 100, 100), dtype=np.uint8)
>>> write_video(video_array, 'raw_data.h5')
Saves `video_array` as a raw numpy array file without frame rate.
Source code in src/cellects/utils/load_display_save.py
write_video_from_images(path_to_images='', vid_name='timelapse.mp4', fps=20, img_extension='', img_radical='', crop_coord=None)
Write a video file from a sequence of images.
Extended Description
This function creates a video from a list of image files in the specified directory. To prevent the most comon issues: - The image list is sorted - mp4 files are removed - If they do not have the same orientation, rotate the images accordingly - Images are cropped - Color vs greyscale is automatically determined
After processing, images are compiled into a video file.
Parameters
path_to_images : str The directory where the images are located. vid_name : str, optional The name of the output video file. Default is 'video.mp4'. fps : int, optional The frames per second for the video. Default is 20. img_extension : str, optional The file extension of the images. Default is an empty string. img_radical : str, optional The common prefix of the image filenames. Default is an empty string. crop_coord : list, optional list containing four crop coordinates: [top, bot, left, right]. Default is None and takes the whole image.
Examples
write_video_from_images('path/to/images', vid_name='timelapse.mp4') This will create a video file named 'timelapse.mp4' from the images in the specified directory.
Source code in src/cellects/utils/load_display_save.py
write_video_sets(img_list, sizes, vid_names, crop_coord, bounding_boxes, bunch_nb, video_nb_per_bunch, remaining, raw_images, is_landscape, use_list_of_vid, in_colors=False, reduce_image_dim=False, pathway='')
Write video sets from a list of images, applying cropping and optional rotation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img_list
|
list
|
List of image file names. |
required |
sizes
|
NDArray
|
Array containing the dimensions of each video frame. |
required |
vid_names
|
list
|
List of video file names to be saved. |
required |
crop_coord
|
dict or tuple
|
Coordinates for cropping regions of interest in images/videos. |
required |
bounding_boxes
|
tuple
|
Bounding box coordinates to extract sub-images from the original images. |
required |
bunch_nb
|
int
|
Number of bunches to divide the videos into. |
required |
video_nb_per_bunch
|
int
|
Number of videos per bunch. |
required |
remaining
|
int
|
Number of videos remaining after the last full bunch. |
required |
raw_images
|
bool
|
Whether the images are in raw format. |
required |
is_landscape
|
bool
|
If true, rotate the images to landscape orientation before processing. |
required |
use_list_of_vid
|
bool
|
Flag indicating if the output should be a list of videos. |
required |
in_colors
|
bool
|
If true, process images with color information. Default is False. |
False
|
reduce_image_dim
|
bool
|
If true, reduce image dimensions. Default is False. |
False
|
pathway
|
str
|
Path where the videos should be saved. Default is an empty string. |
''
|
Source code in src/cellects/utils/load_display_save.py
zoom_on_nonzero(binary_image, padding=2, return_coord=True)
Crops a binary image around non-zero elements with optional padding and returns either coordinates or cropped region.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
binary_image
|
NDArray
|
2D NumPy array containing binary values (0/1) |
required |
padding
|
int
|
Amount of zero-padding to add around the minimum bounding box |
2
|
return_coord
|
bool
|
If True, return slice coordinates instead of cropped image |
True
|
Returns:
| Type | Description |
|---|---|
If `return_coord` is True: [y_min, y_max, x_min, x_max] as 4-element Tuple.
|
If False: 2D binary array representing the cropped region defined by non-zero elements plus padding. |
Examples:
>>> img = np.zeros((10,10))
>>> img[3:7,4:6] = 1
>>> result = zoom_on_nonzero(img)
>>> print(result)
[1 8 2 7]
>>> cropped = zoom_on_nonzero(img, return_coord=False)
>>> print(cropped.shape)
(6, 5)
Notes
- Returns empty slice coordinates if input contains no non-zero elements.
- Coordinate indices are 0-based and compatible with NumPy array slicing syntax.