46. plugins.imagearray — Convert bitmap images into numpy arrays.

This module contains functions to convert bitmap images into numpy arrays and vice versa. There are functions to read image from file into arrays, and to save image arrays to files. There is even a class that reads a full stack of Dicom images into a 3D numpy array.

Some of this code was based on ideas found on the PyQwt mailing list.

46.1. Classes defined in module plugins.imagearray

class plugins.imagearray.DicomStack(files, zsort=True, reverse=False)[source]

A stack of DICOM images.

Note

This class is only available if you have pydicom installed.

The DicomStack class stores a collection of DICOM images and provides conversion to ndarray.

The DicomStack is initialized by a list of file names. All input files are scanned for DICOM image data and non-DICOM files are skipped. From the DICOM files, the pixel and slice spacing are read, as well as the origin. The DICOM files are sorted in order of ascending origin_z value.

While reading the DICOM files, the following attributes are set:

  • files: a list of the valid DICOM files, in order of ascending z-value.
  • pixel_spacing: a dict with an (x,y) pixel spacing tuple as key and a list of indices of the matching images as value.
  • slice_thickness: a list of the slice thicknesses of the images, in the same order as files.
  • xy_origin: a dict with an (x,y) position the pixel (0,0) as key and a list of indices of the matching images as value.
  • z_origin: a list of the z positions of the images, in the same order as files.
  • rejected: list of rejected files.
class Object[source]

_A dummy object to allow attributes

nfiles()[source]

Return the number of accepted files.

files()[source]

Return the list of accepted filenames

rejected()[source]

Return the list of rejected filenames

pspacing()[source]

Return the pixel spacing and slice thickness.

Return the pixel spacing (x,y) and the slice thickness (z) in the accepted images.

Returns: a float array of shape (nfiles,3).

origin()[source]

Return the origin of all accepted images.

Return the world position of the pixel (0,0) in all accepted images.

Returns: a float array of shape (nfiles,3).

zvalues()[source]

Return the zvalue of all accepted images.

The zvalue is the z value of the origin of the image.

Returns: a float array of shape (nfiles).

zspacing()[source]

Check for constant slice spacing.

spacing()[source]

Return uniform spacing parameters, if uniform.

image(i)[source]

Return the image at index i

pixar(raw=False)[source]

Return the DicomStack as an array

Returns all images in a single array. This is only succesful if all accepted images have the same size.

46.2. Functions defined in module plugins.imagearray

plugins.imagearray.image2array(filename, mode=None, flip=True)[source]

Read an image file into a numpy array.

Parameters:
  • filename (path_like) – The name of the file containing the image.
  • mode (str, optional) – If provided, the image will be converted to the specified mode. The mode is a string defining the color channels to be returned. Typical values are ‘1’ (black/white), ‘L’ (grayscale), ‘LA’ (gray with alpha), ‘RGB’ (three colors), ‘RGBA’ (three colors plus alpha). Default is to return the image as it is stored.
  • flip (bool) – If True, the vertical axis will be inverted. This is the default, because image scanlines are stored from top to bottom, while opengl uses a vertical axis running from bottom to top. Set this to False when using images as fonts in FontTexture, because the FontTexture engine itself takes account of the top-down image storage.
plugins.imagearray.array2image(ar, filename)[source]

Save an image stored in a numpy array to file.

Parameters:
  • ar (array) – Array holding the pixel data. This is typically an Int8 type array with shape (height, width, 3) where the last axis holds the RGB color data.
  • filename (path_like) – The name of the file where the image is to be saved.
plugins.imagearray.resizeImage(image, w=0, h=0)[source]

Load and optionally resize a QImage.

Parameters:
  • image (qimage_like) – QImage, or data that can be converted to a QImage, e.g. the name of a raster image file.
  • w (int, optional) – If provided and >0, the image will be resized to this width.
  • h (int, optional) – If provided and >0, the image will be resized to this height.
Returns:

QImage – A QImage with the requested size (if provided).

plugins.imagearray.qimage2numpy(image, resize=(0, 0), order='RGBA', flip=True, indexed=None)[source]

Transform a QImage to a numpy.ndarray.

