mippy.viewing

This module contains the key image viewing/displaying classes and functions in MIPPY. If you want to work with images on a canvas, this is probably the right place to look.

ImageFlipper (Class)

class mippy.viewing.ImageFlipper(master, canvas)

Toolbar for performing simple flip/rotate functions on images on an instance of MIPPYCanvas. Extends tkinter.Frame.

The toolbar has 4 buttons:

  • Rot R (Rotate clockwise 90 degrees)
  • Rot L (Rotate anti-clockwise 90 degrees)
  • Flip H (Reflect through a vertical line down the center of the image)
  • Flip V (Reflect through a horzontal like across the center of the image)

Functions are designed to be invoked by buttons, but could theoretically be invoked with a direct call.

Parameters:
  • master (tkinter widget) – Master object for displaying the widget (usually a tkinter.Frame instance)
  • canvas (mippy.viewing.MIPPYCanvas) – MIPPYCanvas object you want the ImageFlipper toolbar to work with.
flip_h()

Reflects the images about a central vertical axis.

flip_v()

Reflects the images about a central horizontal axis.

rot_left()

Rotates the images through 90 degrees anticlockwise.

rot_right()

Rotates the images through 90 degrees clockwise.

MIPPYCanvas (Class)

class mippy.viewing.MIPPYCanvas(master, width=256, height=256, bd=0, drawing_enabled=False, autostats=False, antialias=True, use_masks=True)

MIPPYCanvas is an extension of tkinter.Canvas with additional functionality for working with DICOM images and region-of-interest based image analysis.

Parameters:
  • master (tkinter object) – The tkinter object which will hold the canvas (typically a tkinter.Frame)
  • width (int, optional) – The on-screen width of the canvas in pixels (default = 256)
  • height (int, optional) – The on-screen height of the canvas in pixels (default = 256)
  • bd (int, optional) – Canvas border width (default = 0)
  • drawing_enabled (bool, optional) – Specifies whether the canvas interacts with left-mouse clicks for ROI drawing (default = False)
  • autostats (bool, optional) – If True, ROI stats will be printed to stdout immediately whenever an ROI is drawn. (default = False)
  • antialias (bool, optional) – If True, antialiasing will be applied when scaling images for display. (default = True)
  • use_masks (bool, optional) – If True, binary ROI masks will be generated whenever an ROI is drawn/updated. This makes it slower to generate the ROI, but much faster to perform stats/analysis on the ROI. (default = True)
Variables:
  • active (int) – The number of the currently displayed image, indexed from 1 (initial value: 1)
  • active_str (tkinter.StringVar) – tkinter.StringVar instance of MIPPYCanvas.active (so that image number can be displayed in a tkinter.Label)
  • antialias (bool) – If True, antialiasing will be applied when scaling images for display (intial value from Constuctor)
  • autostats (bool) – If True, ROI stats will be printed to stdout immediately whenever an ROI is drawn (intial value from Contructor)
  • drawing_enabled (bool) – Specifies whether the canvas interacts with left-mouse clicks for ROI drawing (intial value from Constructor)
  • images (list) – The list of mippy.viewing.MIPPYImage objects currently loaded on the MIPPYCanvas (initial value: [ ])
  • height (int) – Height of the canvas in pixels (intial value from Constructor)
  • last_clicked (datetime.datetime) – The timestamp of the last time the canvas was drawn on using the left mouse button (initial value: datetime.datetime.now())
  • master (tkinter.Frame) – The master tkinter widget on which the canvas is displayed
  • roi_list (list) – List of mippy.viewing.ROI objects currently active on the displayed image (initial value: [ ])
  • roi_list_2d (list) – 2D list of mippy.viewing.ROI objects currently active on all loaded images (initial value: [ [ ] ])
  • roi_mode (str) – The currently active ROI drawing mode (inital value: ‘rectangle’)
  • use_masks (bool) – If True, binary ROI masks will be generated whenever an ROI is drawn/updated. This makes it slower to generate the ROI, but much faster to perform stats/analysis on the ROI. (intial value from Constructor)
  • width (int) – Width of the canvas in pixels (intial value from Constructor)
  • zoom_factor (float) – The scaling factor applied to the raw pixel data for display on the MIPPYCanvas (initial value: 1)
add_roi(coords, tags=['roi'], roi_type=None, color='yellow')

