Latest News:10/07/2015: ITK-SNAP 3.4.0-rc1 is available!

# Convert3D Documentation

### What's New?

• -cos,-sin,-atan2 commands
• -align-landmarks command
• -color-map command
• -min, -max commands
• -accum, -endaccum loop structure
• -tile command, great for stacking TIFFs into a 3D volume
• -test-xxx set of commands
• -holefill command
• New c4d command
• -slice command extended to support range of slices (e.g., 5:10, 0:-1, 0:2:-1)

• convert3d is a command-line tool for converting 3D images between common file formats. The tool also includes a growing list of commands for image manipulation, such as thresholding and resampling. The tool can also be used to obtain information about image files.
• The simplest way to use convert3d is to convert images between formats. Here are some examples. Note that you must use the -o command to specify the output of the conversion.
c3d input.img -o output.vtk
c3d hello.cub -o hello.img
c3d float.img -type short -o short.img

• convert3d works in a way like a Revese Polish notation calculator. This means that actions must be preceeded by their inputs: instead of writing 'a + b', we must write 'a b +'. In our case, the inputs are image files, and the actions are specified on the command line. For example, to add a pair of images, we would issue the following command:
c3d input1.img input2.img -add -o output.img

Here, input1.img and input2.img are a pair of image files (in Analyze format), while -add and -o are commands. The command -add takes two input images, adds them, and generates a single output image. The command -o (short for output) takes one input image and writes it to a filename specified after the command (in this case, output.img).
• The behavior of convert3d commands can be affected by options. For example, the -resample command is affected by the -interpolation option. In order for the option to affect a command, the option must precede the command on the command line. For example:
c3d input.img -interpolation Cubic -resample 50x30x40vox -o output.img

• All image processing is done in double-precision reals. However you can use the -type option to save as any data type. By default, image intensities are rounded to the nearest integer (not rounded down) when saving as a integral data type.

### Command autocompletion for Bash users

Users of the bash shell can take advantage of its command autocompletion features. When this is enabled, you can type on the command line

c3d input.img -re[TAB]


and as you hit the TAB key, the list of possible completions will be presented to you. This way you will have to go back to this reference less often. To enable this feature, download the script bashcomp.sh and add the following line to your .profile script;

source SOMEDIR/bashcomp.sh


where SOMEDIR should be replaced by the directory where you saved the script.

### Coordinate Frames and NIFTI

• The latest version of convert3d is NIFTI-compatible. The transformation between the image coordinates and physical coordinates is read from the NIFTI header and maintained through the pipeline. The physical coordinates are in the RAS frame: x increases from left to right, y from posterior to anterior, z from inferior to superior. You can display the coordinate transformation using the -info-full command.
c3d.exe input.nii -info-full Image #1: Image Dimensions : [176, 255, 216] Bounding Box : {[87.2353 103.015 -108.064], [263.235 358.015 107.936]} Voxel Spacing : [1, 1, 1] Intensity Range : [5, 1775] Mean Intensity : 103.175 Voxel->RAS x-form : 1.00000 -0.00000 -0.00000 -87.23527 -0.00000 1.00000 -0.00000 -103.01535 0.00000 0.00000 1.00000 -108.06398 0.00000 0.00000 0.00000 1.00000 Image Metadata: ITK_InputFilterName = NiftiImageIO ITK_OnDiskStorageTypeName = short  ### Usage Examples To convert an image from Metaimage format to short-valued Analyze format use c3d input.mha -type short -o output.img.gz  To apply some arithmetic to the image, do the following c3d input.mha -scale 4096 -shift 2048 -type short -o output.img.gz  To resample and Gaussian blur an image the following command is used c3d input.hdr -interpolation Linear -resample 256x256x192 -smooth 3vox -o output.img.gz  To compute a+2b with a pair of images, do c3d a.img b.img -scale 2 -add -o c.img  ### Multilabel Images Multilabel (ML) images are images where each voxel is assigned a label, chosen from a relatively small set of labels. Labels are typically integers, although they can be floating point numbers. For example, labels can be used to identify anatomical structures in an image: label 1 may correspond to the white matter, 2 to the gray matter, 3 to CSF, and 0 to the background. When processing ML images, one must take certain care to make sure that numerical operations do not blend labels into meaningless values. For instance, smoothing a ML image will create intermediate values at places where two labels are near each other. A similar issue comes up when resampling or reslicing these images. However, convert3d provides commands that split the ML image into a set of binary images (one for each label), allowing you to perform operations on each label separately. Subsequently, the processed label-wise images can be combined into a new ML image. This is accomplished using commands -split and -merge. In addition, the -foreach ... -endfor command structure allows operations to be applied sequentially to all images on the stack. For example, to smooth the components of a ML image separately, we can use the following command c3d ml.img -split -foreach -smooth 3mm -endfor -merge -o mlsmooth.img  The -merge command implements voting between individual label images. A label assigned to a voxel during merge is that of the label image with highest intensity at that voxel. The values of the labels assigned during the -merge command are remembered from the time the -split command is run. So if the image ml.img has labels 1, 4, 10 then the output image will also have the same labels. When applying spatial transformations to ML images, one may choose to use nearest neighbor interpolation: c3d ref.img ml.img -interpolation NearestNeighbor -reslice-matrix affine.mat -o mltran.img  However, this causes some aliasing of the results. It is sometimes useful to assume that labels are fuzzy, and to apply linear or cubic interpolation to the fuzzy labels. Here is how we can apply an affine transformation to a ML image this way: c3d ref.img -popas ref ml.img -split -foreach -smooth 3mm -insert ref 1 -reslice-matrix affine.mat -endfor -merge-o mltran.img  This command is somewhat complex, mainly because the -reslice-matrix command requires a reference image as the first operand, and we have to use named images to insert it on the stack in the right place. ### Commands: Stack Manipulation and Flow Control These commands are used to manipulate the convert3d stack. The stack is a linear array of images. Every time an image is specified on the command line, it is loaded and placed at the top of the stack. Most operations take one image from the top of the stack, apply some operation to it, and place the result on the top of the stack. Certain commands like -levelset and -reslice-matrix take two images from the top of the stack as the input and replace them with a single output. Some other commands, like -add and -vote take all images on the stack and replace them with a single output. Sometimes, for complex operations, it is useful to change the order of the images on the stack, to duplicate images, or to execute the same command multiple times. The stack manipulation and flow control commands allow you to complete complex tasks without saving intermediate images to the disk. -accum command(s) -endaccum Apply a binary operation (such as addition or multiplication) to all the images on the stack in a cumulative fashion. The command(s) will be applied to the last and second-to-last images on the stack, then to the result of this operation and the third-to-last image on the stack and so on. Below is the example of using the command to add multiple images. c3d image*.nii -accum -add -endaccum -o sum.nii  -as var Associates the image currently at the top of the stack with variable name 'var'. This allows you to retrieve the image later on the command line using the -push command. The -as and -push commands are useful when you need to use a certain image more than once during a convert3d operation. For example, if you want to compute the distance transform of a binary image and mask it so that the values outside of the binary image region have value 0, you would use the following command: c3d binary.img -as A -sdt -push A -times -o masked_distance.img  -clear Clears the image stack. Images assigned a name with the -as command will remain in memory. -foreach commands -endfor This command forces the commands between -foreach and -endfor to be applied to every image on the stack. The main use of this command is to automate processing of multiple datasets. For example, c3d epi*.nii -foreach -smooth 3mm -endfor -add -o episum.nii  -insert var pos This command is similar to -push, but allows you to insert the image associated with 'var' at any position in the stack, counting from the top. When 'pos' is zero, the image is placed at the top of the stack (same as -push). When pos is one, the image is placed at the next-to-top position, and so on. -pop Removes the last image from the image stack. Images assigned a name with the -as command will remain in memory. -popas var Removes the last image from the stack, but also assigns it the name 'var', keeping the image in memory. Same as calling -as var followed by -pop. -push var Places the image associated with variable name 'var' on top of the image stack. Variable names are assigned using the -as command. The -as and -push commands are useful when you need to use a certain image more than once during a convert3d operation. For example, if you want to compute the distance transform of a binary image and mask it so that the values outside of the binary image region have value 0, you would use the following command: c3d binary.img -as A -sdt -push A -times -o masked_distance.img  -reorder k -reorder fraction Rearranges images in the stack, such that images that are k positions apart become next to each other on the stack. In other words, if the original order of the images is 1, 2, ..., n, the new order of the images becomes 1, 1+k, 1+2k, ..., 2, 2+k, 2+2k, ..., k, 2k, ... n. Of course, n must be divisible by k. As an alternative to specifying k, you can specify a floating point number (i.e., -reorder 0.5), in which case k is obtained by multiplying n by the floating point number and rounding to the nearest integer. Here are a couple of examples: c3d a1.nii a2.nii a3.nii a4.nii b1.nii b2.nii b3.nii b4.nii -reorder 4 ... // These 3 commands are equivalent c3d a1.nii a2.nii a3.nii a4.nii b1.nii b2.nii b3.nii b4.nii -reorder 0.5 ... // These 3 commands are equivalent c3d a1.nii b1.nii a2.nii b2.nii a3.nii b3.nii a4.nii b4.nii ...  The -reorder command us useful when you specify two sets of images using wildcards and then want to perform pairwise operations on the images. For example c3d weight*.nii gray*.nii -reorder 0.5 -weighted-sum-voxelwise -o wsum.nii c3d weight1.nii gray1.nii weight2.nii gray2.nii ... -weighted-sum-voxelwise -o wsum.nii  -dup Duplicates the image on the stack. This is the same as -as var -push var but shorter. An example is when you want to pass an image as both arguments to a binary operator, e.g., computing the square of the image intensity: c3d input.img -dup -times -o square.img  ### Commands: Image Processing The following command-line parameters invoke an action that is applied to images. Unary commands apply the action to the top image on the stack, binary commands apply to the top two images and so on. Commands are affected by options, which are listed separately. -add Adds two images. The command is applied to the last two images on the stack. For example # Add two images: x = a + b c3d a.img b.img -add -o x.img # Add three images, x = (a + b) + c in the first example, x = a + (b + c) in the second c3d a.img b.img -add c.img -add -o x.img c3d a.img b.img c.img -add -add -o x.img # Subtract two images, using scale command: x = a - b c3d a.img b.img -scale -1 -add -o x.img  -ad,-anisotropic-diffusion conductance n_iter Executes the Perona-Malik anisotropic diffusion algorithm on the image. This smooths the image, but with edge preservation. Conductance is a number between 0 and 1 that determines how well edges are preserved. n_iter is the number of iterations, which affects the scale of the smoothing. c3d x.img -ad 0.1 100 -o ad.img  -atan2 compute the angle in radians from sine and cosine. This is a voxel-wise operation. It requires two images on the stack. c3d sin_theta.nii.gz cos_theta.nii.gz -atan2 -o theta.nii.gz  -biascorr Performs automatic bias field correction for MRI images. This feature uses the N3 implementation in ITK by Dr. Tustison, based on the N3 algorithm by Sled et al. c3d mri.nii.gz -biascorr -o mricorr.nii.gz  -align-landmarks, -alm dof outfile Performs rigid or affine alignment between to sets of landmark images. A landmark image is an image where for every intensity value, the centroid of all voxels with that intensity represents a landmark. Landmarks can be created using the paintbrush tool in ITK-SNAP (they can be spheres, cubes, etc). The first image on the stack is the target/fixed/reference image, and the second is the moving image. The parameters are the degrees of freedom, which is a number (6 for rigid, 7 for rigid+scale, 12 for affine) and the output matrix file. In this example, we have images fixed.nii and moving.nii' with corresponding landmark images. We use landmarks to align the moving image to the fixed: c3d fixed_landmarks.nii moving_landmarks.nii -alm 6 rigid.mat c3d fixed.nii moving.nii -reslice-matrix rigid.mat -o moving_resliced_to_fixed.nii  -binarize Converts an image to binary by mapping all background values (the background is 0 by default and can be changed by the option -background) to 0 and all non-background values to 1. The -binarize command is shorthand for the -threshold command. c3d test.img -binarize -o binary.img c3d -background 10 -binarize -o binary.img c3d test.img -threshold 10 10 0 1 // equivalent to above command  -centroid <value> Reports the centroid, in physical coordinates, of all foreground voxels in the image. c3d binaryimage.img -centroid // centroid of all non-0 voxels c3d grayimage.img -thresh 1000 7000 1 0 -centroid 1 // centroid of all voxels in range 1000-7000 c3d labelimage.img -thresh 5 5 1 0 -centroid // centroid of all voxels with label 5 c3d labelimage.img -split -foreach -centroid -endfor // centroids of all labels (including 0)  -clip iMin iMax Clips image intensities, so that the values below iMin are converted to iMin and values greater than iMax are converted to iMax. This is useful for eliminating hyperintensities in images. Values iMin and iMax are intensity specifications (see below). c3d mri.img -clip 1000 8000 -o mriclip01.img // Clips below and above c3d mri.img -clip -inf 8000 -o mriclip02.img // Clips above only c3d mri.img -clip -inf 95% -o mriclip03.img // Clips at 95th percentile  -color-map, -colormap ColormapName Converts a scalar image to a color (RGB) image using a specified color map. The output of the command are three images, containing the red, green and blue channels of the RGB image. The mapping uses the range of the input image, e.g., using the jet color map, the lowest intensity pixel in the image will be mapped to blue, and the highest intesnity pixel will be mapped to red. The admissible color maps are hot,cool,spring,summer,autumn,winter,copper,jet,hsv,red,green,blue,grey,overunder. The command can be used with the -omc command to write RGB images. The example below generates a PNG image from a slice in a scalar image. c3d scalar.nii.gz -slice z 50% -flip y -color-map jet -type uchar -omc colorslice.png  -connected-components, -comp Computes the connected components of a binary image. Each connected component is assigned an integer index. Indices are ordered by the size of the component, so the component assigned index 1 is the largest. The background is assigned index 0. To select the largest connected component, combine the call to -connected-components with a call to -threshold. c3d binary.img -connected-components -o comp.img c3d binary.img -connected-components -threshold 1 1 1 0 -o largest_comp.img  -coordinate-map-voxel, -cmv Replaces the last image on the stack with 3 images, whose intensity at a given voxel are the voxels x, y and z coordinates, respectively, in voxel space. c3d image.nii -cmv -oo coordmap%d.nii.gz  Here is how we can use this command to split a segmentation image into a left hemisphere segmentation and a right hemisphere segmentation (assuming the X coordinate corresponds to the R->L axis): c3d seg.nii -as SEG -cmv -pop -pop -thresh 50% inf 1 0 -as MASK \ -push SEG -times -o seg_left.nii.gz \ -push MASK -replace 1 0 0 1 \ -push SEG -times -o seg_right.nii.gz  -coordinate-map-physical, -cmp Save as -coordinate-map-voxel, but physical coordinates are stored in the output images. -copy-transform Copies the geometrical transform (origin, spacing, direction cosines) from the first image to the data from the second image. This is best done with NIFTI images, which store this information well. c3d first.nii second.nii -copy-transform -o out.nii  -cos compute the cosine of the image voxels. -create dimensions voxel_size Creates a new blank image with specified dimensions and voxel size. The image is set to the current background value, which is zero by default but can be overwritten with the -background command. The origin of the image can be changed with the -origin command. c3d -create 256x256x160 1x1x1mm -o newimage.img c3d -background 128 -create 256x256x160 1x1x1mm -origin 128x128x80mm -o newimage.img  -dilate label radius Applies the dilation mathematical morphology operation to a binary image. The first parameter is the intensity value of the object that is to be dilated. The second is the radius of the dilation structuring element in 3D. c3d binary.img -dilate 255 3x3x3mm -o newimage.img  -divide Divides one image by another. For instance to compute C = A / B, use the command c3d A.img B.img -divide -o C.img  -erf mu sigma Computes the standard error function. This is useful for computing error functions or making soft thresholds. The function computes y = erf((x - mu)/sigma). c3d input.img -erf 5 2 -o erf.img  -erode label radius Applies the erosion mathematical morphology operation to a binary image. The first parameter is the intensity value of the object that is to be erodes. The second is the radius of the erosion structuring element. c3d binary.img -erode 255 3mm -o newimage.img  -exp Computes exponent of each voxel in the image c3d input.img -exp -o output.img  -flip axes Flips the image around specified axes. The parameter 'axes' may be any combination of characters 'x', 'y', and 'z'; the order does not matter. c3d input.img -flip xy -o output.img  -glm design_matrix_file contrast_vector_file Applies voxel-wise general linear model to a set of images. More precisely, the general linear model solves the following system:Y = X \beta + \epsilon$, where Y are the observations (a list of n images, where each voxel is treated as an independent observation); X is the$n x k$design matrix, where$k$is the number of factors;$\beta$is a set of$k$unknown images (factors) and$\epsilon$is the error term. The command will compute the$\betaimages and return a weighted sum of them, where the weights are specified in the contrast vector. The design matrix and the contrast vector are passed in as files. The file format is just a space-separated list of numbers. For a good explanation of the general linear model, see S. Kiebel and A. Holmes, General Linear Model, in Ashburner, Friston, Holmes eds., Human Brain Function, 2nd Edition. The example below computes the regression coefficient between a set of longitudinal images and subject's age: echo "1 67.00" > design_mat.txt echo "1 75.00" >> design_mat.txt echo "1 80.00" >> design_mat.txt echo "1 83.00" >> design_mat.txt echo "0 1" >> contrast_vec.txt c3d time1.img time2.img time3.img time4.img -glm design_mat.txt contrast_vec.txt -o regress.img  -holefill intensity_value [0|1] Apply the binary hole filling algorithm to a particular intensity value in the image. The input image is typically a binary image or a multi-label segmentation image. Holes (voxels not matching the specified intensity value that are completely contained by voxels matching this value) are filled. The second parameter specifies what type of topological connectivity is used to determine holes. The value 0 uses the default algorithm in ITK (face connectivity) and 1 uses the full connectivity variant (face, edge and vertex connectivity). For more details see the ITK page for this algorithm. c3d segmentation.nii.gz -holefill 5 0 -type uchar -o filledlabel5.nii.gz  -info, -info-full Prints information about the last image on the stack. The command -info-full prints more information about the image, such as the metadata dictionary. For example, c3d image.hdr -info  -label-statistics -lstat Given an image and a multilabel or binary image, this command computes the statistics for every label. For instance, if image mri.nii is a medical image and seg.nii is a multilabel segmentation of the image with labels 0, 1 and 4, the following command can be used to print the statistics of the intensity of mri.nii for each of the labels c3d mri.nii seg.nii -label-statistics  The output contains the mean, standard deviation, maximum intensity and minimum intensity for each label. -landmarks-to-spheres <landmark file> <radius> Reads a list of landmarks from a file and for each landmark draws a sphere with the landmark at the center. Landmarks are specified in a file with four entries per line: x y z value, where (x,y,z) give the landmark position in physical units (mm) and value is the image value that the sphere will be filled with. The radius (for now) is specified in physical units (mm). The example below first creates a landmark file, and then calls c3d to create the spheres. Notice that the -scale command is first used to create a blank image of the same dimensions as the input image. echo 14.5 23.12 44.53 1 > landmarks.txt echo 76.3 43.12 34.32 2 >> landmarks.txt ... c3d image.img -scale 0 -landmarks-to-spheres landmarks.txt 3 -o landspheres.img  -laplacian, -laplace Applies the Laplacian filter to the image. Used to detect ridges of intensity. Typically, used with the -smooth option: c3d input.img -smooth 1.2vox -laplacian -o output.img  -levelset n_iter Perform level set segmentation for n_iter iterations, like in ITK-SNAP. The last image on the stack is treated as the initialization image and the second image on the stack is the speed image. Both images should be in the range between -1 and 1. Here is how the signs of the different images are interpreted  Sign Speed Image Initialization Image Output Image +1 Foreground Voxels Outside Outside -1 Background Voxels Inside Inside Here is an example where you have the speed and the initialization given: c3d speed.img initial.img -levelset-curvature 0.5 -levelset 100 -o seg.img  Here is an example of segmenting the ventricles in an MRI image, where the ventricles and other CSF have intensity below 715. The image seg_bubbles.nii.gz in this example is a binary image of the initialization seeds (1 inside the seeds, 0 outside). c3d brain.nii.gz -erf 715 100 -scale -1 seg_bubbles.nii.gz \ -replace 0 1 1 -1 -levelset-curvature 0.2 -levelset 500 \ -thresh -inf 0 1 0 -o segmentation.nii.gz  Another example of smoothing a binary image that is useful for cleaning up manual segmentations. Here the speed image is positive inside the binary object, and the initialization is negative inside the object. The command writes out both the level set image (whose 0-level set is the smoothed boundary of the binary object) and the smoothed binary object c3d binary.img -threshold 1 inf 1 -1 -binary.img 1 inf 1 -1 \ -levelset-curvature 1.5 -levelset 100 -o levelset.img \ -thresh -inf 0 1 0 -o smoothed_binary.img  -log,-ln Computes natural logarithm of the image -log10 Computes base 10 logarithm of the image c3d input.img -ln -o output.img  -max, -maximum Computes the voxel-wise maximum of two images -min, -minimum Computes the voxel-wise minimum of two images c3d a.img b.img -max -o abmax.img c3d a1.img a2.img a3.img a4.img -accum -min -endaccum -o amin.img  -mean Computes the mean of all the images on the stack. c3d image_*.nii -mean -o mean.nii  -merge Works in conjunction with the -split command. Has same behavior as -vote, except that label values are carried from the input to the -split command. -mi, -mutual-info [movtransform.mat] Compute the mutual information metric between the last two images on the stack. If an optional movtransform.mat file is provided, the metric is computed by applying the transform to the moving image. The definitions of reference and moving images and the transform file format are similar to the -reslice-matrix command. # Compute metric between ref.nii and mov.nii c3d ref.nii mov.nii -mi # Compute metric between ref.nii and mov.nii after applying transform to mov.nii c3d ref.nii mov.nii -mi tmov.mat  -mmi, -mattes-mutual-info [movtransform.mat] Compute the Mattes mutual information metric between the last two images on the stack. Usage is similar to the -mi command above. -msq, -mean-square [movtransform.mat] [reftransform.mat] Compute the mean square difference metric between the last two images on the stack. If an optional movtransform.mat file is provided, the metric is computed by applying the transform to the moving image. If, in addition to movtransform.mat, the optional reftransform.mat file is also provided -- the moving transform is applied to the moving image, the ref transform is applied to the reference image, and the metric is computed in an image space that is physically halfway between the reference and moving images. This may be useful for unbiased metric computation if the two transforms are inverse of each other as both images undergo similar amount of interpolation. The definitions of reference and moving images and the transform file format are similar to the -reslice-matrix command. # Compute metric between ref.nii and mov.nii c3d ref.nii mov.nii -msq # Compute metric between ref.nii and mov.nii after applying transform to mov.nii c3d ref.nii mov.nii -msq tmov.mat # Compute metric between ref.nii and mov.nii in a neutral space after applying transforms to both c3d ref.nii mov.nii -msq tmov.mat tref.mat  -multiply Multiply two images voxel-by-voxel. The operation is applied to the last two images on the stack. # Compute x = a * b c3d a.img b.img -multiply -o x.img # Compute x = a * (b + c) using -add and -multiply c3d a.img b.img c.img -multiply -add -o x.img  -ncor, -normalized-correlation [movtransform.mat] [reftransform.mat] Compute the normalized correlation metric between the last two images on the stack. Usage is similar to the -msq command above. -nmi, -normalized-mutual-info [movtransform.mat] Compute the normalized correlation metric between the last two images on the stack. Usage is similar to the -mi command above. -o image Write image, overriding an existing image. Without the -o option, convert3d will write an image only if it does not exist. The -o options protects input images from being accidentally deleted. Here we copy an image, changing format:<pre>convert3d image1.cub -o image2.img</pre>The -o option can also be used to save an intermediate image in the stack: c3d image1.img -threshold 1 10 1 0 -o thresh.img -resample 100x100x100 -o final.img  : -omc [number] file -output-multicomponent [n] file Write multiple images on the convert3d stack as a single multi-component image. If the optional number n is specified, only the last n images on the stack will be used. c3d red.nii green.nii blue.nii -omc rgb.mha  -oo image_list | image_spec -output-multiple image_list | image_spec Write all images on the convert3d stack as multiple files. There are two ways to use this command. The first is to supply a list of file names, separated by spaces: c3d labelimage.nii -split -oo labelA.nii labelB.nii labelC.nii  In the above example, the image at the top of the stack will be saved as labelC.nii, the image next to the top of the stack will be saved as labelB.nii and so on. The second way to use the -oo command is to supply a pattern for the output filenames. In this case, all the images on the stack will be written. The format for the pattern is the same as for the C++ printf command. For example, the following command c3d labelimage.nii -split -oo label%02d.nii  will generate images label00.nii, label01.nii, label02.nii and so on. The image at the top of the stack will have the highest number, and the image at the bottom of the stack will have number 00. -orient CODE Set the orientation of the image using one of 48 canonical orientations. The orientation describes the mapping from the voxel coordinate system (i,j,k) to the physical coordinate system (x,y,z). In the voxel coordinate system, i runs along columns of voxels, j runs along rows of voxels, and k runs along slices of voxels. It is assumed (by the NIFTI convention) that the axes of the physical coordinate system run as follows: x from (L)eft to (R)ight, y from (P)osterior to (A)nterior, z from (I)nferior to (S)uperior. The CODE passed in is a three-letter code consisting of letters RLAPSI. Each letter describes the anatomical direction corresponding to the voxel coordinates (i,j,k). For example, code RAI means that i runs from Right to Left, j from Anterior to Posterior, and k from Inferior to Superior. c3d input.img -orient RAI -o output.img c3d input.img -orient SAL -o output.img  This command has the same behavior as the 'Reorient Image' menu option in ITK-SNAP. -origin vector Set the origin of the image. The origin is the world coordinate (in NIfTI coordinate space) of the center of the voxel (0,0,0) in the image. The origin should be specified in millimeters. c3d input.img -origin 100x100x100mm -o output.img  -origin-voxel vector Set the origin of the image by specifying the voxel coordinates of the center of the patient (RAS) coordinate system. The vector should be specified in voxel units. c3d input.img -origin-voxel 60x70x35 -o output.img c3d input.img -origin-voxel 50% -o output.img # image centered around origin  -overlay-label-image lookup_table_file opacity -oli lookup_table_file opacity This command takes a grayscale image and a label image (i.e. image with a set of discrete values) and produces red, green and blue components of a color image. The resulting color image is an overlay of the labels over the grey image. The first parameter (lookup_table) is a text file with entries in the format "label_value red green blue alpha." Alpha values must be between 0 and 1. Red, green and blue values should be on the same order as the intensity of the grey image (typically 0-255). The text file is compatible with ITK-SNAP and can be generated using the ITK-SNAP "Segmentation->Save Label Descriptions" command. The second parameter (opacity) is between 0 and 1 and sets the overall opacity of the overlay. The output of this command is similar to the way ITK-SNAP presents segmentation data on top of grayscale images. ./c3d gray.nii.gz -stretch 2% 98% 0 255 -clip 0 255 seg.nii.gz -oli labels.txt 0.5 -omc rgb.nii.gz  Note: this command does not interpolate between entries in the lookup table. It should not be used for images with a continuous intensity spectrum. Here is a more complex example, used to visualize a segmentation result. We do a few things in this command: trim grayscale and segmentation images to an ROI around the object of interest; map intensity range of the grayscale image to 0-255; extract slices through the middle of the cropped images; overlay segmentation on the grayscale image; and save as a color PNG file. ./c3d seg.nii.gz -trim 20x20x0vox -as S gray.nii.gz -stretch 2% 98% 0 255 -clip 0 255 \\ -reslice-identity -push S -foreach -slice z 50% -flip xy -endfor \\ -oli labels.txt 0.5 -type uchar -omc ovl.png  -overlap Z Compute overlap between last two images on the stack. Overlap is computed for a given label Z, i.e., the number of voxels that are equal to Z in both images is computed and divided by either the average number of voxels equal to Z in both images (to get Dice coefficient) or by the size of the region where at least one of the images is equal to Z. Use the flag -verbose to get full information c3d -verbose img1.img img2.img -overlap 255  -pad <padlower> <padupper> <value> Pads the image by a given percentage or number of voxels. The padlower dimension pads along the zero faces of the image, and the padupper dimension pads along the upper faces of the image. For example to add 1 voxel to the left side of an image, do c3d img1.nii -pad 1x0x0vox 0x0x0vox 0 -o padded.nii  while c3d img1.nii -pad 2x2x4vox 0% 0 -o padded.nii  adds two voxels padding to the left and posterior sides, and four slices to the bottom of the image. Note that the first argument changes the location of voxel (0,0,0) and thus the origin of the output image will be changed to maintain anatomical alignment between the padded and original images. MRIcro does not correctly interpret the origins of NIFTI images, but ITK-SNAP does. Normally you will want to pad with zeros, but you can pad with any constant value, eg : c3d img1.nii -pad 10% 10% 1 -o padded.nii  Adds 10% to all sides of the image, and fills the new voxels with the value 1. -probe <point> Get the value of the image at the position specified by the parameter 'point'. c3d img1.img -probe 128x120x160vox c3d img1.img -interpolation NearestNeighbor -probe 60x60x60mm  -rank This command takes N images as the input (all the images on the stack are used). It also generates N images as the output. For voxel k in image j, it assigns it a label based on its rank among the values of voxel k in all N images. If the voxel has highest intensity in image j, then the j'th output will have value 1. c3d img1.img img2.img ... imgN.img -rank -oo rank%d.img  -reciprocal Computes the reciprocal of an image. For instance to compute B = 1 / A, use the command c3d A.img -reciprocal -o B.img  -region vOrigin vSize Extract a rectangular region from the image. The first parameter is the position of the corner of the region, and the second is the size of the region. c3d img1.img -region 20x20x20vox 50x60x70vox -o img2.img c3d img1.img -region 25% 50% -o img3.img  -replace I1 J1 I2 J2 ... Replace intensity I1 by J1, I2 by J2 and so on. Allowed values of intensity include nan, inf and -inf. c3d img1.img -replace 1 128 nan 0.0 -o img2.img  -resample <size> Resamples the image, keeping the bounding box the same, but changing the number of voxels in the image. The size can be specified as a percentage, for example to double the number of voxels in each direction. The -interpolation flag affects how sampling is performed. c3d img1.img -resample 123x142x200 -o img2.img c3d img1.img -resample 200% -o img2.img c3d img1.img -resample 100x100x200% -o img2.img c3d img1.img -background 4.0 -interpolation Cubic -resample 123x142x200 -o img2.img  -resample-mm <voxel_size> Resamples the image as in -resample, but the user specifies the new voxel size rather than number of voxels. This may not be precise, so the bounding box of the image may change. A warning will be generated in that case. c3d img1.img -resample-mm 1.0x1.5x1.5mm -o img2.img  -reslice-itk <transform_file> -reslice-matrix <matrix_file> Applies affine (or other) transform to an image. The first image on the command line is the reference image. The output image will have same dimensions and voxel-to-space transform as the reference image. The second parameter is the moving image, i.e., the image to be resliced. The transform file is either an ITK-format transform file or a 4x4 matrix that gives a transform from the physical space of the reference image to the physical space of the moving image. To generate a transform file, you must use some sort of registration algorithm, which is not part of convert3d (at least not yet). c3d reference_image.nii moving_image.nii -reslice-itk transform_file.txt -o output_image.nii  Here is an example of using -reslice-matrix with SPM. In MATLAB, you would execute the following commands p = spm_coreg('reference.nii', 'moving.nii'); m = inv(spm_matrix(p(:)')); save -ascii ref2mov_mat.txt  Then to reslice using convert3d, run c3d reference.nii moving.nii -reslice-matrix ref2mov.txt -o resliced.nii  -reslice-identity Applies the -reslice command with the identity transform. This is useful when you have two scans of the same subject with different coordinate transformations to patient space and you want to resample one scan in the space of another scan. For example, if you have T1 and T2 images in different coordinate frames, and want to reslice the T2 image into the space of the T1 c3d t1.nii t2.nii -reslice-identity -o t2_in_t1_space.nii  -rms Computes RMS (root mean square) of all images on the stack. The command takes the square of each image on the stack, adds all the squared images and takes the square root of the result. This is very useful for statistical operations. Images must have the same size! c3d img1.img img2.img img3.img img4.img -rms -o rms.img  -scale <factor> Scales image intensity by the given factor. c3d img1.img -scale 0.5 -o img2.img  -set-sform <sform.mat> Set the Nifti sform of the first image on the stack to the matrix provided. -shift <constant> Adds a constant to the image intensity. c3d img1.img -shift 100 -o img2.img  -signed-distance-transform, -sdt Computes the signed distance transform of a binary image. Voxels where the binary image is non-zero will have negative values and voxels where the binary image is zero will have negative values. The magnitude of the value will be the approximate Euclidean distance to the boundary of the object represented by the binary image. c3d binary.img -sdt -o dist.img  -sin compute the sine of the image voxels. -slice axis position_spec Extracts a slice along the specified axis (x,y or z). The position specifier position_spec can be a single slice or a range of slices. For a single slice, it can be specified as a number or a percentage. Numbering is zero-based, i.e, the first slice is slice 0, the last slice is N-1, where N is the number of slices. For a range, use MATLAB notation first:step:last. The slice is placed on the stack as an image with size 1 in the last dimension. You can save the slice as a 2D PNG image. c3d input.img -slice x 128 -o myslice.nii.gz c3d input.img -slice y 50% myslice.nii.gz c3d input.img -slice z 25% -type uchar -stretch 0 2000 0 255 -o myslice.png c3d input.img -slice z 0:-1 -oo slice%0d.nii.gz c3d input.img -slice z 20%:10%:80% -oo slice%0d.nii.gz  With the new command c4d, the -slice command can be used to extract volumes from a 4D image. This can be useful to reformat a 4D NIFTI image as a 3D multi-component NIFTI image, using the command c4d input4d.nii.gz -slice w 0:-1 -omc output3d_multicomp.nii.gz  -smooth <vector> Applies Gaussian smoothing to the image. The parameter vector specifies the standard deviation of the Gaussian kernel. Also see Vector Format Specification below. c3d img1.img -smooth 2x1x1vox -o out.img  -spacing <vector> Sets the voxel spacing of the image. This should always be a vector with positive components. For example, to set the spacing of the image to 1mm isotropic, use the command below. This command only changes the header of the image, not its contents. c3d img.nii -spacing 1x1x1mm -o out.img  -sphere <center> <radius> <value> Draws a filled sphere with specified center, radius and value. This is useful for converting landmarks into images. The center and radius can be specified in units of voxels or mm. The radius can be a single value, or a vector, in which case, an ellipsoid will be drawn. The inside of the sphere is set to the specified value. c3d img1.img -sphere 128x128x96vox 5vox 255 -o out.img c3d img1.img -sphere 128x128x96vox 7x7x4mm 128 -o out.img  -split This command takes a multilabel image (one with a small number of discrete intensity levels), and replaces it with a set of binary images, one for each of the levels. The images can later be recombined using the -merge command. The labels corresponding to each binary image are remembered by convert3d so that when -merge is called, the labels are faithfully reassigned. The -merge command treats each input as a probability image, and selects at each voxel the label that has highest probability. The example below smooths each label independently, then recombines using -merge c3d multilabel.nii -split -foreach -smooth 3mm -endfor -merge -o ml_smooth.nii  Also of note is that the -split command will disregard infinite intensity values. So if you want to apply voting to a subset of the labels, you can replace labels you do not care about with inf, for example, using the -thresh command. -sqrt Computes square root of each voxel in the image c3d input.img -sqrt -o output.img  -staple <intensity_value> Runs the STAPLE afgorithm (See Paper). STAPLE generates an estimate of the 'true' segmentation of a structure given a set of segmentations by different raters. This command treats all images on the stack as inputs. Each image is considered to be a segmentation by a different rater. The parameter intensity_value specifies the label in the segmentation images corresponding to the structure of interest (e.g., the segmentation image may have value 1 corresponding to the caudate and value 2 corresponding to the hippocampus. To run STAPLE on the hippocampus, pass in 2 as the intensity_value). The output of STAPLE is a real-valued image with voxels between 0 and 1, representing the probability of each voxel being in the 'true' segmentation. This image can be thresholded to get a binary consensus segmentation. Additional outputs (estimates of the sensitivity and specificity of each rater) are printed out if the -verbose command is used before the -staple command. c3d -verbose rater1.img rater2.img rater3.img -staple 1 -o probmap.img c3d -verbose rater*.img -staple 1 -threshold 0.5 inf 1 0 -o bin_segm.img  -stretch <u1 u2 v1 v2> Stretches the intensities in the image linearly, such that u1 maps to v1 and u2 maps to v2. The linear transformation is applied to all intensities in the image, whether inside the range or not. For example, to map a floating point image with intensities in interval (0,1) to the full range of an unsigned short image, use c3d input.img -stretch 0.0 1.0 0 65535 -type ushort -o output.img  -test-xxx These advanced commands (with more to come in the future) are primarily meant to allow testing of c3d. However, they can also be used for flow control in shell scripts (e.g., bash shell). The commands check a certain aspect of the c3d state and cause the program to exit with either return code 0 if the test succeeded or a non-zero return code if the test failed. The -test-image command The -test-probe' -test-image [test_tolerance] Test if the last two images on the stack are identical (both in terms of data and header). Returns 0 if the images are identical. The optional tolerance parameter has default value 1e-8. c3d input1.img input2.img -test-image  -test-probe vector test_value [test_tolerance] Similar to the -probe command. Test if the value of the last image on the stack at the position given by vector is equal to the test_value. An optional tolerance value may be specified, the default is 1e-8. c3d input1.img -test-probe 40x40x20vox 1.0 1e-6  -tile <tile_spec> Tiles multiple images into a single image -- including stacking slices into a 3D volume. The command takes all images on the stack and produced a single tiled image. The tile_spec parameter can either specify a coordinate axis (x, y, or z) along which to tile the images, or a layout vector (e.g., 4x4) which specifies the tiling along each coordinate. Passing 0 for the last value in the layout vector determines the value based on the number of images currently loaded. For example, to create a 3D volume from a set of slices, we use c3d slices*.png -tile z -o volume.nii.gz  And to arrange the same 2D slices into a 2D montage of 4 images per row, we would use the c2d command as follows: c2d slices*.png -tile 4x0 -type uchar -o montage.png  -threshold, -thresh <u1 u2 vIn vOut> Thresholds the image, setting voxels whose intensity is in the range [u1,u2] to vIn and all other voxels to vOut. Values u1 and u2 are intensity specifications (see below). This means that you can supply values inf and -inf for u1 and u2 to construct a one-sided threshold. You can also specify u1 and u2 as percentiles. c3d in.img -threshold -inf 128 1 0 -o out.img c3d in.img -threshold 64 128 1 0 -o out.img c3d in.img -threshold 20% 40% 1 0 -o out.img  -trim margin_vector Use this command to trim background in an image. When most of the image is filled by background, this command will find the smallest rectangular region that contains all of the non-background voxels in the image. I will then expand this region by the margin of the size specified, and return the resulting region as the new image. For example: # Trim an image, leaving a 5-voxel margin of background values on all sides c3d in.img -trim 5vox -o out.img  -trim-to-size size_vector This command also trims the background in an image. However, instead of -trim, you specify the target size of the output region. The actual region may be smaller if the specified region falls outside the boundaries of the input image. For example, if you want a 64x64x128 image containing all the foreground pixels in your image, call c3d in.img -trim-to-size 64x64x128vox -o out.img  -vote This command takes all images on the stack as arguments and at each voxel (i,j,k) returns the index of the image for which the image value at (i,j,k) is the greatest. This is most useful when combining probability maps into a single label image. If images prob1.img, prob2.img, etc. give the probability of label 1, 2, etc. over the image domain, the -vote command will return the most probable label at each voxel. c3d prob1.img prob2.img prob3.img -vote -type uchar -o label.img  The value assigned to each image is based on its position from the bottom of the stack, with zero indicating bottom-most image. In the example above, the output image has values 0 for voxels where prob1.img is highest, 1 for prob2.img and 2 for prob3.img. Also see the related commands -split and -merge. -voxel-sum Print the sum of all voxels in the image.  c3d image.img -voxel-sum
Voxel Sum: 200923123


