[Python] Cropping DICOM image fragment in Python

Discussão em 'Python' iniciado por Stack, Março 26, 2025.

  1. Stack

    Stack Membro Participativo

    I want to crop a fragment of DICOM (.dcm) file in Python, and then save such an image. I was trying to do such thing using pydicom, openslide or opencv(cv2) library, without success. For example I tried:

    import pydicom
    ds = pydicom.dcmread(r"path_to_file")
    ds=ds[500:1500,500:1500]
    ds.save_as(r"path_to_file2")


    without success. Let me know if you got some ideas how to fix it, regards

    Edit:below are the errors present using above code


    Traceback (most recent call last): File "C:\Users\marci\AppData\Roaming\Python\Python313\site-packages\pydicom\dataset.py", line 1047, in getitem tag = Tag(key) File "C:\Users\marci\AppData\Roaming\Python\Python313\site-packages\pydicom\tag.py", line 89, in Tag raise TypeError( ...<2 lines>... ) TypeError: Unable to create an element tag from '(slice(500, 1500, None), slice(500, 1500, None))': both arguments must be the same type and str or int

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

    Traceback (most recent call last): File "D:\praca\GUMED\serce\testy2.py", line 3, in ds=ds[500:1500,500:1500] ~~^^^^^^^^^^^^^^^^^^^ File "C:\Users\marci\AppData\Roaming\Python\Python313\site-packages\pydicom\dataset.py", line 1049, in getitem raise KeyError(f"'{key}'") from exc KeyError: "'(slice(500, 1500, None), slice(500, 1500, None))'"

    Process finished with exit code 1
    ​

    Continue reading...

Compartilhe esta Página