Created
December 29, 2025 18:02
-
-
Save StoneLabs/5442a09a3ee63d7c303a43c5eb3097a9 to your computer and use it in GitHub Desktop.
DICOM/DICOMDIR Patient Sex Updater
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 os | |
| #Enter your name Here with a ^ symbol. | |
| NAME_SEQ = "Lastname^Firstname".encode("ascii") | |
| SEX_TAG = bytes.fromhex("10 00 40 00") | |
| MALE = ord('M') | |
| FEMALE = ord('F') | |
| #The target sex | |
| NEWVALUE = FEMALE | |
| #Usage: Place this file in the base folder next to DICOMDIR, then run. Done. | |
| #The script will go through the DICOMDIR and all DICOM files and update the sex | |
| #data of the first patient with the above name. | |
| #Enjoy :) | |
| for filename in [os.path.join('DICOM', f) for f in os.listdir('DICOM')] + ['DICOMDIR']: | |
| if not os.path.isfile(filename): | |
| continue | |
| try: | |
| with open(filename, 'rb') as f: | |
| data = bytearray(f.read()) | |
| name_pos = data.find(NAME_SEQ) | |
| if name_pos == -1: | |
| print(f"{filename}: Error could not find name position") | |
| continue | |
| tag_pos = data.find(SEX_TAG, name_pos + len(NAME_SEQ)) | |
| if tag_pos == -1: | |
| print(f"{filename}: Error could not find sex tag") | |
| continue | |
| sex_pos = tag_pos + 4 + 4 | |
| if sex_pos >= len(data): | |
| print(f"{filename}: Error could not find value pos after sex tag (file too short)") | |
| continue | |
| current = data[sex_pos] | |
| if (current == MALE and NEWVALUE == FEMALE) or \ | |
| (current == FEMALE and NEWVALUE == MALE): | |
| data[sex_pos] = NEWVALUE | |
| with open(filename, 'wb') as f: | |
| f.write(data) | |
| print(f"{filename}: {chr(current)}->{chr(NEWVALUE)}") | |
| elif current == NEWVALUE: | |
| print(f"{filename}: {chr(current)} (no change)") | |
| else: | |
| # stop to prevent corruption | |
| if 32 <= current <= 126: | |
| val = chr(current) | |
| else: | |
| val = f"0x{current:02X}" | |
| print(f"{filename}: Error unexpected value {val}") | |
| except Exception: | |
| print(f"{filename}: Error could not find value") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment