repl.it
@emileferreira/

Image Classifier

Java

Image classifier that I've written from the ground up. It comprises of aspects from both an SVM and neural network structure.

fork
loading
Files
  • Main.java
  • models.txt
  • StdDraw.java
Main.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import javax.imageio.ImageIO;
import java.io.IOException;
import java.io.File;
import java.awt.Color;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.PrintWriter;
import java.awt.Image;
import java.net.URL;
import java.io.BufferedWriter;
import java.io.FileWriter;

class Main {
  public static void main(String[] args) throws IOException {
    //get image from local file
    /*System.out.println("\nWelcome to Emile's image classifier. \nPlease input the image file path. (e.g. test.jpg)");
    BufferedImage image = ImageIO.read(new File(System.console().readLine()));*/

    //get image from URL
    System.out.println("\nPlease input the image URL:");

    BufferedImage image = null;
    try {
        URL url = new URL(System.console().readLine());
        System.out.println("\nLoading image...");
        image = ImageIO.read(url);
    } catch (IOException e) {
      e.printStackTrace();
    }

    //create model of current image
    int[][] currentValues = convertToAvgRGB(image);

    System.out.println("Comparing to image models...");

    //compare to learnt models
    double min = 1000000000;
    double distance;
    double coefficient;
    String result = "";
    String model_name = "";
    int[][] model_values = new int[3][900];
    String line;

    //get text file
    try {
      Scanner scanner = new Scanner(new File("models.txt"));

      while (scanner.hasNextLine()) {
        line = scanner.nextLine();
        //get model name
        model_name = line.substring(0, line.indexOf(";"));
        line = line.substring(line.indexOf(";") + 1, line.length());
        //get model values
        int quad = 0;
        while (line.length() > 3) {
          model_values[0][quad] = Integer.parseInt(line.substring(0, line.indexOf(",")));
          line = line.substring(line.indexOf(",") + 1, line.length());
          model_values[1][quad] = Integer.parseInt(line.substring(0, line.indexOf(",")));
          line = line.substring(line.indexOf(",") + 1, line.length());
          model_values[2][quad] = Integer.parseInt(line.substring(0, line.indexOf(";")));
          line = line.substring(line.indexOf(";") + 1, line.length());
          quad++;
        }

        //draw models
        //show(model_values);
    
        //calculate average distance
        distance = 0;
        for (int i = 0; i < model_values.length; i++) {
          coefficient = 10 * Math.sin(0.21 * i - 1.7) + (-0.00009 * Math.pow(i - 450, 2)) + 29;
          distance += coefficient / 3 * Math.sqrt(Math.pow(currentValues[0][i] - model_values[0][i], 2) + Math.pow(currentValues[1][i] - model_values[1][i], 2) + Math.pow(currentValues[2][i] - model_values[2][i], 2));
        }
        distance = distance / model_values.length;
        //System.out.println(model_name + " distance: " + distance);

        //update closest match
        if (min > distance) {
          result = model_name;
          min = distance;
        }
      }
      scanner.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }

    //output result
    double confidence = 1 / ((min*0.001) + 0.1) * 10;
    confidence = (double) Math.round(confidence * 100) / 100; //round to two decimal places
    System.out.println("\nIt's a " + result + " (" + confidence + "% confidence).");

    //call train
    if (confidence != 100) {
      train(currentValues, model_name);
    }
  }

  private static int[][] convertToAvgRGB(BufferedImage image) {

    int width = image.getWidth();
    int height = image.getHeight();
    int[][] pixels = new int[height][width];
    int[][] result = new int[3][900];

    //2D array of hexidecimal colour values
    for (int row = 0; row < height; row++) {
        for (int col = 0; col < width; col++) {
          pixels[row][col] = image.getRGB(col, row);
        }
    }

    System.out.println("Scratching head...");

    //convert to average RBG values
    //red = 0, green = 1, blue = 2
    Color pixelColour;
    int quad = -1;
    int quad_height = height / 30;
    int quad_width = width / 30;

    for (int quad_y = 0; quad_y < 30; quad_y++) {
      for (int quad_x = 0; quad_x < 30; quad_x++) {
        //one quadrant
        quad++;
        for (int row = 0 + (quad_height * quad_y); row < quad_height + (quad_height * quad_y); row++) {
          for (int col = 0 + (quad_width * quad_x); col < quad_width + (quad_width * quad_x); col++) {
            pixelColour = new Color(pixels[row][col]);
            result[0][quad] = result[0][quad] + pixelColour.getRed();
            result[1][quad] = result[1][quad] + pixelColour.getGreen();
            result[2][quad] = result[2][quad] + pixelColour.getBlue();
          }
        }
      result[0][quad] = result[0][quad] / (quad_height * quad_width);
      result[1][quad] = result[1][quad] / (quad_height * quad_width);
      result[2][quad] = result[2][quad] / (quad_height * quad_width);
      //System.out.println((quad + 1) + ": " + result[0][quad] + "," + result[1][quad] + "," + result[2][quad]);
      //end one quadrant
      }
    }

    return result;
   }

  private static void train (int[][] currentValues, String model_name) {
    System.out.println("Is that correct? Type \"yes\" or provide the correct label.");
    String answer = System.console().readLine();
    String label = "";
    if (answer.equals("yes")) {
      label = model_name;
    } else {
      label = answer;
    }

    //write model txt file
    try {
      PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("models.txt", true)));
      writer.print(label + ";");
      for (int i = 0; i < currentValues[0].length; i++) {
        writer.print(currentValues[0][i] + "," + currentValues[1][i] + "," + currentValues[2][i] + ";");
      }
      writer.println();
      writer.close();
    } catch (Exception e) {
      //handle exception
    }
  }

  private static void show (int[][] model_values) {
    StdDraw.setXscale(0.0, 30.0);
    StdDraw.setYscale(0.0, 30.0);
    StdDraw.enableDoubleBuffering();
    int quad = -1;
    double coefficient;
    double R, G, B;
    for (int quad_y = 29; quad_y >= 0; quad_y--) {
      for (int quad_x = 0; quad_x < 30; quad_x++) {
        quad++;
        coefficient = 10 * Math.sin(0.21 * quad - 1.7) + (-0.00009 * Math.pow(quad - 450, 2)) + 29;
        coefficient = coefficient / 39;
        R = coefficient * model_values[0][quad];
        G = coefficient * model_values[1][quad];
        B = coefficient * model_values[2][quad];
        StdDraw.setPenColor((int) R, (int) G, (int) B);
        StdDraw.filledSquare(quad_x + 0.5, quad_y + 0.5, 0.5);
      }
    }
    StdDraw.show(50);
  }
}