Class CAAMShape


  • public class CAAMShape
    extends CDVector
    This is the Java modified version of C++ active appearance model API (AAM_API). It is modified with a subset of required functions for automatic MRI prostate segmentation. AAM-API LICENSE - file: license.txt This software is freely available for non-commercial use such as research and education. Please see the full disclaimer below. All publications describing work using this software should cite the reference given below. Copyright (c) 2000-2003 Mikkel B. Stegmann, mbs@imm.dtu.dk IMM, Informatics & Mathematical Modelling DTU, Technical University of Denmark Richard Petersens Plads, Building 321 DK-2800 Lyngby, Denmark http://www.imm.dtu.dk/~aam/ REFERENCES Please use the reference below, when writing articles, reports etc. where the AAM-API has been used. A draft version the article is available from the homepage. I will be happy to receive pre- or reprints of such articles. /Mikkel ------------- M. B. Stegmann, B. K. Ersboll, R. Larsen, "FAME -- A Flexible Appearance Modelling Environment", IEEE Transactions on Medical Imaging, IEEE, 2003 (to appear) ------------- 3RD PART SOFTWARE The software is partly based on the following libraries: - The Microsoft(tm) Vision Software Developers Kit, VisSDK - LAPACK DISCLAIMER This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any non-commercial purpose, and to alter it, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. -- No guarantees of performance accompany this software, nor is any responsibility assumed on the part of the author or IMM. This software is provided by Mikkel B. Stegmann and IMM ``as is'' and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall IMM or Mikkel B. Stegmann be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage. $Revision: 1.4 $ $Date: 2003/04/23 14:49:15 $ Shape container. This class act as a container for a shape. Essentially it's just a set of 2D points stored in a vector in the format xxxyyy.
    Author:
    Ruida Cheng
    • Field Detail

      • m_vPointAux

        private java.util.Vector<CAAMPointInfo> m_vPointAux
        Auxillary point data.
      • m_vUser1

        private java.util.Vector<java.lang.Float> m_vUser1
        User-defined field 1.
      • m_vUser2

        private java.util.Vector<java.lang.Float> m_vUser2
        User-defined field 2.
      • m_vUser3

        private java.util.Vector<java.lang.Float> m_vUser3
        User-defined field 3.
      • m_szASFVer

        private java.lang.String m_szASFVer
        Current ASF version number.
      • m_iNbPoints

        private int m_iNbPoints
        The number of points.
      • m_bAbsPointCoordinates

        private boolean m_bAbsPointCoordinates
        Indicates if the point coordinates is in relative or absolute format.
      • m_szHostImage

        private java.lang.String m_szHostImage
        Optional 'host image' filename including full path.
      • myHostImage

        private ModelImage myHostImage
        host image.
      • m_pData

        private double[] m_pData
        un-safe pointer to the first point data element.
    • Constructor Detail

      • CAAMShape

        public CAAMShape()
        Default constructor. Defaults to absolute shape coordinates and sets the number of points to zero. Notice that the user defined fields is *not* allocated by default. In order to preserved memory the user must to this explicitly by using AllocateUserFields();
      • CAAMShape

        public CAAMShape​(int nbPoints)
        Constructs a shape with 'nbPoints' points. Defaults to absolute point coordinates and single closed path connectivity.
        Parameters:
        nbPoints - The number of points the shape should contain.
        See Also:
        SetClosedPathConnectivity()
      • CAAMShape

        public CAAMShape​(CDVector v)
        Constructs a shape from a vector. Defaults to absolute point coordinates and single closed path connectivity.
        Parameters:
        v - The input vector.
        See Also:
        SetClosedPathConnectivity()
      • CAAMShape

        public CAAMShape​(CAAMShape s)
        Copy contructor.
        Parameters:
        s - The input shape.
    • Method Detail

      • ToFile

        public void ToFile​(java.io.DataOutputStream fh)
        Write the shape to a binary file.
        Overrides:
        ToFile in class CDVector
        Parameters:
        sFilename - Destination filename.
      • FromFile

        public void FromFile​(java.io.DataInputStream fh)
        Reads a shape from a file.
        Overrides:
        FromFile in class CDVector
        Parameters:
        fh - An open file handle.
      • SetClosedPathConnectivity

        public void SetClosedPathConnectivity()
        Sets all point to be connected in one closed path. Manipulates the aux point info such that the shape points is interpreted as one closed outer path defined clock-wise with repect to it's normals.
      • assign

        public CDVector assign​(double value)
        Assignment operator (double). Sets all x and y compoments of a shape equal to a double. [Actually only used when calculating a mean shape -- since we want to accumulate in an empty shape].
        Overrides:
        assign in class CDVector
        Parameters:
        value - The value to set all shape points to.
        Returns:
        This.
      • assign

        public CAAMShape assign​(CAAMShape s)
        Assignment operator (CAAMShape). Set one shape equal another.
        Parameters:
        s - The shape to copy.
      • CopyData

        private void CopyData​(CAAMShape s)
        Copies all data from a shape to this. Called from the assignment operator.
        Parameters:
        s - Shape to copy data from.
      • assign

        public CDVector assign​(CVisDVector vIn)
        Assignment operator (CAAMShape). Set the shape to be equal an xxx-yyy formatted vector. NOTE: this method does not manipulate any connectivity (i.e. point aux) info. So, if the shape beforehand was empty one should call SetClosedPathConnectivity() afterwards this call to obtain sensible point aux info.
        Overrides:
        assign in class CDVector
        Parameters:
        vIn - xxx-yyy formatted vector.
        Returns:
        This.
      • dispose

        public void dispose()
        dispose memory
        Overrides:
        dispose in class CVisDVector
      • Rotate

        public void Rotate​(double theta)
        rotate shape with given theta angle
        Parameters:
        theta -
      • Rotate

        public void Rotate​(double theta,
                           boolean aroundCOG)
        Rotates the shape. Rotates the shape 'theta' radians.
        Parameters:
        theta - Rotation angle in radians.
        aroundCOG - If true the rotation is being done around the cog of the shape instead of around the global center.
      • Translate

        public void Translate​(CAAMPoint p)
        Translates the shape.
        Parameters:
        p - The offset to translate.
      • Translate

        public void Translate​(double x,
                              double y)
        Translates the shape.
        Parameters:
        x - X-translation.
        y - Y-translation.
      • ShapeSize

        public double ShapeSize()
        Returns the 2-norm of this shape centralized.
        Returns:
        The 2-norm.
      • MinX

        public double MinX()
        Find the maximum x component of the shape.
        Returns:
        The x-maximum.
      • MaxX

        public double MaxX()
        Find the maximum x component of the shape.
        Returns:
        The x-maximum.
      • MinY

        public double MinY()
        Find the minimum y component of the shape.
        Returns:
        The y-minimum.
      • MaxY

        public double MaxY()
        Find the maximum y component of the shape.
        Returns:
        The y-maximum.
      • Scale

        public void Scale​(double s)
        Scale the shape
        Parameters:
        s -
      • Scale

        public void Scale​(double s,
                          boolean aroundCOG)
        Scales the shape.
        Parameters:
        s - Scale factor.
        aroundCOG - If true the scale is being done around the cog of the shape instead of around the global center.
      • COG

        public CAAMPoint COG()
        Calculates the center of gravity of the shape (actually it's the center of the centroid).
        Parameters:
        p - cog output.
      • COG

        public void COG​(double[] x,
                        double[] y)
        Calculates the center of gravity of the shape (actually it's the center of the centroid).
        Parameters:
        x - X cog output.
        y - X cog output.
      • Normalize

        public double Normalize()
        Normalizes the shape by translating it's center of gravity to origo and scale by the reciprocal of the 2-norm.
        Returns:
        The 2-norm of the shape seen as a 2*nbPoint vector after the translation to orig.
      • SetPoint

        public int SetPoint​(int i,
                            double x,
                            double y)
        Overwrites the i'th point.
        Returns:
        Zero.
      • SetPoint

        public int SetPoint​(int i,
                            CAAMPoint p)
        Overwrites the i'th point. If the point doesn't exists, non-zero is returned.
        Returns:
        Zero on success, non-zero if the point doesn't exists.
      • GetPoint

        public int GetPoint​(int i,
                            double[] x,
                            double[] y)
        Returns the i'th point.
        Returns:
        Zero.
      • GetPoint

        public CAAMPoint GetPoint​(int i)
        Returns the i'th point.
        Returns:
        The i'th point.
      • Resize

        public void Resize​(int length,
                           double[] storage)
        Change number of shape points in the shape. Note: Destroys *all* current point data and point info data.
        Overrides:
        Resize in class CVisDVector
        Parameters:
        length -
        storage -
      • AlignTransformation

        public void AlignTransformation​(CAAMShape ref,
                                        double[] scale,
                                        double[] theta,
                                        CAAMPoint t)
        Returns the transformation that aligns this to 'ref' with respect to pose.
        Parameters:
        ref - The reference shape.
      • initAlignTo

        public double initAlignTo​(CAAMShape ref)
        Init ref to this.
        Parameters:
        ref -
        Returns:
        2-norm of the shape
      • initAlignTo

        public double initAlignTo​(CAAMShape ref,
                                  double[] pTheta)
        Aligns this to 'ref' with respect to pose.
        Parameters:
        ref - The reference shape.
        pTheta - Optional pointer to return the rotation carried out on this.
        Returns:
        The 2-norm of the this shape seen as a 2*nbPoint vector after the translation to orig but before the scale done to fit 'ref'.
      • AlignTo

        public double AlignTo​(CAAMShape ref)
        Wrapper to align this to ref.
        Parameters:
        ref -
        Returns:
      • AlignTo

        public double AlignTo​(CAAMShape ref,
                              double[] pTheta)
        Aligns this to 'ref' with respect to pose.
        Parameters:
        ref - The reference shape.
        pTheta - Optional pointer to return the rotation carried out on this.
        Returns:
        The 2-norm of the this shape seen as a 2*nbPoint vector after the translation to origo but before the scale done to fit 'ref'.
      • GetRotation

        public double GetRotation​(CAAMShape ref)
        Returns the rotation between ref and this (in radians). Get the rotation between two shapes by minimizing the sum of squared point distances, as described by Goodall (and Bookstein) using Singular Value Decomposition (SVD). Note that both shapes must be normalized with respect to scale and position beforehand. This could be done by using CAAMSAhape::Normalize().
        Returns:
        The estimated angle, theta, between the two shapes.
      • Param2PoseVec

        public static void Param2PoseVec​(double scale,
                                         double theta,
                                         double tx,
                                         double ty,
                                         CDVector poseVec)
        Converts pose parameters: scale, theta, tx, ty to a pose vector. The pose vector will be in the format: [ s, theta, tx, ty ] where s = scale-1
        Parameters:
        scale - Scale input.
        theta - Rotational input.
        tx - X translation input.
        ty - Y translation input.
        poseVec - The output pose vector.
      • PoseVec2Param

        public static void PoseVec2Param​(CDVector poseVec,
                                         double[] scale,
                                         double[] theta,
                                         double[] tx,
                                         double[] ty)
        Converts a pose vector to pose parameters: scale, theta, tx, ty. The pose vector are expected to be in the format: [ s, theta, tx, ty ] where s = scale-1
        Parameters:
        poseVec - The input pose vector.
        scale - Scale output.
        theta - Rotational output.
        tx - X translation output.
        ty - Y translation output.
      • Displace

        public void Displace​(CDVector poseVec)
        Displaces the shape around it's center of gravity using a displacement vector.
        Parameters:
        poseVec - The input pose vector.
      • IsInsidePath

        public boolean IsInsidePath​(CAAMPoint p,
                                    int path_start)
        Tests if the point 'p' is inside the path starting at position 'path_start'. Rarely used. Primary a helper function to IsInside.
        Parameters:
        p - The point to test for.
        path_start - The point index where a path starts
        Returns:
        True if 'p' is inside
      • IsInside

        public boolean IsInside​(CAAMPoint p)
        Wrapper to check is point p is inside the shape
        Parameters:
        p - point
        Returns:
        inside or not
      • IsInside

        public boolean IsInside​(CAAMPoint p,
                                boolean bBoundTest)
        Tests if the point 'p' belongs to the shape. In the current version all shape points are assumes to be ordered points in a n-point polygon with no holes. For example used to clean up the meshes (removing unwanted triangles from the triangulisation).
        Parameters:
        bBoundTest - Flags wheather a bounding box test should be performed prior to the exact test.
        Returns:
        True if 'p' is inside.
      • Expand

        public void Expand​(int nPixels)
        Expands the shape by moving each model point 'nPixels' perperdicular to the shape contour (that is: along the model point normal). This function will expand each outer (closed) path of the shape. No tests for crossing contours are being made as of now.
        Parameters:
        nPixels - The number of pixel to expand the shape with.
      • Normal

        public void Normal​(int i,
                           CAAMPoint p1,
                           CAAMPoint p2,
                           double dist)
        Finds the normal to the i'th point on the shape. If the point should be a single point the normal points is defined to be equal to the point it self.
        Parameters:
        i - Index of point.
        p1 - Reference to the outside normal point.
        p2 - Reference to the inside normal point.
        dist - The desired distance from p[1|2] to the i-th point.
      • NormalDisplacement

        public void NormalDisplacement​(int i,
                                       double dist)
        Displaces the i-th point along the normal.
        Parameters:
        i - Index of point.
        dist - The distance to move the point (>0 move point outwards, <0 inwards).
      • WriteASF

        public boolean WriteASF​(java.lang.String filename,
                                int image_width,
                                int image_height)
        Writes the shape to a ASF file. Remember asf's are always in relative coordinates. Se format description else where.
        Parameters:
        filename - Output filename.
        image_width - The image the coord. is relative to.
        image_height - The image the coord. is relative to.
        Returns:
        true on success, false on errors
      • WriteASF0_90

        public boolean WriteASF0_90​(java.lang.String filename,
                                    int image_width,
                                    int image_height)
        ASF writer version 0.90. Writes the shape to a ver. 0.90 ASF file. Remember asf's are always in relative coordinates. Se format description else where.
        Parameters:
        filename - Output filename.
        image_width - The image the coord. is relative to.
        image_height - The image the coord. is relative to.
        Returns:
        true on success, false on errors
      • generateVOIs

        public boolean generateVOIs​(ModelImage targetImageSlice)
        ASF writer version 0.90. Writes the shape to a ver. 0.90 ASF file. Remember asf's are always in relative coordinates. Se format description else where.
        Parameters:
        filename - Output filename.
        image_width - The image the coord. is relative to.
        image_height - The image the coord. is relative to.
        Returns:
        true on success, false on errors
      • generateVOImesh

        public boolean generateVOImesh​(ModelImage targetImageSlice)
        From the current shape, generate the corresponding triagnle meshes view. VOIs is used to display the mesh.
        Parameters:
        targetImageSlice -
        Returns:
        true by default
      • ReadASF

        public boolean ReadASF​(java.lang.String filename)
        Reads an ver. 0.90 .asf into relative coordinates. Se format description else where.
        Parameters:
        filename - Input filename.
        Returns:
        true on success, false on errors
      • ReadASF0_90

        public boolean ReadASF0_90​(java.lang.String filename)
        Reads an ver. 0.90 .asf into relative coordinates. Se format description else where.
        Parameters:
        filename - Input filename.
        Returns:
        true on success, false on errors
      • ReadASFfromVOI

        public boolean ReadASFfromVOI​(ModelImage image)
        Generate ASF shape from given VOI
        Parameters:
        image - image with VOI.
        Returns:
        success or not
      • ConvertASFfromVOI

        public boolean ConvertASFfromVOI​(VOIBase v)
        Convert ASF shape from VOI
        Parameters:
        v - VOI
        Returns:
        success or not.
      • ReadASFfromVOI_init

        public boolean ReadASFfromVOI_init​(ModelImage image)
      • Abs2Rel

        public void Abs2Rel​(java.lang.String hostImagePath)
        Converts shape coordinates from absolute to relative by using the hostimage.
      • IsAbs

        public boolean IsAbs()
        Returns true if the shape is in absolute coordinates.
        Returns:
        is abs coordinate or not
      • Rel2Abs

        public void Rel2Abs​(java.lang.String hostImagePath)
      • Abs2Rel

        public void Abs2Rel​(int image_width,
                            int image_height)
        Converts shape coordinates from absolute to relative. Relative coordinates are specified as: x_relative = x_abs/image_width y_relative = y_abs/image_height
        Parameters:
        image_width - The image the coord. should be relative to.
        image_height - The image the coord. should be relative to.
        See Also:
        Rel2Abs(java.lang.String)
      • Rel2Abs

        public void Rel2Abs​(int image_width,
                            int image_height)
        Converts shape coordinates from relative to absolute. Relative coordinates are specified as: x_relative = x_abs/image_width y_relative = y_abs/image_height
        Parameters:
        image_width - The image the coord. is relative to.
        image_height - The image the coord. is relative to.
        See Also:
        Abs2Rel(java.lang.String)
      • AddPath

        public void AddPath​(CAAMShape shape,
                            CAAMPointInfo pointType)
        Adds a path to the shape. All added point inherits the given pointtype.
        Parameters:
        shape - A shape containing one path.
        pointType - The pointtype of the added points.
      • ReversePointOrder

        public void ReversePointOrder()
        Reverses the point point ordering. Used when a clock-wise outer path shall converted to a counter-clock wise hole.
      • GetPaths

        public java.util.Vector<java.lang.Integer> GetPaths()
        Extracts the starting positions of each path in the shape by a simple linear search. The starting position is identified by a change in path id (saved in the m_vPointAux member).
        Returns:
        A vector of path starting positions.
      • PathLen

        public int PathLen​(int startPosition)
        Returns the length of a path.
        Parameters:
        startPosition - The starting position of the path.
        Returns:
        The path length.
        See Also:
        GetPaths()
      • ExtractPath

        public CAAMShape ExtractPath​(int startPosition)
        Extracts one path from a shape into a new shape.
        Parameters:
        startPosition - The starting position of the path.
        Returns:
        The path as a new shape.
      • AddShapeExtends

        public void AddShapeExtends​(int nPixels)
        Adds an extra outer path on each outer path in the distance of 'nPixels' along the point normal. This method is primary used in conjunction with the "do not use the convex hull" feature. In such a case one often still wants a certain neighborhood of the shape to be included in the model.
        Parameters:
        nPixels - The size of the extents.
      • SetPointInfoFlagsInPath

        public void SetPointInfoFlagsInPath​(int startPosition,
                                            int flags)
        Sets all flags in one path to the same value.
        Parameters:
        startPosition - Starting position of the path.
        flags - The flags.
      • AddInterior

        public void AddInterior​(int interations)
        Add articifial interior points to the shape by making a Delaunay triangulation and adding the centroid of each triangle. This is done iteratively. Default is one iteration
        Parameters:
        interations - Controls the number of artificial points. One iteration equals one triangulation.
      • ConsistencyCheck

        public boolean ConsistencyCheck()
        Tests if any interior points has gone outside outer path of the shape.
        Returns:
        True if the shape looks ok, false if not.
      • MakeBorderShape

        public void MakeBorderShape​(int size)
        Converts a one path shape into a border shape by adding two symmetric borders: an inside (a hole) and an outside border. No checks for folding paths are done as of now.
        Parameters:
        size - The size of the border in pixels.
      • add

        public CAAMShape add​(CVisDVector v)
        Plus operator.
        Overrides:
        add in class CVisDVector
        Parameters:
        v - Vector to add.
        Returns:
        The addition of this and 'v'.
      • sub

        public CAAMShape sub​(CVisDVector v)
        Minus operator.
        Overrides:
        sub in class CVisDVector
        Parameters:
        v - Vector to add.
        Returns:
        The subtraction of this and 'v'.
      • GetHostImage

        public ModelSimpleImage GetHostImage​(ModelSimpleImage dest,
                                             java.lang.String path,
                                             int rfactor)
        Retrives the image connected to the shape. As of now it's loaded from disk using the HostImage() member in the shape.
        Parameters:
        dest - The destination image.
        path - The path to the .asf file.
        rfactor - Optional reduction factor. Performs a scaling of the the shape by 1/rfactor. Default 1 i.e. no scaling.
        Returns:
        refactored image.
      • GetHostImage

        public ModelSimpleImage GetHostImage​(ModelImage src,
                                             int rfactor)
        Retrives the image connected to the shape. As of now it's loaded from disk using the HostImage() member in the shape.
        Parameters:
        src - source image
        rfactor - reduction factor
        Returns:
        refactored iamge.
      • Area

        public double Area()
      • Area

        public double Area​(boolean use_covex_hull)
        Returns the total area of the shape (with holes excluded).
        Parameters:
        use_covex_hull - Use the convex hull of the shape for area calculation (default false).
        Returns:
        The area.
      • CalcConvexHull

        public CAAMShape CalcConvexHull()
        Calculates the convex hull of each path in the shape. The calulation is built upon the geometrical fact that the homogenous point matrix: [ p1x p2x p3x ; p1y p2y p3y ; 1 1 1 ] is positive if p1, p2, p3 is a convex segment and negative if concave. Note: this holds for a clock-wise ordering of p1,p2,p3. Any open paths are considered cyclic in the concavity calulation. Remember that paths should be defined clock-wise in the asf format. BUG COMMENT: This does not seem to work with multiple paths.
        Returns:
        A convex version of this shape w.r.t. each path.
      • IsConvex

        public boolean IsConvex()
        Tests if the shap is convex w.r.t. each path. This call is rather expensive, since it spaws a call to CalcConvexHull().
        Returns:
        True on convex, false on concave.
      • RemovePoint

        public void RemovePoint​(int i)
        Removes the i-th point from the shape. Since this require massive reordering of the preceeding point connectivity this is actually a very expensive call [a fairly ugly in it's implementation] :-(
        Parameters:
        i - The index of the point to remove.
      • DEC_TO_ZERO

        public int DEC_TO_ZERO​(int a)
        Convert deciam number to 0
        Parameters:
        a - int number
        Returns:
      • UserField

        public java.util.Vector<java.lang.Float> UserField​(int field_nb)
        Returns the reference of the user defined field vector number 'field_nb'.
        Parameters:
        field_nb - Field number [1-3].
        Returns:
        A reference to the specified field vector.
      • AllocateUserFields

        public void AllocateUserFields()
        Allocates room for the three user defined fields. Notice that the user defined fields is *not* allocated by default. In order to preserved memory the user must to this explicitly by using AllocateUserFields();
      • HostImage

        public final java.lang.String HostImage()
        Host image (if any).
        Returns:
        host image
      • SetHostImage

        public void SetHostImage​(java.lang.String hostImageFilename)
        Returns the host image (if any).
        Parameters:
        hostImageFilename -
      • Width

        public double Width()
        Shape width.
        Returns:
        shape width
      • Height

        public double Height()
        Shape height
        Returns:
        shape height
      • NPoints

        public final int NPoints()
        The number of shape points.
        Returns:
        number of points on shape
      • GetPointUS

        public void GetPointUS​(int i,
                               double[] x,
                               double[] y)
        un-safe (and dirty) since it depends on assumptions regarding the
        Parameters:
        i - index
        x - x coordinate pointer
        y - y conrdinate pointer
      • PointAux

        public java.util.Vector<CAAMPointInfo> PointAux()
        Returns the complete point aux vector of the shape.
        Returns:
        point info vector
      • setPointAux

        public void setPointAux​(java.util.Vector<CAAMPointInfo> value)
        set point info vector
        Parameters:
        value -
      • setPointAux

        public void setPointAux​(int index,
                                CAAMPointInfo value)
        Set specific point info
        Parameters:
        index -
        value -
      • getHostImage

        public ModelImage getHostImage()
        Get host image.
        Returns:
        image