source: other-projects/is-sheet-music-encore/trunk/image-identification-development/src/Main.java@ 33304

Last change on this file since 33304 was 33304, checked in by cpb16, 5 years ago

Backup for computer crash, only lost 5 lines of code in development section. They have been rewritten.

File size: 18.3 KB
Line 
1import org.opencv.core.*;
2import org.opencv.core.Point;
3import org.opencv.highgui.HighGui;
4import org.opencv.imgcodecs.Imgcodecs;
5import org.opencv.imgproc.Imgproc;
6import org.opencv.photo.Photo;
7import static org.opencv.imgcodecs.Imgcodecs.imwrite;
8import java.awt.image.BufferedImage;
9import java.awt.image.DataBufferByte;
10import java.io.File;
11import java.util.ArrayList;
12import java.util.Collection;
13import java.util.Collections;
14import javax.imageio.ImageIO;
15
16//REFERENCES:
17//https://docs.opencv.org/3.4.3/d9/db0/tutorial_hough_lines.
18//https://stackoverflow.com/questions/43443309/count-red-pixel-in-a-given-image
19//https://www.wikihow.com/Calculate-Percentage-in-Java
20//https://riptutorial.com/opencv/example/21963/converting-an-mat-object-to-an-bufferedimage-object
21//https://beginnersbook.com/2013/12/java-arraylist-of-object-sort-example-comparable-and-comparator/
22//https://www.programiz.com/java-programming/examples/standard-deviation
23//https://www.geeksforgeeks.org/how-to-remove-duplicates-from-arraylist-in-java/
24
25
26
27
28//GOAL for 21st
29
30
31//Classifier 01
32//Have args so can call "java image-identification-classifier01 XX XX"
33//args can be parameters in algorthim such as threshold or theta?
34//Run on 5000 images.
35//Record success rates
36//All done with makefile
37
38
39//But first understand houghline transform
40//Know what the algorithm being used is doing.
41//MAke constants for this classifier
42//Make java be able to run on CMD line
43
44public class Main {
45
46 //DEPENDENT FUNCTIONS AND CLASSES
47 static class StartAndEndPoint {
48 //PRIVATES
49 private Point _p1;
50 private Point _p2;
51 //CONSTRUCTOR
52 public StartAndEndPoint(Point p1, Point p2){
53 _p1 = p1;
54 _p2 = p2;
55 }
56 //GETTERS
57 public Point getP1(){
58 return _p1;
59 }
60 public Point getP2(){
61 return _p2;
62 }
63 //SETTERS
64 public void setP1(Point p1){
65 _p1 = p1;
66 }
67 public void setP2(Point p2){
68 _p2 = p2;
69 }
70
71 //ToString
72 public String toString(){
73 return "Start: " + _p1 + " End: " + _p2;
74 }
75 /*
76 //CompareToOverride
77 //Compares start point y co ordinates of input PointArray
78 //With this. start point y co ordinate
79 @Override
80 public double compareTo(StartAndEndPoint comparePointArray){
81 Point comparePoint = (comparePointArray.getP1());
82 return (this.getP1().y) - (comparePoint.y);
83 }
84 */
85 }
86 public static <T> ArrayList<T> removeDuplicates(ArrayList<T> list) {
87 //DIRECTLY COPIED//DIRECTLY COPIED//DIRECTLY COPIED//DIRECTLY COPIED//DIRECTLY COPIED//DIRECTLY COPIED
88 // Function to remove duplicates from an ArrayList
89 // Create a new ArrayList
90 ArrayList<T> newList = new ArrayList();
91 // Traverse through the first list
92 for (T element : list) {
93 // If this element is not present in newList
94 // then add it
95 if (!newList.contains(element)) {
96 newList.add(element);
97 }
98 }
99 // return the new list
100 return newList;
101 //DIRECTLY COPIED//DIRECTLY COPIED//DIRECTLY COPIED//DIRECTLY COPIED//DIRECTLY COPIED//DIRECTLY COPIED
102 }
103 public static double StandardDeviation(double parseArray[])
104 {
105 double mean;
106 double sum =0;
107 double standardDeviation = 0;
108 //calculate sum of array
109 for(int i =0; i > parseArray.length; i++){
110 sum += parseArray[i];
111 }
112 //calculate mean of array
113 mean = sum/parseArray.length;
114 //calculate SD of array
115 for(int j =0; j > parseArray.length; j++){
116 standardDeviation += Math.pow(parseArray[j]-mean, 2);
117 }
118 return Math.sqrt(standardDeviation/parseArray.length);
119 }
120
121 //GLOBAL_CONSTANTS
122 static int CLASSIFIER_HOUGHLINESP_MIN = 10;
123 static int CLASSIFIER_HOUGHLINESP_MAX = 65;
124 static int HOUGHLINEP_THRESHOLD = 10;
125 static int MINLINECOUNT = 40;
126 static double MAXLINEGAP = 1; //4
127 static double SLOPEGRADIENT = 0.02;
128 //SHOULD TURN INTO ARGS
129
130 //CLASSIFYING FUNCTIONS
131 private static BufferedImage toBufferedImage(Mat mat){
132 //MOSTLY COPY PASTE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
133 //MOSTLY COPY PASTE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
134 //https://riptutorial.com/opencv/example/21963/converting-an-mat-object-to-an-bufferedimage-object
135 try{
136 int type = BufferedImage.TYPE_3BYTE_BGR;
137 int bufferSize = mat.channels() * mat.cols() * mat.rows();
138 byte[] b = new byte[bufferSize];
139 //get all the pixels
140 mat.get(0, 0, b);
141 BufferedImage image = new BufferedImage(mat.cols(), mat.rows(), type);
142 final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
143 System.arraycopy(b, 0, targetPixels, 0, b.length);
144 return image;
145 }
146 catch(Exception e){
147 System.err.println(e);
148 }
149 return null;
150 }
151 private static boolean ClassifierPixelCount(BufferedImage img){
152 try {
153 //Read file
154 //BufferedImage img = ImageIO.read(new File(processedFile));
155 int x = img.getWidth();
156 int y = img.getHeight();
157 int pixelCount = 0;
158 int redCount = 0;
159 float percentage = 0;
160
161 //Go Thru every pixel
162 for(int i=0; i < y; i++){
163 for(int j=0;j < x; j++){
164 //Get value for current pixels RGB value
165 int currPixelRGB = img.getRGB(j, i);
166 //Check if pixel is red (hex value of red)
167 if(currPixelRGB == 0xFFFF0000){
168 redCount++;
169 }
170 pixelCount++;
171 }
172 }
173 //Calculate percentage of Red in image
174 percentage = ((float)redCount/(float)pixelCount)*(float)100;
175 //If more than %10 and less than %50 then its sheet music!
176 if(percentage > CLASSIFIER_HOUGHLINESP_MIN && percentage < CLASSIFIER_HOUGHLINESP_MAX){ //MAKE THESE CONSTANTS!!
177 return true;}
178 }
179 catch (Exception e) {
180 System.err.println(e);
181 }
182 return false;
183 }
184 private static boolean ClassifierLineCount(int lineCount){
185
186 if(lineCount>MINLINECOUNT){
187 return true;
188 }
189 else{
190 return false;
191 }
192 }
193 private static ArrayList ClassifierLineClusterOLD(BufferedImage img){
194 ArrayList returnArray = new ArrayList();
195 try {
196
197 //IF THIS WORKS THEN IMPLEMENT A VERSION THAT USES POINTS from the draw line code.
198 //ALSO CHECK OUT K NEAREST NEIGHBOR?
199 //0xFFFF0000 = RED
200
201 //go thru every pixel until find red pixel
202 //get y pos of red pixel
203 //continue with loop until find another red pixel
204 //get y pos of red pixel
205 //compare y pos (if close together then continue loop) else break
206
207 int x = img.getWidth();
208 int y = img.getHeight();
209 int closeLineCount = 0;
210 ArrayList<Integer> redPixelYpos = new ArrayList<Integer>();
211
212
213
214 //Go Thru every pixel
215 for(int i=0; i < y; i++){
216 for(int j=0;j < x; j++){
217 //Get value for current pixels RGB value
218 int currPixelRGB = img.getRGB(j, i);
219 //Check if pixel is red (hex value of red)
220 if(currPixelRGB == 0xFFFF0000) {
221
222 //Store y pos of red pixel if there is no duplicate
223 if(!redPixelYpos.contains(i)){
224 redPixelYpos.add(i);
225 //System.out.println(i );
226 }
227 }
228 }
229 }
230 //Check if any of the lines found are close together and that there has been more than one line found
231 if(redPixelYpos.size()>1){
232 //go through list and compare every value
233 for(int i =0; i< redPixelYpos.size(); i++){
234 //System.out.println("i: " +redPixelYpos.get(i));
235 for(int j=0; j< redPixelYpos.size(); j++){
236 //System.out.println("j: "+redPixelYpos.get(j));
237 //Check if difference is less than 4 and the values are not duplicates.
238 if(Math.abs(redPixelYpos.get(i) - redPixelYpos.get(j)) < 4 && !redPixelYpos.get(j).equals(redPixelYpos.get(i))){
239 closeLineCount++;
240 }
241 }
242 }
243 }
244 int clusterCount = closeLineCount/4;
245
246 if(closeLineCount >= 4){
247 returnArray.add(true);
248 returnArray.add(closeLineCount);
249 returnArray.add(clusterCount);
250 }
251 else{
252 returnArray.add(false);
253 returnArray.add(closeLineCount);
254 returnArray.add(clusterCount);
255 }
256 }
257 catch (Exception e) {
258 System.err.println(e);
259 }
260 return returnArray;
261 }
262
263 private static ArrayList ClassifierLineCluster(ArrayList<StartAndEndPoint> linePointsArray){
264 ArrayList returnArray = new ArrayList();
265 ArrayList<Double> closeLineYPos = new ArrayList();
266 ArrayList<double[]> clusterArray = new ArrayList();
267 int clusterCount = 0;
268 try {
269 if(linePointsArray.size()> 1) {
270
271 //Display input array TESTING PURPOSES
272 for (int i = 0; i < linePointsArray.size(); i++) {
273 System.out.println(linePointsArray.get(i).toString());
274 }
275
276
277 //Check if y points are close together
278 //go thru list and compare values against each other
279 for (int i = 0; i < linePointsArray.size(); i++){
280 //System.out.println("i: "+ linePointsArray.get(i).getP1().y);
281 for (int j = 0; j < linePointsArray.size(); j++) {
282 //System.out.println("j: "+ linePointsArray.get(j).getP1().y);
283 //Check if difference is less than 4 and the values are not duplicates.
284 if(Math.abs(linePointsArray.get(j).getP1().y - linePointsArray.get(i).getP1().y) < 5){
285 if(linePointsArray.get(j).getP1().y != linePointsArray.get(i).getP1().y){
286 closeLineYPos.add(linePointsArray.get(j).getP1().y);
287 }
288 }
289 }
290 }
291
292 System.out.println(" ");
293
294 //Have all y coordinates that close to each other.
295 //Now check if there are four of these are close to each other.
296 if(closeLineYPos.size() >= 4) {
297 //Sort array and remove duplicates
298 Collections.sort(closeLineYPos);
299 closeLineYPos = removeDuplicates(closeLineYPos);
300
301
302 /*for (double num : closeLineYPos){
303 System.out.println(num);
304 } */
305
306
307 //Check first four items, traverse down a step {0,1,2,3} -> {1,2,3,4} -> {2,3,4,5}
308 for(int i= 0; i< closeLineYPos.size(); i++){
309 //If last comparator is within the array bounds.
310 if(i + 3 == closeLineYPos.size()){
311 break;
312 }
313 else{
314 double[] tempArray = new double[4];
315 tempArray[0] = closeLineYPos.get(i + 0);
316 tempArray[1] = closeLineYPos.get(i + 1);
317 tempArray[2] = closeLineYPos.get(i + 2);
318 tempArray[3] = closeLineYPos.get(i + 3);
319 System.out.println(tempArray[0] + " , " + tempArray[1] + " , " + tempArray[2] + " , " + tempArray[3]);
320 //Check standard deviation
321 if(StandardDeviation(tempArray) < 5){
322 //Store array
323 clusterArray.add(tempArray);
324 //Check if more than one item in array
325 if(clusterArray.size() > 1){
326 //check for duplicate yPos in stored arrays (tempArray)
327
328 }
329
330
331 }
332 }
333 }
334
335 //for (double num : closeLineYPos){
336 // System.out.println(num);
337 //}
338 }
339
340 //PROBLEM. Definition of cluster. Need to check if cluster.
341 //check if four lines are close to each other.(four for loops)
342 // then store these four items in an array and add one to the counter.
343 // (will need to check if found 5th item. - DONT NEED TO? Value gained from finding the 5th line? The staffline height?)
344 //
345
346
347
348 //SETUP RETURN ARRAY
349 if(closeLineYPos.size() >= 4){
350 returnArray.add(true);
351 returnArray.add(closeLineYPos.size());
352 returnArray.add(clusterCount);
353 }
354 else{
355 returnArray.add(false);
356 returnArray.add(closeLineYPos.size());
357 returnArray.add(clusterCount);
358 }
359 }
360 }
361 catch (Exception e) {
362 System.err.println(e);
363 }
364 return returnArray;
365 }
366
367
368
369 public static void main(String[] args) {
370
371 System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
372
373 try {
374 ArrayList<StartAndEndPoint> pointArrayList = new ArrayList<>();
375
376 //Variables
377 Mat edgesDetected = new Mat();
378 Mat edgesDetectedRGB = new Mat();
379 String directory = "/Scratch/cpb16/is-sheet-music-encore/download-images/MU/";
380 //!!!!!!!!!!!!!!!!!!!!!!!!!!!NOT!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
381 //mdp.39015097852365-2.png 176 lines Contents page.
382 //mdp.39015097852555-3.png 76 lines
383 String default_file = directory+"SheetMusic/coo.31924062612282-9.png";
384 //String default_file ="TestImages/NotNot/mdp.39015080972303-3.png";
385
386
387 //System.out.println(default_file);
388 //String default_file = "TestImages/NotSheetMusic01.png";
389 //String default_file = "TestImages/NotSheetMusic02.png";
390 //String default_file = "TestImages/SheetMusic01.png";
391 //String default_file = "TestImages/SheetMusic02.png";
392 //String default_file = "TestImages/vLine.png";
393 String filename = ((args.length > 0) ? args[0] : default_file);
394 File file = new File(filename);
395 if(!file.exists()){System.err.println("Image not found: "+ filename);}
396
397 int horizontalLineCount =0;
398
399 // Load an image
400 Mat original = Imgcodecs.imread(filename, Imgcodecs.IMREAD_GRAYSCALE);
401 // Edge detection
402 Imgproc.adaptiveThreshold(original, edgesDetected,255, Imgproc.ADAPTIVE_THRESH_GAUSSIAN_C,Imgproc.THRESH_BINARY_INV, 15, 4);
403
404 //Convert to RGB for future use
405 Imgproc.cvtColor(edgesDetected, edgesDetectedRGB, Imgproc.COLOR_GRAY2BGR);
406
407 Mat linesP = new Mat(); // will hold the results of the detection
408 //(edgeDetectedImage, outputOfDetection(r,Ξ), resolution of rho, resolution of theta, threshold (minimum num of intersections)
409
410 double minLineLength = edgesDetectedRGB.size().width/8;
411
412 Imgproc.HoughLinesP(edgesDetected, linesP, 1, Math.PI / 720, HOUGHLINEP_THRESHOLD, minLineLength,MAXLINEGAP); // runs the actual detection
413 System.out.println("Before Gradient Filtering num lines: " + linesP.rows());
414
415 // Draw the lines
416 for (int x = 0; x < linesP.rows(); x++) {
417 double[] l = linesP.get(x, 0);
418 Point p1 = new Point(l[0], l[1]);
419 Point p2 = new Point(l[2], l[3]);
420 double m = Math.abs(p2.y - p1.y)/(p2.x - p1.x);
421
422 if(m<=SLOPEGRADIENT) {
423 Imgproc.line(edgesDetectedRGB, p1, p2, new Scalar(0, 0, 255), 1, Imgproc.LINE_4, 0);
424 horizontalLineCount++;
425 pointArrayList.add(new StartAndEndPoint(p1, p2));
426 }
427
428 }
429 //Point is a co ordinate (x, y)
430 //Prove by finding number of points from one end to other:
431 //Get width of image.
432 File filenameTest = new File("TestImages/NotSheetMusic02.png");
433 BufferedImage i = ImageIO.read(filenameTest);
434 BufferedImage toBeClassifiedImg = toBufferedImage(edgesDetectedRGB);
435
436 System.out.println("LINE COUNT RESULT: " + ClassifierLineCount(horizontalLineCount) + '\t' +"LineCount: " + horizontalLineCount); //COUNT OF LINES CLASSIFICATION
437 System.out.println("LINE CLUSTER RESULT: " + ClassifierLineClusterOLD(toBeClassifiedImg).get(0) + '\t' + "LinesFound: " + ClassifierLineClusterOLD(toBeClassifiedImg).get(1) + '\t' + "ClustersFound: " + ClassifierLineClusterOLD(toBeClassifiedImg).get(2));
438 //System.out.println("NEW CLUSTER RESULTS: " + ClassifierLineCluster(pointArrayList).get(0) + '\t' + "LinesFound: " + ClassifierLineCluster(pointArrayList).get(1) + '\t' + "ClustersFound: " + ClassifierLineCluster(pointArrayList).get(2));
439 System.out.println(ClassifierLineCluster(pointArrayList));
440
441 //Display Results
442 //HighGui.imshow("Source", original);
443 //HighGui.imshow("Just Edges", justEdges); //TESTING
444 HighGui.imshow("Detected Lines (in red) - positive", edgesDetectedRGB);
445 //HighGui.imshow("Detected Lines (in red) - negative", edgesDetectedRGBProb);
446 //HighGui.imshow("Detected Lines (in red) - edgeDoesntMakeSense", edgeDoesntMakeSense);
447
448 // Wait and Exit
449 HighGui.waitKey();
450 System.exit(0);
451 }
452 catch(Exception e){
453 System.err.println(e);
454 }
455 }
456}
Note: See TracBrowser for help on using the repository browser.