Generates the mippy.viewing.ROI object and updates the canvas ROI lists.

Usually called as part of MIPPYCanvas.new_roi().

Parameters:
  • coords (list(tuple)) – List of (x,y) coordinate tuples
  • tags (list(str), optional) – List of tags to be applied to the ROI. For useful tags, see Useful tags. (default = [‘roi’])
  • roi_type (str, optional) – ROI type; can be ‘rectangle’,’ellipse’,’freehand’,’line’. If None specified, it will be automatically determined from the coordinates provided. (default = None)
  • color (str, optional) – Color of the ROI to be displayed on the canvas; must be a color recognised by tkinter (default = ‘yellow’)
canvas_coords(image_coords, zoom=None)

Converts image coordinates to canvas coordinates (determined by size of the canvas).

Parameters:
  • image_coords (list(tuple)) – List of (x,y) image coordinate tuples
  • zoom (float, optional) – Zoom factor to use. If None is specified (as should be done generally) the current MIPPYCanvas.zoom_factor is used. (default = none)
Returns:

new_coords – List of (x,y) coordinate tuples of transformed coordinates.

Return type:

list(tuple)

configure_scrollbar()

This method expects that a tkinter Scrollbar object has been created as the attribute img_scrollbar. It needs to be run after the scrollbar is created to establish the link between the scrollbar and the canvas.

Although the scrollbar is created as an attribute of the canvas, you will need to specify the window/frame you want the scrollbar to appear on as its master when you construct it.

Example:

my_window.canvas1 = MIPPYCanvas(my_window)
my_window.canvas1.img_scrollbar = Scrollbar(my_window, orient='horizontal')
my_window.canvas1.configure_scrollbar()
delete_rois()

Deletes all objects with the tag ‘roi’ on the canvas.

draw_ellipse_roi()

Enables drawing on the MIPPYCanvas object and sets the active ROI mode to ‘ellipse’

draw_freehand_roi()

Enables drawing on the MIPPYCanvas object and sets the active ROI mode to ‘freehand’

draw_line_roi()

Enables drawing on the MIPPYCanvas object and sets the active ROI mode to ‘line’

draw_rectangle_roi()

Enables drawing on the MIPPYCanvas object and sets the active ROI mode to ‘rectangle’

draw_roi(coords, tags=[], color='yellow')

Draw the ROI defined by its bounding coordinates on the canvas. The tags can be used to define the ROI appearance (e.g. dashed borders, stippled appearance).

Please see Useful tags for more information.

Parameters:
  • coords (list(tuple)) – Coordinates as a list of (x,y) tuples defining the boundary of the ROI
  • tags (list(str), optional) – List of tags to be attached to the ROI; can be used to define the appearance of the ROI or select ROIs for statistics/analysis (default = [ ])
  • color (str, optional) – Color of the ROI (default = ‘yellow’)
get_3d_array()

If all images on the canvas are of the same dimensions, this returns the pixel data of the whole image stack as a 3-dimensional numpy.ndarray.

Warning

The axes of this array may seem counter-intuitive to those less familiar with the python concept of ‘slicing’.

  • Axis 0 = image number (z)
  • Axis 1 = row number (y)
  • Axis 2 = column number (x)

So you would reference pixel (100,250) in your 7th image as:

px_data = my_canvas.get_3d_array()
# Either of the below are acceptable
val = px_data[6][250][100]
val = px_data[6,250,100]
Returns:px_array – 3-dimensional array of pixel data.
Return type:numpy.ndarray
get_active_image()

Returns the mippy.viewing.MIPPYImage object for the image currently being displayed.

Returns:image
Return type:mippy.viewing.MIPPYImage
get_profile(resolution=1, width=1, interpolate=False, direction='horizontal', index=0)

Returns a line profile from the image, with interpolation when required.

Parameters:
  • resolution (float, optional) – The spacing between points in the profile, measured in pixels (default = 1)
  • width (int, optional) – The width of the profile that should be averaged across, in pixels. Only applies with a ‘line’ ROI type. (default = 1)
  • interpolate (bool, optional) – Whether or not interpolation should be performed. If False, nearest neighbour pixel values are taken. If true, bilinear interpolation is used. False is not recommended when using resolutions <1. (default = False)
  • direction (str, optional) – Only applies when using a ‘rectangle’ ROI ‘horizontal’ or ‘vertical’. If ‘horizontal’, pixels are averaged vertically to form a 1D profile. If ‘vertical’, the opposite applies. (default = ‘horizontal’)
  • index (int, optional) – The ROI to be used for the profile, with index representing the position in MIPPYCanvas.roi_list. (default = 0)