Parameters:
  • image (qimage_like) – A QImage or any data that can be converted to a QImage, e.g. the name of an image file, in any of the formats supported by Qt. The image can be a full color image or an indexed type. Only 32bit and 8bit images are currently supported.
  • resize (tuple of ints) – A tuple of two integers (width,height). Positive value will force the image to be resized to this value.
  • order (str) – String with a permutation/subset of the characters ‘RGBA’, defining the order in which the colors are returned. Default is RGBA, so that result[…,0] gives the red component. Note however that QImage stores in ARGB order. You may also specify a subset of the ‘RGBA’ characters, in which case you will only get some of the color components. An often used value is ‘RGB’ to get the colors without the alpha value.
  • flip (bool) – If True, the image scanlines are flipped upside down. This is practical because image files are usually stored in top down order, while OpenGL uses an upwards positive direction, requiring a flip to show the image upright.
  • indexed (bool or None.) –

    If True, the result will be an indexed image where each pixel color is an index into a color table. Non-indexed image data will be converted.

    If False, the result will be a full color array specifying the color of each pixel. Indexed images will be expanded to a full color array.

    If None (default), no conversion is done and the resulting data are dependent on the image format. In all cases both a color and a colortable will be returned, but the latter will be None for non-indexed images.

Returns:

  • colors (array) – An int8 array with shape (height,width,ncomp), holding the components of the color of each pixel. Order and number of components is as specified by the order argument. The default is 4 components in order ‘RGBA’.

    This value is only returned if the image was not an indexed type or if indexed=False was specified, in which case indexed images will be converted to full color.

  • colorindex (array) – An int array with shape (height,width) holding color indices into colortable, which stores the actual color values.

    This value is only returned if the image was an indexed type or if indexed=True was specified, in which case nonindexed images will be converted to using color index and table.

  • colortable (array or None.) – An int8 array with shape (ncolors,ncomp). This array stores all the colors used in the image, in the order specified by order

    This value is only returned if indexed is not False. Its value will be None if indexed is None (default) and the image was not indexed.

Notes

This table summarizes the return values for each of the possible values of the indexed argument combined with indexed or nonindexed image data:

arg non-indexed image indexed image
indexed=None colors, None colorindex, colortable
indexed=False colors colors
indexed=True colorindex, colortable colorindex, colortable
plugins.imagearray.numpy2qimage(array)[source]

Convert a 2D or 3D integer numpy array into a QImage

Parameters:array (2D or 3D int array) – If the input array is 2D, the array is converted into a gray image. If the input array is 3D, the last axis should have length 3 or 4 and represents the color channels in order RGB or RGBA.

Notes

This is equivalent to calling gray2qimage() for a 2D array and rgb2qimage() for a 3D array.

plugins.imagearray.gray2qimage(gray)[source]

Convert a 2D numpy array to gray QImage.

Parameters:gray (uint8 array (height,width)) – Array with the grey values of an image with size (height,width).
Returns:QImage – A QImage with the corresponding gray image. The image format will be indexed.
plugins.imagearray.rgb2qimage(rgb)[source]

Convert a 3D numpy array into a 32-bit QImage.

Parameters:rgb (int array (height,width,ncomp)) – Int array with the pixel values of the image. The data can have 3 (RGB) or 4 (RGBA) components.
Returns:QImage – A QImage with size (height,width) in the format RGB32 (3 components) or ARGB32 (4 components).
plugins.imagearray.qimage2glcolor(image, resize=(0, 0))[source]

Convert a bitmap image to corresponding OpenGL colors.

Parameters:
  • image (qimage_like) – A QImage or any data that can be converted to a QImage, e.g. the name of an image file, in any of the formats supported by Qt. The image can be a full color image or an indexed type. Only 32bit and 8bit images are currently supported.
  • resize (tuple of ints) – A tuple of two integers (width,height). Positive value will force the image to be resized to this value.
Returns:

float array (w,h,3) – Array of float values in the range 0.0 to 1.0, containing the OpenGL colors corresponding to the image RGB colors. By default the image is flipped upside-down because the vertical OpenGL axis points upwards, while bitmap images are stored downwards.

plugins.imagearray.removeAlpha(qim)[source]

Remove the alpha component from a QImage.

Directly saving a QImage grabbed from the OpenGL buffers always results in an image with transparency. See https://savannah.nongnu.org/bugs/?36995 .

This function will remove the alpha component from the QImage, so that it can be saved with opaque objects.

Note: we did not find a way to do this directly on the QImage, so we go through a conversion to a numpy array and back.

plugins.imagearray.saveGreyImage(a, f, flip=True)[source]

Save a 2D int array as a grey image.

Parameters:
  • a (int array) – Int array (height,width) with values in the range 0..255. These are the grey values of the pixels.
  • f (str) – Name of the file to write the image to.
  • flip (bool) – If True (default), the vertical axis is flipped, so that images are stored starting at the top. If your data already have the vertical axis downwards, use flip=False.

Note

This stores the image as an RGB image with equal values for all three color components.

plugins.imagearray.dicom2numpy(files)[source]

Easy conversion of a set of dicom images to a numpy array.

Parameters:files (list of path_like) – List of file names containing the subsequent DICOM images in the stack. The file names should be in the correct order.
Returns:
  • pixar (int array (nfiles, height, width)) – Pixel array with the nfiles images.
  • spacing