Create single axial slice image file of specified size

Pardon me if I picked the wrong tags.

I have been asked to produce an image file (.png or .jpg) for the single, 4" high by 6" wide midpoint sagittal slice of a T1w anatomical image that will be used on a thank you card. I found nilearn.plotting.plot_anat(), and this seems to basically work,

plot_anat(img, output_file='image.jpg', display_mode='x',
    cut_coords=(25,), draw_cross=False, annotate=False)

but the size is quite small, and I am not a sufficiently practiced Python programmer to be able to figure out how to set the image size, which the documentation for plot_anat()

I tried adding

from matplotlib import pyplot as plt
figsize = (6,4)
plot_anat(img, display_mode='x', cut_coords=(25,), draw_cross=False, annotate=False, figure=0)
plt.savefig('image.png')

thinking that might create the matplotlib image 0 referred to in the plot_anat() documentation, but that did not seem to work.

The scaling of the image seems to be to accommodate the height of the anatomical image, with the excess width being black, as is the image background. Several years ago, this might have been done manually by displaying the image in something like fsleyes or SPM’s image viewer and then doing a screen capture of some kind.

That seems awkward and error-prone.

Thanks!

Hi Bennett,

You can start by creating a matplotlib figure with a specific size:

from matplotlib.pyplot import figure
fig=figure(figsize=(8, 6), dpi=80) # you can change the figsize and DPI

and then use this figure for plot_anat by passing figure=fig into the arguments.

Best,
Steven

Thank you, Steven, that works a treat!

– bennet