Returns:

  • profile (numpy.ndarray) – 1D numpyndarray of the values in the profile
  • x (numpy.ndarray) – 1D numpy.ndarray of the length (x) position of each point in the profile, in pixels

get_roi_pixels(rois=[], tags=[])

Returns a LIST of pixel values from an ROI. This list has no shape, and needs converting to a numpy.ndarray to be able to do any useful stats on it.

Parameters:
  • rois (list(int), optional) – List of indices. If specified, only the specified positions in MIPPYCanvas.roi_list will be analysed.
  • tags (list(str), optional) – List of tags. If specified, only ROIs with any of the specified tags will be analysed.
Returns:

px_list – 1D list of pixel values

Return type:

list

get_roi_statistics(rois=[], tags=[])

Returns some statistics from ROIs on the canvas. The stats are returned as a dictionary, where each key contains the values per-ROI as a list.

Available stats (use these as dictionary keys, as shown in the example):

  • mean (mean value)
  • min (minimum value)
  • max (maximu value)
  • std (standard deviation)
  • mode (modal value)
  • skewness (skewness of the distribution)
  • kurtosis (kurtosis of the distribution)
  • cov (coefficient of variation)
  • sum (sum of all values)
  • area_px (number of pixels within the ROI)

Example:

stats = my_window.canvas1.get_roi_statistics()

# To get the mean of the first ROI...
val = stats['mean'][0]
Parameters:
  • rois (list(int), optional) – List of indices. If specified, only the specified positions in MIPPYCanvas.roi_list will be analysed.
  • tags (list(str), optional) – List of tags. If specified, only ROIs with any of the specified tags will be analysed.
Returns:

stats – Results as a dictionary

Return type:

dict

image_coords(canvas_coords, zoom=None)

Converts canvas coordinates (determined by the size of the canvas relative to the image) to the coordinates within the image frame of reference.

Parameters:
  • canvas_coords (list(tuple)) – List of (x,y) canvas coordinate tuples
  • zoom (float, optional) – Zoom factor to use. If None is specified (as should be done generally) the current MIPPYCanvas.zoom_factor is used. (default = none)
Returns:

new_coords – List of (x,y) coordinate tuples of transformed coordinates.

Return type:

list(tuple)

load_images(image_list, keep_rois=False, limitbitdepth=False)

Loads images onto the canvas, autoscaling pixel values where appropriate and automatically windowing to the full range of pixel values provided.

mippy.viewing.MIPPYImage objects will be created for all images passed in, which are added to MIPPYCanvas.images (a list).

There is a hard-coded limit of 500 images that can be loaded onto the canvas. If you attempt to load a list of images longer than 500, only the first 500 will be displayed.

Note

The image_list object must be a 1D list of objects. These objects can be:

  • pydicom.Dataset.Dataset or pydicom.Dataset.FileDataset
  • str absolute paths to DICOM files on the disk
  • 2-dimensional numpy.ndarray objects of pixel data to be loaded directly onto the canvas.
Parameters:
  • image_list (list) – List of images to be loaded. See the note above for allowed object types.
  • keep_rois (bool, optional) – If True, any ROIs present on the canvas will be preserved if the image geometry (slices, height, width) is the same as the currently loaded images. (default = False)
  • limitbitdepth (bool, optional) – If True, all pixels will be automatically scaled to 8-bit integer values in order to limit memory usage and speed up image loading. This is used in the preview window in the main MIPPY GUI. (default = False)
load_multislice_rois(loadpath=None)

Loads all ROIs from a file to all open slices. If you want to load ROIs across multiple slices, loop the function yourself.

Parameters:loadpath (str, optional) – The absolute path at with which the ROI set is saved. If no path is provided, a load file dialog box is opened to generate the path. (default = None)
load_rois(loadpath=None)

Loads all ROIs from am roipickle file to the current active image only. If you want to load ROIs across multiple slices, loop the function yourself.

