赞
踩
def preprocess_image(self, image_path, target_height=1350, target_width=900, fill=0, change_side='right', padding_mode='constant'): dicom = pydicom.dcmread(image_path) try: window_center = dicom.WindowCenter window_width = dicom.WindowWidth # 如果WindowCenter和WindowWidth是列表,选择第一个值 if isinstance(window_center, pydicom.multival.MultiValue): window_center = window_center[0] if isinstance(window_width, pydicom.multival.MultiValue): window_width = window_width[0] except Exception as e: print(f"文件 {image_path} {e} 没有窗口参数") dicom_image = apply_voi_lut(dicom.pixel_array, dicom) min_val = window_center - (window_width / 2) max_val = window_center + (window_width / 2) dicom_image = np.clip(dicom_image, min_val, max_val) dicom_image = (dicom_image - min_val) / (max_val - min_val) dicom_image = dicom_image.astype(np.float32) original_height, original_width = dicom_image.shape new_height = target_height # 保持高度不变 new_width = int(original_width * (new_height / original_height)) # 根据新的高度比例调整宽度 # 根据目标宽度调整图像 if new_width < target_width: padding = target_width - new_width if change_side == 'left': img_padded = cv2.copyMakeBorder(dicom_image, 0, 0, padding, 0, cv2.BORDER_CONSTANT, value=fill) else: img_padded = cv2.copyMakeBorder(dicom_image, 0, 0, 0, padding, cv2.BORDER_CONSTANT, value=fill) elif new_width > target_width: crop = int((new_width - target_width) / 2) if change_side == 'left': img_padded = dicom_image[:, crop*2:] else: img_padded = dicom_image[:, :-crop*2] else: img_padded = dicom_image img_resized = cv2.resize(img_padded, (target_width, target_height), interpolation=cv2.INTER_LANCZOS4) img_resized = np.clip(img_resized, 0, 1) preprocess = transforms.Compose([ transforms.ToTensor(), ]) return preprocess(img_resized)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。