Home > Articles > Programming > Graphic Programming

This chapter is from the book

Comprehensive Example: Kspace Visualization

The following is a comprehensive example that will be integrated with some of Java 3D examples from Part III to form one of the integrated examples at the end of the book. It isn't necessary to understand the subject matter to understand the graphics programming; however, some background information is helpful.

Background Information on Kspace

One of the fundamental concepts in magnetic resonance imaging is kspace. It is sometimes said in jest that kspace is a place where no one can hear you scream. Without a doubt, kspace is a tough concept for people learning MRI. However, kspace is a simple extension of the concept of Fourier space that is well known in imaging. For now, suffice it to say that Fourier space and image space are different representations of the same data. It is possible to go back and forth between image space and Fourier space using the forward and inverse Fourier transform. Many image processing routines make direct use of this duality.

What makes MRI different from other imaging modalities is that the data are collected directly in Fourier space by following a time-based trajectory through space. The position in Fourier space is directly related to the gradient across the object being imaged. By changing the gradient over time, many points in kspace can be sampled in a trajectory through Fourier space. Discreet samples are taken at each point until the Fourier space is filled. A backward (inverse) Fourier Transform is then performed to yield the image of the object (in image space).

It turns out that there are numerous (almost infinite ways) to traverse kspace. One such trajectory is called spiral and benefits from improved coverage of kspace per unit time because of the inherent properties of the circle. The spiral kspace trajectory allows for images to be taken in snapshot (20ms) fashion and is used for such leading-edge applications such as imaging of the beating heart or imaging brain activity (functional magnetic resonance imaging). Figure 3.13 shows the final trajectory. Blue dots indicate that all time points up to the current time, whereas red dots indicate the full trajectory. This part of the visualization will be integrated with Java 3D models in the KspaceModeller application developed in Part III of this book.

Figure 3.13 Final kspace trajectory for KspacePlot.java.

In this example, we will use a slider bar to advance through time and see the current and previously sampled kspace points. The visualization will be made using an actual file that sits on the computer that runs an MRI scanner. We will later expand the number of kspace trajectories we can make, including making programmatic versions that aren't based on real data.

Step 1—The Visualization

First, let's make a skeleton of our external extended Canvas and call it KspaceCanvas. It is in this external class that all our painting will be accomplished. We will begin by painting an x- and y-axis with labels. An important part of this process is determining the height and width of the Canvas (accomplished with the getSize() method).

Listing 3.7 KspaceCanvas.java—a Custom Canvas for Visualization

import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;


public class KspaceCanvas extends Canvas {
  int xcenter, ycenter, offsetx, offsety;

  KspaceCanvas() {
  System.out.println("Creating an instance of KspaceCanvas");
  }

 public void drawKspace(int tpoint) {
   System.out.println("drawKspace");
   this.tpoint = tpoint;
   repaint();
  }

 public void paint(Graphics g){

   Graphics2D g2d = (Graphics2D)g; //always!

    offsetx = (int) this.getSize().width/50; 
    offsety = (int) this.getSize().height/50; 
    xcenter = (int) this.getSize().width/2; 
    ycenter = (int) this.getSize().height/2;

  //call method to paint the x-y axix
   paintAxis(g2d);
 }

  public void paintAxis(Graphics2D g2d) {
   //setup font for axis labeling
   Font f1 = new Font("TimesRoman", Font.BOLD, 14);
   g2d.setFont(f1);

   g2d.drawString("Kx",this.getSize().width-(2*offsetx),
             this.getSize().height/2);

   g2d.drawString("Ky",this.getSize().width/2,offsetx);

   // draw axis for kspace

   g2d.setColor(Color.black); //set rendering attribute
   g2d.drawLine(offsetx, ycenter, xcenter-xoffset, ycenter-yoffset);
   g2d.drawLine(xcenter, yoffset, xcenter, ycenter-yoffset); 

 }

}