Parameters:loadpath (str, optional) – The absolute path at with which the ROI set is saved. If no path is provided, a load file dialog box is opened to generate the path. (default = None)
new_roi(coords, tags=[], system='canvas', color='yellow')

Generates a new ROI from a set of coordinates. Coordinates can be in ‘canvas’ coordinates or ‘image’ coordinates.

Usually called from within MIPPY rather than being invoked directly. For easier ways of generating ROIs programmatically, see roi_rectangle, roi_circle and roi_ellipse.

Tags can be used to define the ROI appearance (e.g. dashed borders, stippled appearance). Please see Useful tags for more information.

Parameters:
  • coords (list(tuple)) – List of (x,y) tuple coordinates defining the boundary of the ROI in a clockwise direction.
  • tags (list(str), optional) – List of tags for the ROI. The tags can be used to identify the ROI at a later date. 'roi' is always appended to this list, so all ROIs have the tag 'roi'. (default = [ ])
  • system (str, optional) – Either 'canvas' or 'image' to identify the coordinate system/reference used for coords. (default = ‘canvas’)
  • color (str, optional) – Color in which the ROI will be drawn - must be understood by tkinter (default = ‘yellow’)
progress(percentage)

If there is a progress bar on the master canvas, this will update the progressbar to the percentage specified. If the progressbar object cannot be found, this method will simply pass without throwing an error.

Parameters:percentage (float) – Percentage value (between 0 and 100) to which the progress bar should update
quick_redraw_image()

Does a quick redraw of the image layer on the canvas without recalculating the PhotoImage or any other objects, intended only to force the canvas to update.

redraw_rois()

Redraws all ROIs on the active slice without redrawing the image.

reset()

Unloads all images from the canvas.

Note

Does not automatically remove ROIs from the list, they are only removed when a new set of images are loaded with MIPPYCanvas.load_images().

reset_window_level()

Resets the window/level of the canvas to the full range of pixel values loaded.

roi_circle(center, radius, tags=[], system='canvas', resolution=128, color='yellow')

Adds a circular ROI to the image.

Parameters:
  • center (tuple) – (x,y) coordinate of the center of the circle
  • radius (float) – Radius of the ROI
  • tags (list(str), optional) – Tags to be added to the ROI (default = [ ]) - Useful tags
  • system (str, optional) – Coordinate system being used for coordinates provided; ‘canvas’ or ‘image’ (default = ‘canvas’)
  • color (str, optional) – Color of the ROI; must be understandable by tkinter (default = ‘yellow’)
roi_ellipse(center, radius_x, radius_y, tags=[], system='canvas', resolution=128, color='yellow')

Adds a circular ROI to the image.

Parameters:
  • center (tuple) – (x,y) coordinate of the center of the circle
  • radius_x (float) – Semi-axis of the ellipse in the X direction
  • radius_y (float) – Semi-axis of the ellipse in the Y direction
  • tags (list(str), optional) – Tags to be added to the ROI (default = [ ]) - Useful tags
  • system (str, optional) – Coordinate system being used for coordinates provided; ‘canvas’ or ‘image’ (default = ‘canvas’)
  • resolution (int, optional) – Number of points used to describe one half of the ROI boundary (default = 128)
  • color (str, optional) – Color of the ROI; must be understandable by tkinter (default = ‘yellow’)
roi_rectangle(x_start, y_start, width, height, tags=[], system='canvas', color='yellow')

Adds a rectangular ROI to the image.

Parameters:
  • x_start (float) – X-coordinate of the top-left corner of the ROI
  • y_start (float) – Y-coordinate of the top-left corner of the ROI
  • width (float) – Width of the ROI
  • height (float) – Height of the ROI
  • tags (list(str), optional) – Tags to be added to the ROI (default = [ ]) - Useful tags
  • system (str, optional) – Coordinate system being used for coordinates provided; ‘canvas’ or ‘image’ (default = ‘canvas’)
  • color (str, optional) – Color of the ROI; must be understandable by tkinter (default = ‘yellow’)
save_multislice_rois(savepath=None)

Saves all ROIs from all slices as a single file.

Parameters:savepath (str, optional) – The absolute path at with which the ROI set should be saved. If no path is provided, a save file dialog box is opened to generate the path. (default = None)
save_rois(savepath=None)

Saves all ROIs from the current active image only. If you want to save all ROIs across all slices, loop the function yourself.