-voxel-integral
Same as voxel sum above, but multiplies the result by voxel size. Useful for computing volumes of objects represented by binary images. The result is in 'ml'.
$c3d image.img -voxel-integral Voxel Integral: 2341  -voxelwise-regression order -voxreg order Perform regression between corresponding voxels in two images. This command takes two images as input, X and Y. This command finds parameters b_0, b_1, ..., b_k, such that Y is best approximated by b_0 + b_1 * X + b_2 * X^2 + ... + b_k * X^k. Here is an example of linear regression. $ c3d Y.nii X.nii -voxreg 2
REGCOEFF[0] = 5.56935
REGCOEFF[1] = 0.844024
$c3d Y.nii X.nii -scale 0.844024 -shift 5.56935 -voxreg 2 REGCOEFF[0] = 0 REGCOEFF[1] = 1  -warp Apply a deformation (warp) field to an image. The command expects the X, Y and Z components of the warp field, followed by the image to be warped. The warp field specifies the displacement, in world coordinates, from reference space to the space of the image to be warped. Deformation fields may be generated by registration programs, such as ANTS. c3d mywarpxvec.nii mywarpyvec.nii mywarpzvec.nii moving.nii -warp -o warped.nii  You can also warp multi-label images. One option is to use nearest neighbor interpolation (with the -interpolation option). Often a better option is to warp each label individually and to merge the warped labels with the -split/-merge command. Here is an example (it gets a bit complex, sorry). c3d mywarpxvec.nii mywarpyvec.nii mywarpzvec.nii -popas Z -popas Y -popas X moving.nii -split -foreach -smooth 0.24mm -popas I -push X -push Y -push Z -push I -warp -endfor -merge -o warped.nii  -weighted-sum weight1 weight2 ... weightN -wsum weight1 weight2 ... weightN Computes weighted sum of the last N images on the stack. c3d image1.nii image2.nii image3.nii -wsum 0.2 0.7 0.1 -o wsum.nii  This command is particularly useful for combining components in a multicomponent image. For example, for an RGB image, we can convert it to grayscale (using ImageMagick formula) as follows: c3d -mcs rgb.nii -wsum 0.29900 0.58700 0.11400 -o gray.nii  -weighted-sum-voxelwise -wsv Computes weighted sum of N weight images and N images. c3d weight1.nii image1.nii weight2.nii image2.nii weight3.nii image3.nii -wsv -o mysum.nii.gz  -wrap <vector> Wrap image around one or more voxel dimensions. Wrapping is typically used to correct for MRI wrap-around artifacts. The vector must have integer components, possibly negative. For example, c3d badmri.nii.gz -wrap 0x20x0 -o fixedmri.nii.gz  will wrap the image in the second voxel dimension by 20 voxels (i.e., voxel at 10x40x20 will me moved to the position 10x20x20). ### Options Options change the behavior of commands that appear later on the command line. -background <value> Sets the background intensity for interpolation and other operations where some default background value is needed. Default is 0.0. -interpolation <NearestNeighbor|Linear|Cubic|Sinc|Gaussian> Specifies the interpolation used with -resample and other commands. Default is Linear. Gaussian interpolation takes as the parameter the standard deviation of the Gaussian filter (e.g, 1mm). Gaussian interpolation is very similar in result to first smoothing an image with a Gaussian filter and then reslicing it with linear interpolation, but is more accurate and has less aliasing artifacts. It is also slower, and should only be used with small sigmas (a few voxels across). -mcs, -multicomponent-split -nomcs, -no-multicomponent-split Enable/disable reading of multi-component images. By default, when a multi-component image is encountered, the components are combined into a single image. Setting the -mcs flag changes this behavior, and each of the components is loaded sequentially. See the section below on multi-component image support. $ c3d -mcs rgb.mha -foreach -probe 110x110x80mm -endfor
Interpolated image value at 110 110 80 is 1
Interpolated image value at 110 110 80 is 66
Interpolated image value at 110 110 80 is 29

