illan
illan

Reputation: 375

Images sizes not matched when downsampling then upsampling images

I am trying to downsample an image (for speed), run prediction, then upsample it back. Due to rounding, I get mismatches with the original image size for some pixel dimensions/voxel sizes. What is the best way to handle this?

Forward pass

original_size = (192, 192, 299)
original_spacing = (3.6458332538605, 3.6458332538605, 3.27)
out_spacing= (5.0, 5.0, 5.0) 
out_size = [
    int(np.round(original_size[0] * (original_spacing[0] / out_spacing[0]))),
    int(np.round(original_size[1] * (original_spacing[1] / out_spacing[1]))),
    int(np.round(original_size[2] * (original_spacing[2] / out_spacing[2])))]

= [140, 140, 196]

Reverse Pass

original_size = (140, 140, 196)
original_spacing = (5.0, 5.0, 5.0) 
out_spacing= (3.6458332538605, 3.6458332538605, 3.27)
out_size = [
    int(np.round(original_size[0] * (original_spacing[0] / out_spacing[0]))),
    int(np.round(original_size[1] * (original_spacing[1] / out_spacing[1]))),
    int(np.round(original_size[2] * (original_spacing[2] / out_spacing[2])))]

out_size = [192, 192, 300]

The foward-reverse output size has 300 slices vs the input which has 299 due to rounding.

Upvotes: 1

Views: 158

Answers (1)

Cris Luengo
Cris Luengo

Reputation: 60504

The error happens because the output size is rounded, and then you attempt to compute the original size from these rounded values.

You can overcome this issue by realizing that rounding the output size forces a slightly different spacing. You can re-compute the spacing, and store those values together with the image. When you use these correct spacing values instead of the ones you originally desired, the original input size can be reconstructed.

original_size = (192, 192, 299)
original_spacing = (3.6458332538605, 3.6458332538605, 3.27)
out_spacing= (5.0, 5.0, 5.0) 
out_size = [
    int(np.round(original_size[0] * (original_spacing[0] / out_spacing[0]))),
    int(np.round(original_size[1] * (original_spacing[1] / out_spacing[1]))),
    int(np.round(original_size[2] * (original_spacing[2] / out_spacing[2])))]

out_spacing = [
   original_size[0] * original_spacing[0] / out_size[0],
   original_size[1] * original_spacing[1] / out_size[1],
   original_size[2] * original_spacing[2] / out_size[2]]

= [4.999999891008685, 4.999999891008685, 4.988418367346939]

Upvotes: 0

Related Questions