Skip to content

Instantly share code, notes, and snippets.

@fornarat
Last active June 30, 2016 11:16
Show Gist options
  • Save fornarat/2d5022bbee09f7a4185f03f42d489002 to your computer and use it in GitHub Desktop.
Save fornarat/2d5022bbee09f7a4185f03f42d489002 to your computer and use it in GitHub Desktop.
package org.sparkexample; /** * sample program to read images belonging to a sample Class e.g. Male/Female . Then writing the images to Vector format into a text file. These text files will be used by Apache Spark for Linear SVM analysis */
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.io.*;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
/**
* @author smruti
* @author fornarat
usage:
java com.hyperiongray.ImageParser 180x200 /home/tomas/projects/spark/img-data/faces94/male/ 1
java com.hyperiongray.ImageParser 180x200 /home/tomas/projects/spark/img-data/faces94/female/ 0
*/
/**
creates a txt file with the pixels of the image
*/
public class ImageParserRGB {
public static void main(String[] args) throws IOException {
/* args[0] is the pixel to which the image will be converted */
String[] pixels = args[0].split("x");
int scaledWidth = Integer.parseInt(pixels[0]);
int scaledHeight = Integer.parseInt(pixels[1]);
/* args[1] is the parent path of images to dump */
String providedParentPath = args[1].toString();
/* args[2] is the Class of the image, Class = Male/Female. Vector will be written into a text file */
String label = args[2];
String outputFilename = args[3];
ImageParserRGB imageParser = new ImageParserRGB();
imageParser.extract(providedParentPath, scaledWidth, scaledHeight, label, outputFilename);
}
public void extract(String providedParentPath, int scaledWidth, int scaledHeight, String label, String outputFilename) throws IOException {
List<String> paths = getRecursiveFolders(providedParentPath);
try {
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(outputFilename +".csv", true)))) {
for(String file : paths){
File input = new File(file.toString());
BufferedImage image = createResizedCopy(ImageIO.read(input),scaledWidth,scaledHeight,Boolean.TRUE);
toGray(image);
if (image == null) continue;
Raster raster=image.getData();
int w=raster.getWidth();
int h=raster.getHeight();
out.print(label +",");
for (int x=0;x<w;x++){
for(int y=0;y<h;y++){
out.print(raster.getSample(x,y,0));
if (x!=w-1 || y!=h-1){
out.print(",");
}
}
// out.print(",");
}
out.println("");
}
}catch (IOException e) {
//exception handling skipped for the reader
System.out.println(e);
}
}
catch (Exception e) {
System.out.println(e);
//exception handling skipped for the reader
}
}
/**
* Traverse All the files inside the Folder and sub folder. args[1] is the path of the folder having the images
* @param providedParentPath
* @return
* @throws IOException
*/
private List<String> getRecursiveFolders(String providedParentPath) throws IOException {
List<String> paths = new ArrayList<>();
Files.walkFileTree(Paths.get(providedParentPath), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
//Files.delete(file);
paths.add(file.toFile().getAbsolutePath());
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
//Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
return paths;
}
public void toGray(BufferedImage image) {
int width = image.getWidth();
int height = image.getHeight();
for(int i=0; i<height; i++){
for(int j=0; j<width; j++){
Color c = new Color(image.getRGB(j, i));
int red = (int)(c.getRed() * 0.21);
int green = (int)(c.getGreen() * 0.72);
int blue = (int)(c.getBlue() *0.07);
int sum = red + green + blue;
Color newColor = new Color(sum,sum,sum);
image.setRGB(j,i,newColor.getRGB());
}
}
}
public BufferedImage createResizedCopy(BufferedImage originalImage,
int scaledWidth, int scaledHeight,
boolean preserveAlpha){
System.out.println("resizing...");
int imageType = preserveAlpha ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
BufferedImage scaledBI = new BufferedImage(scaledWidth, scaledHeight, imageType);
Graphics2D g = scaledBI.createGraphics();
if (preserveAlpha) {
g.setComposite(AlphaComposite.Src);
}
g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);
g.dispose();
return scaledBI;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment