yfukai / m2stitch

MIST-inspired microscope image stitching package
Other
63 stars 11 forks source link

KeyError: 'top_ncc_first' #401

Open sajiniho07 opened 1 year ago

sajiniho07 commented 1 year ago

I attempted to run this code, but I encountered a KeyError: 'top_ncc_first' in the stitch_images method. What can I do to resolve this error? I'm using Python 3.10.

import os
import numpy as np
import pydicom
from m2stitch import stitch_images
from pydicom.pixel_data_handlers import apply_voi_lut
from PIL import Image

def read_dcm_images_from_directory(directory_path):
    image_files = [f for f in os.listdir(directory_path) if f.endswith(".dcm")]

    dcm_images = []
    for file_name in image_files:
        file_path = os.path.join(directory_path, file_name)
        try:
            dataset = pydicom.dcmread(file_path)
            image_array = apply_voi_lut(dataset.pixel_array, dataset)
            dcm_images.append(image_array)
        except Exception as e:
            print(f"Error reading '{file_name}': {e}")
    return dcm_images

def calculate_position_indices(images):
    num_images = len(images)
    image_shape = images[0].shape
    position_indices = np.zeros((num_images, len(image_shape)), dtype=int)

    for i in range(num_images):
        indices = np.unravel_index(i, image_shape)
        position_indices[i] = indices

    return position_indices

input_dir = "res"
dicom_images = read_dcm_images_from_directory(input_dir)
position_indices = calculate_position_indices(dicom_images)
stitched_result, _ = stitch_images(images=dicom_images, position_indices=position_indices, ncc_threshold=0.3)
stitched_image = Image.fromarray(stitched_result.astype(np.uint8))
stitched_image.save('final_image_2.jpg')
yfukai commented 1 year ago

Hi, thanks @sajiniho07 for your report! Can you send me the full error message and, if possible, the content of dicom_images and position_indices in .npy format?

yfukai commented 1 year ago

Also the stitched_result is not the stitched images, but instead the position of each tiles. You can check this code to understand how we can actually stitch images with calculated positions. https://m2stitch.readthedocs.io/en/latest/usage.html

sajiniho07 commented 1 year ago

This message is a complete error report that I received. And my input files are all in DCM format. It seems that your library cannot handle the raw DCM file and connect them together. They must be input files in the NPY format. Therefore, I think the code I wrote is incorrect. What do you think? Thank you very much for your attention. 😊

https://github.com/sajiniho07/StitchingTiles/blob/main/m2stitch_method.py

100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 4/4 [00:05<00:00,  1.46s/it]
100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 4/4 [00:00<?, ?it/s]
Traceback (most recent call last):
  File "d:\AI_sources\my-venv-3-10\lib\site-packages\pandas\core\indexes\base.py", line 3802, in get_loc
    return self._engine.get_loc(casted_key)
  File "pandas\_libs\index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\index.pyx", line 165, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\hashtable_class_helper.pxi", line 5745, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas\_libs\hashtable_class_helper.pxi", line 5753, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'top_ncc_first'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\98902\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "C:\Users\98902\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "c:\Users\98902\.vscode\extensions\ms-python.python-2023.14.0\pythonFiles\lib\python\debugpy\__main__.py", line 39, in <module>
    cli.main()
  File "c:\Users\98902\.vscode\extensions\ms-python.python-2023.14.0\pythonFiles\lib\python\debugpy/..\debugpy\server\cli.py", line 430, in main
    run()
  File "c:\Users\98902\.vscode\extensions\ms-python.python-2023.14.0\pythonFiles\lib\python\debugpy/..\debugpy\server\cli.py", line 284, in run_file
    runpy.run_path(target, run_name="__main__")
  File "c:\Users\98902\.vscode\extensions\ms-python.python-2023.14.0\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_runpy.py", line 321, in run_path
    return _run_module_code(code, init_globals, run_name,
  File "c:\Users\98902\.vscode\extensions\ms-python.python-2023.14.0\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_runpy.py", line 135, in _run_module_code
    _run_code(code, mod_globals, init_globals,
  File "c:\Users\98902\.vscode\extensions\ms-python.python-2023.14.0\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_runpy.py", line 124, in _run_code
    exec(code, run_globals)
  File "D:\AI_sources\projects\stitching\m2stitch_method.py", line 37, in <module>
    stitched_result, _ = stitch_images(images=dicom_images, position_indices=position_indices, ncc_threshold=0.3)
  File "d:\AI_sources\my-venv-3-10\lib\site-packages\m2stitch\stitching.py", line 200, in stitch_images
    grid["top_ncc_first"] > ncc_threshold
  File "d:\AI_sources\my-venv-3-10\lib\site-packages\pandas\core\frame.py", line 3807, in __getitem__
    indexer = self.columns.get_loc(key)
  File "d:\AI_sources\my-venv-3-10\lib\site-packages\pandas\core\indexes\base.py", line 3804, in get_loc
    raise KeyError(key) from err
KeyError: 'top_ncc_first'
yfukai commented 1 year ago

Hi, thanks for your udpate!

It seems that your library cannot handle the raw DCM file and connect them together. They must be input files in the NPY format.

No, it can be any files, as far as it is read as a numpy array in memory. It seems that the function apply_voi_lut returns np.ndarray, so I wouldn't expect an issue here.

I couldn't check your code so carefully, but I think here is where you have a problem. position_indices must be something like

[[0,0], # row 0 col 0
 [0,1], # row 1 col 0
...
[N,M]] # row M col N

for a MxN tile. Maybe you can double check this part, or use row and col parameteres instead.