Created
March 28, 2025 22:57
-
-
Save alisterburt/2131711c620b954c000f67426f224da2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pathlib import Path | |
import mrcfile | |
import numpy as np | |
image_path = "CountRef_20250327_s004101_75-4_000_Mar27_17.04.37.mrc" | |
image = mrcfile.read(image_path) | |
image = np.array(image) | |
image = image[:, :4031] | |
output_dir = Path() / "cropped" | |
output_dir.mkdir(parents=True, exist_ok=True) | |
output_path = output_dir / image_path | |
mrcfile.write(output_path, image, voxel_size=1) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import concurrent.futures | |
from pathlib import Path | |
import numpy as np | |
import tifffile | |
def crop_and_save(image_path: Path, output_path: Path): | |
image = tifffile.imread(image_path) | |
image = np.array(image) # (t, h, w) | |
image = image[:, :, :4031] | |
tifffile.imwrite(output_path, image) | |
if __name__ == "__main__": | |
# find image files | |
files = list(Path().glob("*.tif")) | |
n_files = len(files) | |
print(f"Found {n_files} images...") | |
# generate output filenames | |
output_dir = Path() / "cropped" | |
output_dir.mkdir(parents=True, exist_ok=True) | |
output_files = [ | |
output_dir / file.name | |
for file in files | |
] | |
# Counter for completed tasks | |
completed = 0 | |
# Process files in parallel using ThreadPoolExecutor | |
with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor: | |
# Submit all tasks | |
futures = [ | |
executor.submit(crop_and_save, file, output_file) | |
for file, output_file in zip(files, output_files) | |
] | |
# Process results as they complete | |
for future in concurrent.futures.as_completed(futures): | |
future.result() # Get result or raise exception if one occurred | |
completed += 1 | |
print(f"\rProcessed {completed}/{n_files} images", end="") | |
# Print a newline after the counter | |
print("\nAll images processed successfully!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment