Example #1
0
 public static GrayImage loadTrainingImage(String path) {
   GrayImage gImage = null;
   BufferedImage img = null;
   try {
     File imageFile = new File(path);
     if (!imageFile.exists()) {
       throw new IllegalArgumentException("loadTrainingImage(): non-existant file");
     }
     img = ImageIO.read(imageFile);
     if (img != null) {
       WritableRaster raster = img.getRaster();
       byte rawPixels[] = ((DataBufferByte) raster.getDataBuffer()).getData();
       int pixLength = 3;
       int pixOffset = 0;
       if (img.getAlphaRaster() != null) {
         pixLength = 4;
         pixOffset = 1;
       }
       int imgWidth = img.getWidth();
       int imgHeight = img.getHeight();
       double resultPixels[] = new double[rawPixels.length / pixLength];
       for (int i = 0, j = 0; i < rawPixels.length - pixOffset - 2; i += pixLength, ++j) {
         resultPixels[j] =
             averagedGrayscale(
                 rawPixels[i + pixOffset] & 0xFF,
                 rawPixels[i + pixOffset + 1] & 0xFF,
                 rawPixels[i + pixOffset + 2] & 0xFF);
       }
       gImage = new GrayImage(resultPixels, imgWidth, imgHeight);
     }
   } catch (IOException e) {
     e.printStackTrace();
   }
   return gImage;
 }
 /**
  * Converts an AWT based buffered image into an SWT <code>Image</code>. This will always return an
  * <code>Image</code> that has 24 bit depth regardless of the type of AWT buffered image that is
  * passed into the method.
  *
  * @param awtImage the {@link java.awt.image.BufferedImage} to be converted to an <code>Image
  *     </code>
  * @return an <code>Image</code> that represents the same image data as the AWT <code>
  *     BufferedImage</code> type.
  */
 private static org.eclipse.swt.graphics.Image toSWT(Device device, BufferedImage awtImage) {
   // We can force bitdepth to be 24 bit because BufferedImage getRGB
   // allows us to always retrieve 24 bit data regardless of source color depth.
   PaletteData palette = new PaletteData(0xFF0000, 0xFF00, 0xFF);
   ImageData swtImageData = new ImageData(awtImage.getWidth(), awtImage.getHeight(), 24, palette);
   // Ensure scansize is aligned on 32 bit.
   int scansize = (((awtImage.getWidth() * 3) + 3) * 4) / 4;
   WritableRaster alphaRaster = awtImage.getAlphaRaster();
   byte[] alphaBytes = new byte[awtImage.getWidth()];
   for (int y = 0; y < awtImage.getHeight(); y++) {
     int[] buff = awtImage.getRGB(0, y, awtImage.getWidth(), 1, null, 0, scansize);
     swtImageData.setPixels(0, y, awtImage.getWidth(), buff, 0);
     if (alphaRaster != null) {
       int[] alpha = alphaRaster.getPixels(0, y, awtImage.getWidth(), 1, (int[]) null);
       for (int i = 0; i < awtImage.getWidth(); i++) {
         alphaBytes[i] = (byte) alpha[i];
       }
       swtImageData.setAlphas(0, y, awtImage.getWidth(), alphaBytes, 0);
     }
   }
   return new org.eclipse.swt.graphics.Image(device, swtImageData);
 }