$c3d rgb.mha -foreach -probe 110x110x80mm -endfor Interpolated image value at 110 110 80 is 49.5198  -noround, -round By default, convert3d will round floating point values when converting to an integer, short or byte image. This command specifies that rounding should not be used. Rounding is used to avoid numerical errors stemming from the internal floating point representation. c3d image1.img -type short -noround image2.img  -percent-intensity-mode Quantile | ForegroundQuantile | Range -pim q | fq | r This options changes how the percent sign (%) is interpreted when specifying intensity values. Quantile means that 10% describes the 10th percentile of all intensity values in the image (i.e., 10% of the voxels have lower intensity). ForegroundQuantile is similar, but voxels with background intensity (see -background option) are excluded from the percentile computation. Range changes the meaning of percent sign from percentile to the range between the minimum and maximum of the image, and 0.1% becomes equal to MIN + 0.1 (MAX - MIN). The default is Quantile. $ c3d comp01.png -verbose -pim Quantile -verbose -threshold 75% inf 1 0
Quantile 0.75 maps to 18

$c3d comp01.png -verbose -pim ForegroundQuantile -verbose -threshold 75% inf 1 0 Foreground quantile 0.75 (over 37467 voxels) maps to 58$ c3d comp01.png -verbose -pim Range -verbose -threshold 75% inf 1 0
Intensity range spec 0.75 maps to 191.25