Notice the drawKspace() method that receives the int argument tpoint, whose sole function is to set the current timepoint and call repaint(). The tpoint variable will represent the current timepoint in the kspace trajectory and will run from 0 to 5499. In the next step, we will create a slider bar with an attached listener. In that listener, the drawKspace() method will be called with the tpoint variable representing the current value of the slider bar.

The other important code for this part occurs in the overridden paint() and paintAxis() methods. First, in the paint() method, we get information necessary for scaling the axis appropriately. We want the x and y centers located half way up the Canvas regardless of size, so we use the getSize() method that was briefly described previously.

Step 2—Setting Up the User Interface

This step is fairly easy. We will extend JFrame and add two JPanels, one to hold the user interface components and another to hold our Canvas, as shown in Listing 3.8.

Listing 3.8 KspaceSpacePlot.java

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import javax.vecmath.*;
import javax.swing.*;
import java.awt.BorderLayout;

import java.util.Vector;

import java.awt.GraphicsConfiguration;

public class KspacePlot extends JFrame {

  int kwidth, kheight;

  KspaceData ks;
  KspaceCanvas kspacec;

 public KspacePlot (int initx, int inity) {

  super("Kspace Plot");

  Panel sliderpanel = new Panel();
  JSlider hslider = new JSlider();
  hslider.setMinimum(0);
  hslider.setMaximum(5498);
  hslider.setValue(0);
  hslider.setPreferredSize(new Dimension(300,20));
  sliderpanel.add(hslider);

  BorderLayout f1 = new BorderLayout(); 
  this.getContentPane().setLayout(f1);
  this.getContentPane().add(sliderpanel, BorderLayout.NORTH);
  ks = new KspaceData();
  kspacec = new KspaceCanvasA();

  this.getContentPane().add(kspacec);
  kspacec.drawKspace(0);
}

public static void main(String[] args) {
  int initialSizex=500; 
  int initialSizey=500;

  WindowListener l = new WindowAdapter() {
   public void windowClosing(WindowEvent e)
    {System.exit(0);}
   public void windowClosed(WindowEvent e)
    {System.exit(0);}
   };

  KspacePlot k = new KspacePlot(initialSizex, initialSizey); 
  k.addWindowListener(l);
  k.setSize(500,500); 
  k.setVisible(true);

  }

}

class SliderListener implements ChangeListener {

  KspaceCanvasA kc;
  int slider_val;

  public SliderListener(KspaceCanvasA kc) {
    this.kc = kc;
  }

 public void stateChanged(ChangeEvent e) {

  JSlider s1 = (JSlider)e.getSource();
  slider_val = s1.getValue();
  System.out.println("Current value of the slider: " + slider_val);
  kc.drawKspace(

}//End of stateChanged
 }//End of SliderListener
//

Step 3—Reading the Scanner Trajectory

Because we want to plot an actual trajectory from the scanner, we will read bytes from a file into an array using a FileInputStream object. There are a few examples that read raw data in this book and you will find that, in practice, reading bytes is occasionally necessary. It probably isn't necessary to get into the details of this class. The important concept is that two files (kxtrap.flt and kytrap.flt) are read into two public arrays. Maximum and minimum values are computed for each array and stored in public variables. Another public array of time values is calculated based on the number of timepoints. The values stored in these arrays will be made accessible to KspaceCanvas by adding code to the KspaceCanvas constructor in "Step 4—Modifying KspaceCanvas to Plot the Data." Note that this class is external and stored in the file KspaceData.java (see Listing 3.9).

Listing 3.9 KspaceData.java—an External Class for Reading a Scanner Trajectory

import java.awt.*;
import java.io.*;

class KspaceData {

  int tpoints=5500;

  double Gxcoord[] = new double[tpoints];
  double Gycoord[] = new double[tpoints];
  int time[] = new int[tpoints];

  double Gx, Gy;

  double Gxmax=0.0;
  double Gymax=0.0;
  double Gxmin=0.0;
  double Gymin=0.0;

  KspaceData() {
    readdata();
  }

