/
NeuroNet.java
270 lines (241 loc) · 8.42 KB
/
NeuroNet.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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
/*
* 4 pixel camera,
*
* */
import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.awt.Color;
import java.io.IOException;
import java.util.Random;
public class NeuroNet
{
private static final int IMG_WIDTH = 800;
private static final int IMG_HEIGHT = 800;
public static void main(String[] args) throws Exception
{
/*get image from Internet and saves it to src folder*/
String imageUrl = "https://stepupandlive.files.wordpress.com/2014/09/3d-animated-frog-image.jpg";
String destinationFile = "image.jpg";
saveImage(imageUrl, destinationFile);
/*
* Read image
* Get the RGB values of each pixels
*/
File originalImage = new File("C:\\Users\\hzhang127\\workspace\\NeuroNetwork\\image.jpg");
BufferedImage img=null;
double[][][] rgbTable=new double[IMG_WIDTH][IMG_HEIGHT][4]; // A table used to store the RGB values of the image's pixels
double[][] greyScaledImage = new double[IMG_WIDTH][IMG_HEIGHT]; // A table to store greyScaled image.
try
{
img= ImageIO.read(originalImage);
int type = img.getType() == 0? BufferedImage.TYPE_INT_ARGB : img.getType();
/* resize the image*/
BufferedImage resizeImage = resizeImageWithHint(img, type);
ImageIO.write(resizeImage, "jpg", new File("C:\\Users\\hzhang127\\workspace\\NeuroNetwork\\img_fjords.jpg"));
//BufferedImage grayscaleImage= new BufferedImage(img.getWidth(),img.getHeight(),BufferedImage.TYPE_INT_ARGB);
// int count=0;
System.out.println("The height of the rescaled image is:"+resizeImage.getHeight() );
System.out.println("The width of the rescaled image is:"+resizeImage.getWidth() );
for(int i=0;i<resizeImage.getWidth();i++)
{
for(int j=0;j<resizeImage.getHeight();j++)
{
Color c= new Color(resizeImage.getRGB(i, j));
rgbTable[i][j][0]=c.getRed();
rgbTable[i][j][1]=c.getGreen();
rgbTable[i][j][2]=c.getBlue();
rgbTable[i][j][3]=c.getAlpha();
greyScaledImage[i][j]=(c.getRed()+c.getGreen()+c.getBlue())/3; // Instead of using three values for each pixel, we take the weighted average.
// count++;
// System.out.println(count+":"+"red is:"+rgbTable.clone()[i][j][0]+"alpha is"+rgbTable.clone()[i][j][3]+"" );
}
}
}
catch(IOException e)
{
System.out.println("Error: "+e);
}
//System.out.println("The matrix representation of the image is as follow:");
//printMatrix(greyScaledImage);
/*
* Create neuro network
*/
/* 1st Convolution layer frames*/
int frameWidth=20;
int frameHeight=20;
int numberOfFeatures=20;
ConvolutedLayerNode[] convLayer = new ConvolutedLayerNode[numberOfFeatures]; // the nodes in a convoluted layer
//double[][][] frame= new double[IMG_WIDTH*IMG_HEIGHT/(frameWidth*frameHeight)][frameWidth][frameHeight]; // convoluted layer
for(int k=0;k<numberOfFeatures;k++)
{
double[][] tempConvolutedFrame = new double[IMG_WIDTH/frameWidth][IMG_HEIGHT/frameHeight];// the convoluted frame associated with each feature
for(int i=0;i<IMG_WIDTH;i=i+frameWidth)
{
for(int j=0;j<IMG_HEIGHT;j=j+frameHeight)
{
/*
* a frame to store each frames of the image after we divided it into frames
*/
double[][] tempFrame= new double[frameWidth][frameHeight];
for(int x=0;x<frameWidth;x++)
{
for(int y=0;y<frameHeight;y++)
{
tempFrame[x][y]=greyScaledImage[i+x][j+y];
}
}
convLayer[k]= new ConvolutedLayerNode(); // Create a Convolutional layer node
/*
* create the weights by giving random datas
*/
double[][] weight= new double[frameWidth][frameHeight];
Random randomGenerator= new Random();
for(int n=0;n<frameWidth;n++)
{
for(int m=0;m<frameHeight;m++)
{
weight[n][m]=randomGenerator.nextDouble()*2-1;
}
}
//printMatrix(weight);
/*
* update convoluted frame
*/
convLayer[k].setWeight(weight); // set the weight of the slides
convLayer[k].setBias(0.5); // set the bias to be 0.5
tempConvolutedFrame[i/frameWidth][j/frameHeight]= sigmoid(sum2d(multMatricesC(convLayer[k].getWeight(),tempFrame))); // store sum of weighed value in
//System.out.println("The weighted sum of frame starting from "+i+" width and "+j+" depth and feature number "+k+" is :"+tempConvolutedFrame[i/frameWidth][j/frameHeight]);
}
}
convLayer[k].setFrames(tempConvolutedFrame);
System.out.println("The weighted image with feature "+k+" is as follow:");
printMatrix(convLayer[k].getFrames());
}
/* Second convolutional layer*/
}
/*
* A function to print a matrix
*/
public static void printMatrix(double[][] m)
{
try{
int rows = m.length;
int columns = m[0].length;
String str = "|\t";
for(int i=0;i<rows;i++){
for(int j=0;j<columns;j++){
str += m[i][j] + "\t";
}
System.out.println(str + "|");
str = "|\t";
}
System.out.println();
}
catch(Exception e){System.out.println("Matrix is empty!!");}
}
/*
* A function that multiply two matrices Entries
*/
public static double[][] multMatricesC(double[][] A, double[][] B)
{
int aRows = A.length;
int aColumns = A[0].length;
int bRows = B.length;
int bColumns = B[0].length;
if (aColumns != bColumns||aRows != bRows)
{
throw new IllegalArgumentException("A:Rows: " + aColumns + " did not match B:Columns " + bRows + ".");
}
double[][] C = new double[aRows][bColumns];
for (int i = 0; i < aRows; i++)
{
for (int j = 0; j < bColumns; j++)
{
C[i][j] = 0.00000;
}
}
for (int i = 0; i < aRows; i++)
{ // aRow
for (int j = 0; j < bColumns; j++)
{ // bColumn
C[i][j]=A[i][j]*B[i][j];
}
}
return C;
}
/*
* A function to compute the sum of entries in an matrix
*/
public static double sum2d (double[ ][ ] array2d)
{
double sum = 0;
for (int row=0; row < array2d.length; row++)
{
for (int col=0; col < array2d[row].length; col++)
{
sum = sum + array2d [row][col];
}
}
return sum;
}
/*
* Function used to saves an image in a url to src folder
*/
public static void saveImage(String imageUrl, String destinationFile) throws IOException {
URL url = new URL(imageUrl);
InputStream is = url.openStream();
OutputStream os = new FileOutputStream(destinationFile);
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
os.close();
}
/*
* Sigmoid Function
*/
public static double sigmoid(double x)
{
return (1/( 1 + Math.pow(Math.E,(-1*x))));
}
/*
* Resize image
*/
private static BufferedImage resizeImage(BufferedImage originalImage, int type)
{
BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
g.dispose();
return resizedImage;
}
/*
* Resize image with hint
*/
private static BufferedImage resizeImageWithHint(BufferedImage originalImage, int type)
{
BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
g.dispose();
g.setComposite(AlphaComposite.Src);
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
return resizedImage;
}
}