-spm, -nospm
These options specify whether use the SPM extension to the Analyze (.hdr,.img) format. When this option is on, the origin field stored by SPM in the Analyze header will be correctly interpreted. When saving analyze files, the origin will be set correctly. The default is equivalent to the -nospm option.
c3d -spm in.hdr out.img.gz


-type < char | uchar | short | ushort | int | uint | float | double >
Specifies the pixel type for the output image. By default, images are written in floating point (float) format. The type does not affect how images are processed, only how they are saved.
c3d image1.img -type short image2.img


-verbose
Commands entered after this command will print debugging information.

### Parameter Specifications

vectors
Certain commands, like -smooth, take vectors as parameters. Vectors can be specified in voxels and in spacing units (mm). The following are some examples of allowed specifications:
c3d ... -smooth 1.0x1.2x0.9mm ...             // Anisotropic, specified in mm (spacing units)
c3d ... -smooth 1.0mm                         // Isotropic, specified in mm (spacing units)
c3d ... -smooth 1.0x1.2x0.9vox ...            // Anisotropic, specified in voxels
c3d ... -smooth 3vox                          // Isotropic, specified in voxels


geometry
Geometry specifications are similar to the ones used in ImageMagick. They have the format S1xS2xS3+O1+O2+O3, where S1,S2,S3 give the size of the region and O1,O2,O3 give the offset. The offset can be omitted, and will default to one.
intensity values
Intensity values can be specified as floating point values. Additionally, some commands support values -inf and inf for negative and positive infinity. Furthermore, intensity can be specified as a percentile of overall image intensity (computed in the last image on the convert3d stack). Here are some examples using the -clip command:
c3d ... -clip 100 400                         // Floating point lower and upper bounds
c3d ... -clip -inf 400                        // Infinite lower bound
c3d ... -clip -inf 90%                        // Upper bound specified as a percentile