  public void readdata() {

   try {
      DataInputStream disx =
new DataInputStream(new FileInputStream("kxtrap.flt"));
      DataInputStream disy =
new DataInputStream(new FileInputStream("kytrap.flt"));

      try {
        for (int i=0; i < tpoints-1; i++) {
          Gx = disx.readFloat();
      Gy = disy.readFloat();

       //find min and max gradient values to determine scaling
          if (Gx > Gxmax) {
           Gxmax=Gx;
          }
          if (Gy > Gymax) {
            Gymax=Gy;
          }
         if (Gx < Gxmin) {
           Gxmin=Gx;
          }
          if (Gy < Gymin) {
            Gymin=Gy;
          }

          Gycoord[i] = Gy;
      Gxcoord[i] = Gx;
      }
      } catch (EOFException e) {
     }
     } catch (FileNotFoundException e) {
      System.out.println("DataIOTest: " + e);
    } catch (IOException e) {
      System.out.println("DataIOTest: " + e);
    }
  }

}

Step 4—Modifying KspaceCanvas to Plot the Data

Now that we can read the kx and ky files, it is time to plot the data over the axis that we made in step 1.

Add the method paintData() just below the paintAxis() method in KspaceCanvas.java:

//method to plot kspace data

public void paintData(Graphics2D g2d) {

  for (int i=1; i<tpoints-2; i++){
   // Scale Gx and Gy between -1 and 1; called Kx and Ky;
   // Multiply Kx and Ky times the width and height 
   //of the Canvas in the same step
    Kx[i] = (ks.Kx[i] *this.getSize().width*scalefac;
    Ky[i] = (ks.Ky[i])*this.getSize().height*scalefac;

    g2d.setColor(Color.lightGray);
    g2d.draw(new Ellipse2D.Double(kxcenter + Kx[i],
                   kycenter + Ky[i],3.0,3.0));
    g2d.setColor(Color.blue);
    g2d.fill(new Ellipse2D.Double(kxcenter + Kx[i],
                   kycenter + Ky[i],4.0,4.0));

  }

}

In addition, we need to instantiate an object from our KspaceData class. In the KspacePlot.java class, add the following line just above the initial call to the KspaceCanvas constructor:

ks = new KspaceData();

We now need to modify the constructor to KspaceCanvas to allow for the passing in the newly constructed KspaceData object. First change the constructor in KspaceCanvas.java:

KspaceCanvas(KspaceData ks) {
  this.ks = ks;
}

And, change the initial call to the constructor in KspacePlot.java accordingly to the following:

kspacec = new KspaceCanvas(ks);

Finally, let's add the call to paintData() right after the call to paintAxis() in the paint() method of KspaceCanvas:

paintData(g2d);

After running the program, your screen should resemble Figure 3.8.

Step 5—Overriding the Update Method in KspaceCanvas

You will notice immediately that, although the program is starting to look promising, it is largely unusable in its present state. The primary problem is that the screen is erased and fully redrawn every time the slider bar changes.

Remember from before that repaint ends up calling update(), which puts the background color over the component before the Component's paint() method is called. This is one of the times when this is undesirable. We must therefore override the update() method and have our program only redraw the points that are new since the last call to repaint(). The following code segment is inserted into KspaceCanvas.java:

public void update(Graphics g) {
   paint(g);
}

Step 6—Add RenderingHints to Improve the Rendering

In this final step, we want to make the output look better. This is achieved through adding RenderingHints to the Graphics2D object. In this case, we want to add antialiasing so that our data point ellipses (dots) look smoother. We also need to add bicubic spline interpolation so that the dots line up better. Add the following lines in the paint() method:

RenderingHints interpHints =
       new RenderingHints(RenderingHints.KEY_INTERPOLATION,
                 RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g2d.setRenderingHints(interpHints);

RenderingHints antialiasHints =
       new RenderingHints(RenderingHints.KEY_ANTIALIASING,
                 RenderingHints.VALUE_ANTIALIAS_ON);

g2d.setRenderingHints(antialiasHints);

You could just as well add this code to the constructor so that the RenderingHints aren't created each time paint() is called; however, this doesn't provide a substantial difference in performance.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020