Parameters:savepath (str, optional) – The absolute path at with which the ROI set should be saved. If no path is provided, a save file dialog box is opened to generate the path. (default = None)
set_window_level(window, level)

Programatically set a new window and level value rather than using mouse interaction.

Parameters:
  • window (float) – The width of the window
  • level (float) – The center value of the window
show_image(num=None)

Display the requested image.

Parameters:num (int) – The required image number, indexed from 1.

MIPPYImage (Class)

class mippy.viewing.MIPPYImage(dicom_dataset, limitbitdepth=False)

The purpose of MIPPYImage is to have a single object which handles everything required to make images viewable on a Canvas. It keeps and updates an Image.Image and ImageTk.PhotoImage object, the actual pixel values as px_float, and a few other useful functions to do with image rotation/flipping etc.

Note

This is currently very MRI-specific, and will not work with other DICOM objects. The intention is to generalise this further and remove some of the dependency on e.g. InPlanePhaseEncodingDirection, which will happen in a future version of MIPPY.

Parameters:
  • dicom_dataset (pydicom.Dataset.Dateset / pydicom.Dataset.FileDataset / numpy.ndarray / str) – The ‘image’ object to be loaded. This can be a pydicom-loaded DICOM object, an array of pixel values, or a path to a DICOM file.
  • limitbitdepth (bool, optional) – If True, it limits the bitdepth of px_float to 8-bit integers. Pixel values are scaled to fit this, so will no longer be representative of the ‘true’ pixel value. Recommended for use with e.g. reference images/landmarking images where pixel values are unimportant in order to reduce memory burden. (default = False)
Variables:
  • px_float (numpy.ndarray) – 2D pixel value array, indexed as [row,col] or [y,x]
  • flip_h (int) – Number of times image has been flipped horizontally since loading. (initial value: 0)
  • flip_v (int) – Number of times image has been flipped vertically since loading (initial value: 0)
  • rotations (int) – Number of 90-degree rotations the image has been through relative to orientation when loaded. Positive values indicate a clockwise rotation. (initial value: 0)
  • rs (float) – Rescale slope (initial value: from DICOM if present, 1 if not)
  • ri (float) – Rescale intercept (initial value: from DICOM if present, 1 if not)
  • ss (float) – Reciprocal scaling factor, specific to Philips images (initial value: from DICOM if present, None if not)
  • rows (int) – Number of rows in image (inital value: from DICOM/pixel array)
  • columns (int) – Number of columns in image (inital value: from DICOM/pixel array)
  • rangemax (float) – Maximum possible value in MIPPYImage.px_float (taking account of bitdepth and rescaling)
  • rangemax – Minimum possible value in MIPPYImage.px_float (taking account of bitdepth and rescaling)
  • image_position (tuple) – Position of pixel [0,0] in 3D space relative to patient/isocenter (initial value: from DICOM if available, None if not)
  • image_orientation (tuple) – 6-tuple representing the unit vectors for X and Y axes of images (initial value: from DICOM if available, None if not)
  • pe_direction (str) – Phase-encoding direction, specific to MRI. Allowed values are 'ROW' or 'COL'. (initial value: from DICOM, if available, None if not)
  • pixel_bandwidth (float) – The pixel bandwidth in Hz, MRI-specific (initial value: from DICOM if available, None if not)
  • xscale (float) – The spacing of pixels in the X direction in mm (initial value: from DICOM if available, 1 if not)
  • yscale (float) – The spacing of pixels in the Y direction in mm (initial value: from DICOM if available, 1 if not)
  • overlay (numpy.ndarray) – Bitmap overlay for the image (inital value: from DICOM if available, None if not)
  • image (PIL.Image.Image) – PIL/pillow Image object generated from the windowed pixel values (initial value: None)
  • photoimage (PIL.ImageTk.PhotoImage) – The final representation of data that can be loaded onto the canvas (initial value: None)
flip_horizontal()

Flips/reflects the image about a central vertical axis. Only intended to be called using a mippy.viewing.ImageFlipper toolbar object.

Note

The MIPPYImage.image and MIPPYImage.photoimage are not regenerated as part of this method. It is expected that MIPPYCanvas will trigger this.

flip_vertical()

Flips/reflects the image about a central horizontal axis. Only intended to be called using a mippy.viewing.ImageFlipper toolbar object.

Note

