重采样DICOM图像遇MultiValue错误:map(float)拼接列表异常求助
Hey there, let's get this sorted out—this error is super common when porting older Python 2 DICOM code to Python 3, so you’re not alone!
Why This Happens
Two main culprits here:
- Python 3’s
map()behavior: In Python 2,map()returns a proper list, but in Python 3 it spits out an iterator. You can’t concatenate an iterator with a list directly, which triggers that error. - Pydicom’s
MultiValueobjects: Modern pydicom versions returnMultiValue(a list-like subclass) for metadata likePixelSpacing. Even if you usemap(), combining this with other lists can cause type mismatches in Python 3.
Step 1: Find the Problematic Line
The error points to your map(float) call. Chances are your code has something like this:
current_spacing = map(float, scan.PixelSpacing) + [float(scan.SliceThickness)]
This worked in Python 2 because map() gave a list, but in Python 3, that map() result is an iterator—so adding it to a list throws the error.
Step 2: Fix the Conversion
We just need to make sure we’re working with actual lists. Here are two clean ways to fix it:
Option 1: Convert map() to a list explicitly
# Turn the map result into a list first pixel_spacing = list(map(float, scan.PixelSpacing)) # Now safely add the slice thickness current_spacing = pixel_spacing + [float(scan.SliceThickness)]
Option 2: Use list comprehensions (more Python 3-friendly)
List comprehensions are easier to read and avoid iterator confusion entirely:
pixel_spacing = [float(val) for val in scan.PixelSpacing] current_spacing = pixel_spacing + [float(scan.SliceThickness)]
Step 3: Update Your Full Resample Function
Here’s how your resample function should look with the fix included (I’ve added comments for clarity):
import numpy as np import scipy.ndimage.interpolation as interp def resample(image, scan, new_spacing=[1,1,1]): # Fix: Convert DICOM spacing values to a proper list of floats pixel_spacing = [float(val) for val in scan.PixelSpacing] current_spacing = pixel_spacing + [float(scan.SliceThickness)] # Calculate resize factors (unchanged logic) resize_factor = np.array(current_spacing) / np.array(new_spacing) new_real_shape = image.shape * resize_factor new_shape = np.round(new_real_shape) real_resize_factor = new_shape / image.shape new_spacing = np.array(current_spacing) / real_resize_factor # Resample the image (using scipy's zoom) resampled_image = interp.zoom(image, real_resize_factor, mode='nearest') return resampled_image, new_spacing
Quick Check
After making this change, test the function again. The error should disappear because we’re now concatenating two proper lists instead of an iterator/MultiValue and a list.
内容的提问来源于stack exchange,提问作者1369

