-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathget_dapi.py
More file actions
44 lines (36 loc) · 1.69 KB
/
get_dapi.py
File metadata and controls
44 lines (36 loc) · 1.69 KB
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
import tifffile as tiff
from pathlib import Path
from typing import Union
import numpy as np
from memory_profiler import profile
import time
@profile
def extract_dapi_channel(reg_path: Union[str, Path], dapi_channel: int) -> np.ndarray:
"""
Extracts the DAPI channel lazily without loading the entire image into memory.
Parameters:
- reg_path (str or Path): Path to the registered image file.
- dapi_channel (int): Index of the DAPI channel in the image array.
Returns:
- np.ndarray: Extracted DAPI image as a NumPy array.
Raises:
- FileNotFoundError: If the specified file does not exist at reg_path.
- ValueError: If the DAPI channel index is out of bounds for the image.
"""
reg_path = Path(reg_path)
try:
with tiff.TiffFile(reg_path) as tif:
# Check the number of channels
image_shape = tif.series[0].shape # Shape of the multi-channel image
print(f"Image shape: {image_shape}")
if dapi_channel < 0 or dapi_channel >= image_shape[0]:
raise ValueError(f"DAPI channel index {dapi_channel} is out of bounds for the image shape {image_shape}.")
# Extract the desired channel lazily
#dapi = tif.series[0].levels[0][dapi_channel]
dapi = tif.series[0].levels[0][dapi_channel].asarray()
print(f"Extracted DAPI channel. Shape: {dapi.shape}, Data type: {dapi.dtype}")
return dapi
except FileNotFoundError as e:
raise FileNotFoundError(f"Could not find the file: {reg_path}") from e
except Exception as e:
raise IOError(f"An error occurred while processing the image file: {reg_path}") from e