The MIPPYImage.image and MIPPYImage.photoimage are not regenerated as part of this method. It is expected that MIPPYCanvas will trigger this.

get_pt_coords(image_coords)

Converts image coordinates (x,y) into a 3D-coordinate representing the location of that point in 3D space.

Deprecated since version 2.0: These transformations should now always be handled using the get_voxel_location and get_img_coords methods in mippy.mdicom.pixel.

resize(dim1=256, dim2=256, antialias=True)

Resizes the MIPPYImage.image and MIPPYImage.photoimage objects that are displayed on the canvas.

Note

No transformation of the actual pixel data is performed; this only updates the display image.

Parameters:
  • dim1 (int, optional) – Dimension 1 (usually X) in pixels for the resized display image (default = 256)
  • dim2 (int, optional) – Dimension 2 (usually Y) in pixels for the resized display image (default = 256)
  • antialias (bool, optional) – Specify if antialiasing should be used when resizing the image (default = True)
rotate_left()

Rotates the image anti-clockwise by 90-degrees. Only intended to be called using a mippy.viewing.ImageFlipper toolbar object.

Note

The MIPPYImage.image and MIPPYImage.photoimage are not regenerated as part of this method. It is expected that MIPPYCanvas will trigger this.

rotate_right()

Rotates the image clockwise by 90-degrees. Only intended to be called using a mippy.viewing.ImageFlipper toolbar object.

Note

The MIPPYImage.image and MIPPYImage.photoimage are not regenerated as part of this method. It is expected that MIPPYCanvas will trigger this.

wl_and_display(window=None, level=None, zoom=None, antialias=True)

Generates the MIPPYImage.image and MIPPYImage.photoimage objects for the specified window and level. If no window and level are specified, it defaults to the maximum/minimum of the dynamic range of the image.

It is not usually necessary to invoke this function - it is primarily used by MIPPYCanvas and MIPPYImage to control the interaction with the mouse.

To set your own window/level programmatically, use MIPPYCanvas.set_window_level.

Parameters:
  • window (float, optional) – Width of the window applied to the pixel values for display
  • level (float, optional) – Center of the window applied to the pixel values for display
  • zoom (float, optional) – Zoom-factor to be used when generating the Image and PhotoImage objects, usually taken from the canvas. If not provided, existing image size is used by default.
  • antialias (bool, optional) – Specify whether antialiasing is to be used when generating the Image object. This is usually specified by the MIPPYCanvas object.
zoom(zoom, antialias=True)

Resizes the MIPPYImage.image and MIPPYImage.photoimage objects that are displayed on the canvas.

Note

No transformation of the actual pixel data is performed; this only updates the display image.

Parameters:
  • zoom (float) – Zoom factor (relative to size of MIPPYImage.px_float) to be used when rescaling the image
  • antialias (bool, optional) – Specify if antialiasing should be used when resizing the image (default = True)

ROI (Class)

class mippy.viewing.ROI(coords, tags=[], roi_type=None, color='yellow')

Region of interest objects in MIPPY, as stored in MIPPYCanvas.roi_list and MIPPYCanvas.roi_list_2d

Parameters:
  • coords (list(tuple)) – list of tuple (x,y) coordinates defining the boundary of the ROI
  • tags (list(str), optional) – List of string objects used to ‘tag’ the ROI on the canvas. The list will always have the string ‘roi’ appended so ROI objects are ALWAYS tagged ‘roi’. (default = [])
  • roi_type (str, optional) – Specifies the type of ROI for easier processing later on. If omitted, the type is established as best as possible from the ROI coordinates. (default = None)
  • color (str, optional) – The color the ROI should appear on a MIPPYCanvas. Colors must be understood by tkinter. (default = ‘yellow’)
contains(point)

Tests whether a point (x,y) is inside or outside of the ROI object.

Parameters:point (tuple) – (x,y) coordinate of the point of interest
Returns:True or False
Return type:bool
update(xmove=0.0, ymove=0.0)

Move an ROI by a specified distance in the X and Y directions (updating the ROI coordinates). One, both or neither distance may be specified.

Note

This does not redraw the ROI on a canvas, it only updates the ROI coordinates. The canvas/ROI must be redrawn to update on screen.

Parameters:
  • xmove (float, optional) – The distance moved in the X direction (positive or negative)
  • ymove (float, optional) – The distance moved in the Y direction (positive or negative)