With the -percent-intensity-mode (shorthand -pim) option, you have fine control over how the percent sign is interpreted when specifying intensities. By default, 10% means 10th percentile of all intensities in the image. With -pim ForegroundQuantile, the quantile is computed only over voxels that are different from the background value (specified with -background option. This is useful if you need a percentile over a masked region of an image, etc. Lastly, with -pim Range, the percent sign changes meaning from percentile to the range between the minimum and maximum of the image, and 0.1% becomes equal to MIN + 0.1 (MAX - MIN).

### File Format Notes

convert3d supports all the file formats that ITK can read and write. In addition it supports some additional formats and format extensions.

.hdr, .img, .img.gz
Analyze files saved in SPM will by default be assigned a zero origin (as ITK does). But with the -spm option passed in before the filename, the origin will be correctly set.
.cub
VoxBo CUB files can be read and written
.df3
PovRay 3D density files can be written. They must be used with integral types (e.g., -type ushort)

### Support for Multicomponent Images

This section discusses images with multiple components, where each voxel contains more than one value. For example color (RGB) images and diffusion tensor images are multi-component images. C3D can read and write multi-component images, but at the present, it can only represent these images internally as separate single-component images.

Use the -mcs flag to tell convert3d that when it encounters a multi-component image file, it should load each of the components as separate images. If you don't use this flag, only the first component of a multi-component image will be read in.

c3d -mcs ...


For example, suppose rgb.mha is a three-component color image. If you read it with the -mcs flag, convert3d will create three volumes, one for the red component, one for the green and one for the blue. You can use the -foreach construct to apply operations to the components. You can then save the components into a multi-component image with the -omc command. Here is an example:

c3d -mcs rgb.mha -foreach -scale 2 -shift 1 -endfor -omc 3 rgbscaled.mha


Here is another example, where we take an RGB image and extract red, green and blue channels.

c3d -verbose rgb.mha -o blue.nii.gz -pop -o green.nii.gz -pop -o red.nii.gz


The components are being saved in reverse order. That's because when the image is read, the red component is placed at the top of the stack, then the green component is placed on the top of the red component, and finally, the blue component is placed at the top of the green component. So the blue component is at the top of the stack. Since convert3d commands like -o apply to the image at the top of the stack, the blue image is saved first, then removed (popped off) the stack, followed by the green and blue components.

With the advent of the -oo command (output multiple images), the command line becomes a little cleaner:

c3d -mcs rgb.mha -oo red.nii.gz green.nii.gz blue.nii.gz


or, if you want to name the component images as comp00.nii.gz, comp01.nii.gz, comp02.nii.gz:

c3d -mcs rgb.mha -oo comp%02d.nii.gz


To create an RGB image from component images, we would use the following command:

c3d red.nii.gz green.nii.gz blue.nii.gz -omc 3 rgb.mha


### Commands with Variable Number of Parameters

Some more recently added commands in c3d take multiple parameters and apply them to multiple images on the stack. As a rule, the last parameter is applied to the topmost image on the stack, the second to last parameter is applied to second from the top image on the stack, and so on.

For example, the -weighted-sum''' command computes a weighted sum of several images:

c3d A.nii B.nii C.nii D.nii -weighted-sum 0.1 0.2 0.3 0.4 -o W.nii


The result of this command will be 0.1 * A + 0.2 * B + 0.3 * C + 0.4 * D. The equivalent way to compute this expression is

c3d A.nii -scale 0.1 B.nii -scale 0.2 -add C.nii -scale 0.3 -add D.nii -scale 0.4 -add -o W.nii


Another example is the -oo command, which allows us to save several images at once.

### How to Add a Command to C3D

This section is for C3D developers. It describes the steps you must typically take to add a new command to C3D. Almost all commands are implemented in an adapter object. An adapter is simply a C++ class that inherits from ConvertAdapter and implements the () operator, where the work of the command is performed. There are many examples of adapters in the adapters directory. Some very simple commands, as well as options, stack manipulation, and flow control commands do not have adapters. We will discuss adding a command that is implemented by an adapter.

1. To add a command to C3D, you should first create an adapter object. To simplify things, we provide a bash script to create a new adapter in the adapters/generator folder. Simply pass in the name of the generator and the parameters to the operator () to the script. For example, if we are adding a command with a single parameter that is a vector, we would call the script as follows:
cd MYDIR/convert3d/adapters/generator
cat MyNewAdapter.cxx                              <- Check that everything is OK


1. Next, you must write the code for the command. Typically, all you have to do now is to fill out the code for the operator (). Please be sure to use the same convention as in other adapters. For example, every adapter should use the *c->verbose stream to report what it's doing and which image it's doing it to. Commands in C3D consume their arguments, so be sure to pop your images off the stack and push your result on the stack. Also be sure to do necessary error checking and fire off ConvertException if parameters or the state of the stack are invalid.
2. Next, you must add your new adapter to the CMakeLists.txt file. That's easy, just look for all the other adapters and insert yours in alphabetical order.
3. Next, edit ConvertImageND.cxx. This is the main application driver and command line processor. At the top of the file, add an #include statement for your new adapter, keeping things in alphabetical order.
4. Staying in ConvertImageND.cxx, insert your new command in the usage() function, again, keeping things in alphabetical order.
5. Still in ConvertImageND.cxx, find the section of the code where commands are implemented. Find where your command fits in alphabetical order, and insert a section of code corresponding to your command. Again, use existing commands as examples. Make sure to return a value - how many parameters your command has consumed from the command line. Otherwise, you will get a "fell through" error message.
6. Almost done. Edit the utilities/bashcomp.sh script and add a line for your command there.
7. Last step: edit this wiki page and document your command.

To summarize, here is a checklist for adding a new command

1. Generate adapter via bash script
2. Write code for operator ()
3. Add line in CMakeLists.txt
4. Add #include line in ConvertImageND.cxx
5. Add usage() line in ConvertImageND.cxx
6. Add code to parse command and call adapter in ConvertImageND.cxx
7. Add line to bashcomp.sh`
8. Document the command on the wiki