You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复DICOM转JPG时的文件元信息头缺失错误?

DICOM转JPG时的文件头错误解决方法

问题场景

尝试将.dcm文件转换为.jpg文件,使用的Python代码如下:

import os
import numpy as np
import pydicom
from PIL import Image


def get_names_of_imgs_inside_folder(directory):

    names = []

    for root, dirnames, filenames in os.walk(directory):
        for filename in filenames:
            _, ext = os.path.splitext(filename)
            if ext in [".dcm"]:
                names.append(filename)

    return names

def convert(directory):
    im = pydicom.dcmread('Database/'+directory)
    im = im.pixel_array.astype(float)

    rescaled_image = (np.maximum(im,0)/im.max())*255 # float pixels
    final_image = np.uint8(rescaled_image) # integers pixels

    final_image = Image.fromarray(final_image)
    return final_image

names = get_names_of_imgs_inside_folder('Database')

for name in names:
    image = convert(name)
    image.save(name+'.jpg')

报错信息

File is missing DICOM File Meta Information header or the 'DICM' prefix is missing from the header. Use force=True to force reading.

解决方法

错误提示已经给出核心解决方案:在pydicom.dcmread()中添加force=True参数强制读取不符合标准的DICOM文件。同时代码存在几个潜在问题,一并修正如下:

关键修正点

  • 强制读取参数:给dcmread()加上force=True,绕过文件头校验
  • 完整路径处理:原函数只返回文件名,无法处理子目录文件,改为返回完整路径
  • 安全路径拼接:用os.path.join()替代手动拼接路径,避免跨平台错误
  • 大小写兼容:判断后缀时转为小写,支持.DCM格式文件

修正后完整代码

import os
import numpy as np
import pydicom
from PIL import Image


def get_names_of_imgs_inside_folder(directory):
    full_paths = []
    for root, dirnames, filenames in os.walk(directory):
        for filename in filenames:
            _, ext = os.path.splitext(filename)
            if ext.lower() == ".dcm":
                full_path = os.path.join(root, filename)
                full_paths.append(full_path)
    return full_paths

def convert(dcm_path):
    # 强制读取缺少文件头的DICOM文件
    im = pydicom.dcmread(dcm_path, force=True)
    im_array = im.pixel_array.astype(float)

    # 归一化像素值到0-255范围
    rescaled_image = (np.maximum(im_array, 0) / im_array.max()) * 255
    final_image = np.uint8(rescaled_image)

    final_image = Image.fromarray(final_image)
    return final_image

# 获取所有DICOM文件的完整路径
dcm_paths = get_names_of_imgs_inside_folder('Database')

for dcm_path in dcm_paths:
    # 生成对应JPG文件名
    jpg_path = os.path.splitext(dcm_path)[0] + '.jpg'
    image = convert(dcm_path)
    image.save(jpg_path)

内容的提问来源于stack exchange,提问作者goOdyaga

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 06:25:21