Functions

mippy.viewing.bits_to_ndarray(bits, shape)

Converts an 8-bit byte string of 1-bit pixel data into a numpy.ndarray of ones and zeros.

Parameters:
  • bits (bytes) – Byte-string containing the 1-bit pixel data
  • shape (tuple) – The desired output shape as (rows,columns)
Returns:

bitmap – Binary pixel data of the required shape

Return type:

numpy.ndarray

mippy.viewing.generate_px_float(pixels, rs, ri, ss=None)

Takes a numpy.ndarray of unscaled integer pixel values (typically 16 bit) and applies the relevant scaling factors from the DICOM header to generate the correct rescaled pixel values.

Parameters:
  • pixels (numpy.ndarray) – The unscaled integer pixel data
  • rs (float) – Rescale slope
  • ri (float) – Rescale intercept
  • ss (float, optional) – Additional reciprocal scaling factor (typically used in Philips images to get ‘real world’ values.
Returns:

px_float – N-dimensional array of scaled pixel values. The shape of the output array matched the shape of the input array.

Return type:

numpy.ndarray

mippy.viewing.get_ellipse_coords(center, a, b, n=128)

Returns an array of the bounding coordinates for an ellipse with “radii” (more correct term??) of a and b. Takes “n” angular rays through 180 degrees and determines intersections of rays with perimeter of ellipse. Coordinates are tuples, returns coordinates as a list going clockwise from top center.

Based on http://mathworld.wolfram.com/Ellipse-LineIntersection.html

Parameters:
  • center (tuple) – Center coordinate (x,y)
  • a (float) – Semi-axis length in X direction (like ‘X radius’)
  • b (float) – Semi-axis length in Y direction (like ‘Y radius’)
  • n (int, optional) – Number of rays to use in the calculation. The number of coordinates returned around your ellipse will be 2*n. More rays = finer resolution = ‘curvier’ ellipse. However, this takes longer to compute! Consider going smaller for smaller ellipses. (default = 128)
Returns:

coords – List of (x,y) coordinate tuples

Return type:

list

mippy.viewing.get_global_min_and_max(image_list)

Takes a list of MIPPYImage objects and returns the minimum and maximum pixel value from the whole list.

Parameters:image_list (list) – 1D list of MIPPYImage objects, as found in MIPPYCanvas.image_list
Returns:
  • min (float) – Minimum pixel value
  • max (float) – Maximum pixel value
mippy.viewing.get_overlay(ds)

Given a Pydicom dataset, this extracts and returns the 1-bit bitmap overlay as a 2D numpy.ndarray containing values of 0 or 255.

If it exists, this bitmap exists in Siemens MRI data as tag (6000,3000).

Parameters:ds (pydicom.Dataset.Dataset or pydicom.Dataset.FileDataset) – Pydicom dataset from which the overlay (6000,3000) should be extracted
Returns:overlay – 2D array of 8-bit integer values
Return type:numpy.ndarray
mippy.viewing.px_bytes_to_array(byte_array, rows, cols, bitdepth=16, mode='littleendian', rs=1, ri=0, ss=None)

Takes a byte-string of pixel value (as in PixelData from a DICOM instance), and converts to a numpy.ndarray of float values.

Parameters:
  • byte array (bytes) – Byte-string of PixelData
  • rows (int) – Number of rows in the image
  • cols (int) – Number of columns in the image
  • bitdepth (int, optional) – Bit-depth of your byte array (default = 16)
  • mode (str, optional) – ‘Endedness’ of your byte array (default = ‘littleendian’)
  • rs (float, optional) – Rescale slope for the pixel values (default = 1)
  • ri (float, optional) – Rescale intercept for the pixel values (default = 0)
  • ss (float, optional) – Additional reciprocal scaling factor often found in Philips images (default = None)
Returns:

px_float – 2D array of 64-bit float values

Return type:

numpy.ndarray

mippy.viewing.quick_display(im_array, master_window)

Given a 2D or 3D numpy.ndarray, opens a new window and displays the image(s) on a new 256x256 image canvas. Bit of a quick and dirty function, but occasionally useful.

Requires an existing Tk instance to use as a master for the window.

Parameters:
  • im_array (numpy.ndarray) – 2D array of pixel values
  • master_window (tkinter object) – Open/running tkinter instance or widget