-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBuyingPatternAnalysisGUI.java
More file actions
1531 lines (1387 loc) · 61.8 KB
/
BuyingPatternAnalysisGUI.java
File metadata and controls
1531 lines (1387 loc) · 61.8 KB
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package ImageLearn;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import org.apache.commons.io.FileUtils;
import com.lifetouch.lti.camera.metadata.ImageMetadataException;
import com.lifetouch.lti.camera.metadata.ImageMetadataTag;
import com.lifetouch.lti.camera.metadata.VegaImageMetadataExtractor;
import com.lifetouch.lti.camera.metadata.VegaImageMetadataExtractor.Requirements;
import com.lifetouch.lti.image.ipp.ifs.IppTranspose.IppTransposeType;
//import com.lifetouch.lti.vega.utils.ImageUtils;
//import com.lifetouch.lti.util.ImageUtils;
import ImageLearn.FaceFeatureForPose;
import f4s.FaceFeatureDetector.FeatureIndex;
import f4s.FaceFeatureDetector.Finder;
import java.awt.Font;
import java.awt.Image;
import java.awt.Color;
import java.awt.SystemColor;
import java.awt.Toolkit;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
import javax.swing.JTextArea;
public class PortraitAnalyzer {
static int faceConfidenceThreshold = 50;
private String myField;
static List<String> imageList = new ArrayList<String>();
// Pose thresholds
private final static double thresholdFullLengthHigh = 0.06;
private final static double thresholdThreeQuarterLow = 0.06;
private final static double thresholdThreeQuarterHigh = 0.10;
private final static double thresholdHalfLengthLow = 0.10;
private final static double thresholdHalfLengthHigh = 0.14;
private final static double thresholdHeadAndShouldersLow = 0.14;
private final static double thresholdHeadAndShouldersHigh = 0.22;
private final static double thresholdCloseUpLow = 0.22;
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PortraitAnalyzer window = new PortraitAnalyzer();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public PortraitAnalyzer() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setBackground(SystemColor.menu);
frame.setBounds(100, 100, 556, 389);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton = new JButton("Browse Image Directory");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser f = new JFileChooser();
f.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
f.showSaveDialog(null);
File selectedImageFile = f.getSelectedFile();
String selectedImageDirectory = selectedImageFile.getPath();
System.out.println("Selected image directory:" + selectedImageDirectory);
setMyField(selectedImageDirectory);
}
});
btnNewButton.setFont(new Font("Tahoma", Font.BOLD, 11));
btnNewButton.setBounds(35, 130, 175, 80);
frame.getContentPane().add(btnNewButton);
JButton btnNewButton_1 = new JButton("Run");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
long startTime = System.nanoTime();
List<String> listOfImages = new ArrayList<String>();
String imageDirecotory = getMyField();
if (imageDirecotory == null)
{
PortraitAnalyzer.infoBox("Please select directory of images before run!"
+ " Exiting the program now...", "Image direcotry NOT selected!");
System.exit(0);
}
System.out.println("Passed image directory:" + imageDirecotory);
// First check if text files exist, delete them
String faceTextPath = imageDirecotory + "/Results/Faces/PredictionResults.txt";
File file1 = new File(faceTextPath);
try {
Files.deleteIfExists(file1.toPath());
} catch (IOException e2) {
e2.printStackTrace();
}
String poseTextPath = imageDirecotory + "/Results/PoseResults.txt";
File file2 = new File(poseTextPath);
try {
Files.deleteIfExists(file2.toPath());
} catch (IOException e2) {
e2.printStackTrace();
}
String BKGTextPath = imageDirecotory + "/Results/BackgroundColorResults.txt";
File file3 = new File(BKGTextPath);
try {
Files.deleteIfExists(file3.toPath());
} catch (IOException e2) {
e2.printStackTrace();
}
String combinedTextPath = imageDirecotory + "/Results/CombinedResults.txt";
File file4 = new File(combinedTextPath);
try {
Files.deleteIfExists(file4.toPath());
} catch (IOException e2) {
e2.printStackTrace();
}
String resultsPath = imageDirecotory + "/Results";
try {
FileUtils.deleteDirectory(new File(resultsPath));
} catch (IOException e2) {
e2.printStackTrace();
}
File dir = new File(imageDirecotory);
String[] extensions = new String[] { "jpg" , "JPG" };
try {
System.out.println("Getting all .jpg and .JPG files in " + dir.getCanonicalPath()
+ " including those in subdirectories");
} catch (IOException e2) {
e2.printStackTrace();
}
List<File> files = (List<File>) FileUtils.listFiles(dir, extensions, true);
Collections.sort(files);
int totalNumber = files.size();
System.out.println("Total number of images in directory: " + totalNumber);
/////////////////////////////////////////////////////////////////////
//---------------- First perform preprcoessing --------------------//
try {
listOfImages = preprcoessing(imageDirecotory);
} catch (ImageMetadataException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
System.out.println("Preprocessing finished successfully.");
////////////////////////////////////////////////////////////////////////
//------------------ Now do facial expression recognition ------------//
System.out.println("Now doing facial expression recognition.");
processFacialExpression(imageDirecotory);
System.out.println("Finished facial expression recognition.");
////////////////////////////////////////////////////////////////////////
//------------------ Then do BKG detection ------------//
System.out.println("Now doing BKG detection.");
processBKGdetection(imageDirecotory);
System.out.println("Finished BKG detection.");
////////////////////////////////////////////////////////////////////////
//------------------ Then do CapGown Detection ------------//
System.out.println("Now doing CapGown Detection.");
processCapGownDetection(imageDirecotory);
System.out.println("Finished CapGown Detection.");
////////////////////////////////////////////////////////////////////////
//------------------ Then do Gender ID ------------//
System.out.println("Now doing Gender ID.");
processGenderID(imageDirecotory);
System.out.println("Finished Gender ID.");
/////////////////////////////////////////////////////////////////////////
//------------------- Then do pose estimation ----------------------//
System.out.println("Now doing pose estimation.");
try {
prcoessPoseEstimation(listOfImages, imageDirecotory);
} catch (ImageMetadataException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
System.out.println("Pose estimation finished.");
//-------------------- Finally create the final results text file ----------------//
System.out.println("Now creating the final results text file.");
try {
createFinalTextResults(imageDirecotory, files);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
long stopTime = System.nanoTime();
System.out.println("\nProcessing all images took " + (stopTime - startTime) / 1e9 + " Seconds to run");
System.out.println("\n ALL PROCESSES FINISHED SUCCESSFULLY!");
Toolkit.getDefaultToolkit().beep();
JOptionPane.showMessageDialog(null, "All processes finished successfully! You can look at the Results now." );
}
});
btnNewButton_1.setFont(new Font("Tahoma", Font.BOLD, 11));
btnNewButton_1.setBounds(360, 130, 153, 80);
frame.getContentPane().add(btnNewButton_1);
JButton btnResults = new JButton("Results");
btnResults.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// if results text file exists, open it. Otherwise, let user know to run first!
String imageDirecotory = getMyField();
if (imageDirecotory == null)
{
PortraitAnalyzer.infoBox("Please select directory of images, then run, then look at results! Exiting the program now...", "Image direcotry NOT selected!");
System.exit(0);
}
String resultsTextPath = imageDirecotory + "/Results/CombinedResults.txt";
File f = new File(resultsTextPath);
if(f.exists() && !f.isDirectory()) {
ProcessBuilder pb = new ProcessBuilder("Notepad.exe", resultsTextPath);
try {
pb.start();
} catch (IOException e1) {
e1.printStackTrace();
}
}else{
PortraitAnalyzer.infoBox("Please select directory of images, then run, then look at results! Exiting the program now...", "Image direcotry NOT selected!");
System.exit(0);
}
String path = System.getProperty("user.dir");
String BKGimagePath = path + "/Other/BKGsNumbered.JPG";
BufferedImage img = null;
try {
img = ImageIO.read(new File(BKGimagePath));
} catch (IOException e1) {
PortraitAnalyzer.infoBox("BKGsNumbered.JPG does not exist! Exiting the program now...", "BKGsNumbered.JPG does not exist!");
}
JLabel lbl = new JLabel();
lbl.setSize(600, 900);
Image dimg = img.getScaledInstance(lbl.getWidth(), lbl.getHeight(),
Image.SCALE_SMOOTH);
ImageIcon icon = new ImageIcon(dimg);
JFrame frame = new JFrame();
frame.setLayout(new FlowLayout());
frame.setSize(600, 900);
lbl.setIcon(icon);
frame.add(lbl);
frame.setVisible(true);
// frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
});
btnResults.setFont(new Font("Tahoma", Font.BOLD, 11));
btnResults.setBounds(202, 249, 153, 68);
frame.getContentPane().add(btnResults);
JButton btnHelp = new JButton("Help");
btnHelp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "1- This program has been tested to"
+ " run on Windows 10 64 bit. Other OS are not currently "
+ "supported.\n2- You need to have JRE/JDK installed on "
+ "your system to run this program.\n3- Make sure you follow this recipe: "
+ "First Browse to the directory of images, Then Run, and finally "
+ "look at Results.\n4- Make sure you have admin rights in the "
+ "directory of images. This program needs to copy some files there. "
+ "\nDo NOT run this program on an image "
+ "directory located on a CD/DVD. Copy them to your local "
+ "hard drive and Run.\n5- If the program was unresponsive, "
+ "close the program and reopen.\n6- After you run the program, "
+ "you can find the debug information under Results subdirectory"
+ " under your image directory.");
}
});
btnHelp.setFont(new Font("Tahoma", Font.BOLD, 11));
btnHelp.setBounds(35, 28, 89, 23);
frame.getContentPane().add(btnHelp);
JButton btnAbout = new JButton("About");
btnAbout.setFont(new Font("Tahoma", Font.BOLD, 11));
btnAbout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "This program analyses the images in a directory"
+ " for pose, expression, background, gender, and cap and gown. It will report"
+ " the followings: \n1- Facial expression (full smile, game face, and soft smile)"
+ " \n2- Pose (full length, 3/4, half length, head and shoulders, and close up)"
+ " \n3- Background (16 backgrounds). \n4- Gender (Male/Female). "
+ "\n5- Cap and Gown (Yes/No). \nIt will also reports a summary"
+ " of statistics for each category at the end of the results text file.");
}
});
btnAbout.setBounds(427, 28, 89, 23);
frame.getContentPane().add(btnAbout);
JLabel lblPortraitAnalyzerV = new JLabel("Portrait Analyzer");
lblPortraitAnalyzerV.setForeground(Color.BLUE);
lblPortraitAnalyzerV.setFont(new Font("Tahoma", Font.BOLD, 17));
lblPortraitAnalyzerV.setBounds(202, 50, 195, 32);
frame.getContentPane().add(lblPortraitAnalyzerV);
JTextArea textArea = new JTextArea();
textArea.setFont(new Font("Tahoma", Font.BOLD, 14));
textArea.setForeground(Color.RED);
textArea.setText("1");
textArea.setBounds(120, 97, 12, 22);
frame.getContentPane().add(textArea);
JTextArea textArea_1 = new JTextArea();
textArea_1.setText("2");
textArea_1.setForeground(Color.RED);
textArea_1.setFont(new Font("Tahoma", Font.BOLD, 14));
textArea_1.setBounds(427, 97, 12, 22);
frame.getContentPane().add(textArea_1);
JTextArea textArea_2 = new JTextArea();
textArea_2.setText("3");
textArea_2.setForeground(Color.RED);
textArea_2.setFont(new Font("Tahoma", Font.BOLD, 14));
textArea_2.setBounds(267, 216, 12, 22);
frame.getContentPane().add(textArea_2);
}
public String getMyField()
{
//include validation, logic, logging or whatever you like here
return this.myField;
}
public void setMyField(String value)
{
//include more logic
this.myField = value;
}
public static void infoBox(String infoMessage, String titleBar)
{
JOptionPane.showMessageDialog(null, infoMessage, "InfoBox: " + titleBar, JOptionPane.INFORMATION_MESSAGE);
}
public static List<String> preprcoessing(String directoryPath) throws ImageMetadataException, IOException
{
String myDirectoryPath = directoryPath;
try {
deleteDirecotry(myDirectoryPath + "/Results");
} catch (IOException e) {
e.printStackTrace();
}
createDirecotry(myDirectoryPath + "/Results");
createDirecotry(myDirectoryPath + "/Results/Faces");
File dir = new File(myDirectoryPath);
String[] extensions = new String[] { "jpg" , "JPG" };
System.out.println("Getting all .jpg and .JPG files in " + dir.getCanonicalPath()
+ " including those in subdirectories");
List<File> files = (List<File>) FileUtils.listFiles(dir, extensions, true);
Collections.sort(files);
int num = 0;
if (files != null) {
for (File child : files) {
num = num + 1;
int total = files.size();
System.out.println("Pre processing image number:" + num + "\tOut of:" + total);
String imgPath = child.getAbsolutePath();
// System.out.println(imgPath);
// First Autorotate the image to make it portrait
autoRotate(imgPath);
// Then check to see if any faces are found
Finder faceFinder = new Finder();
String stringLandmarks = faceFinder.DetectLandmarks(imgPath, -1);
int[] binLandmarks = faceFinder.ParseMPEG4Landmarks(stringLandmarks);
int faceCount = Finder.GetFaceCount(binLandmarks );
// System.out.println("Face count = " + faceCount);
int faceConfidence = 0;
int faceConfidenceFinal = 0;
int faceId = 0;
// If no faces found, rotate 90 degree and try again.
if(faceCount < 1)
{
rotate90(imgPath);
// Then check to see if any faces are found
faceFinder = new Finder();
stringLandmarks = faceFinder.DetectLandmarks(imgPath, -1);
binLandmarks = faceFinder.ParseMPEG4Landmarks(stringLandmarks);
faceCount = Finder.GetFaceCount(binLandmarks );
// System.out.println("Face count = " + faceCount);
if(faceCount < 1)
{
// Rotate back to original
rotate270(imgPath);
}
}
// Chose only the high confidence faces
if(faceCount > 0)
{
for( int i = 0; i < faceCount; ++i )
{
faceConfidence = Finder.GetFeatureForFace(binLandmarks, FeatureIndex.ConfidenceFactorFace, i + 1);
// System.out.println( "Face Confidence : " + faceConfidence);
if(faceConfidence > faceConfidenceThreshold)
{
faceConfidenceFinal = faceConfidence;
// System.out.println( "Face Confidence Final : " + faceConfidenceFinal);
faceId = i + 1;
// System.out.println( "Face ID : " + faceId);
}
}
}
if(faceCount > 0 && faceConfidenceFinal > faceConfidenceThreshold)
{
// Save the list of images that are acceptable for future.
imageList.add(imgPath);
// Now crop the faces
int faceTopLeftX = Finder.GetFeatureForFace(binLandmarks, FeatureIndex.FaceBoxTopLeftX, faceId);
int faceTopLeftY = Finder.GetFeatureForFace(binLandmarks, FeatureIndex.FaceBoxTopLeftY, faceId);
int faceTopRightX = Finder.GetFeatureForFace(binLandmarks, FeatureIndex.FaceBoxTopRightX, faceId);
int faceBottomLeftY = Finder.GetFeatureForFace(binLandmarks, FeatureIndex.FaceBoxBottomLeftY, faceId);
int cropWidth = Math.abs(faceTopRightX - faceTopLeftX);
int cropHeight = Math.abs(faceBottomLeftY - faceTopLeftY);
File imageFile = new File(imgPath);
String imageNameOnly = imageFile.getName();
String saveImagePath = myDirectoryPath + "/Results/Faces/" + imageNameOnly;
File fileToRead = new File(imgPath);
BufferedImage faceBufferedImage = cropImage(fileToRead, faceTopLeftX, faceTopLeftY, cropWidth, cropHeight);
try {
ImageIO.write(faceBufferedImage, "jpg", new File(saveImagePath));
} catch (IOException e) {
e.printStackTrace();
}
}else{ // if face count < 1 then skip this image.
System.out.println("Warning! Could not find a face! Continuing to next image.");
FileUtils.copyFileToDirectory(new File(imgPath), new File(myDirectoryPath + "/Results/NA"));
}
} // end for
} else { // if directory is null, throw an error!
System.out.println("ERROR! Not a directory!");
}
System.out.println("Finished cropping faces.");
// System.out.println("Here is the list of acceptable images:" + imageList);
System.out.println("Total number of face images:" + imageList.size());
return imageList;
}
private static void createDirecotry(String directoryName) {
File newDirectory = new File(directoryName);
// if the directory does not exist, create it
if (!newDirectory.exists()) {
System.out.println("Creating directory: " + newDirectory.getName());
boolean result = false;
try{
newDirectory.mkdirs();
result = true;
}
catch(SecurityException se){
//handle it
}
if(result) {
System.out.println("Direcotory created sucessfully.");
}
}
}
public static void deleteDirecotry(String directoryName) throws IOException {
Path directory = Paths.get(directoryName);
if (Files.exists(directory)) {
Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
}
System.out.println("Direcotory deleted sucessfully.");
}
// File newDirectory = new File(directoryName);
// // if the directory exists, delete it
// if (newDirectory.exists()) {
// System.out.println("Recursively deleting directory: " + newDirectory.getName());
// boolean result = false;
// try{
// FileUtils.deleteDirectory(new File("directory"));
// }
// catch(SecurityException se){
// //handle it
// }
// if(result) {
// System.out.println("Direcotory deleted sucessfully.");
// }
// }
// filter to identify images based on their extensions
static final FilenameFilter IMAGE_FILTER = new FilenameFilter() {
// array of supported extensions (use a List if you prefer)
String[] EXTENSIONS = new String[]{
"jpg", "JPG" // and other formats you need
};
public boolean accept(final File dir, final String name) {
for (String ext : EXTENSIONS) {
if (name.endsWith("." + ext)) {
return (true);
}
}
return (false);
}
};
private static void autoRotate(String imagePath) throws IOException, ImageMetadataException {
File imageFile = new File(imagePath);
BufferedImage originalImage = ImageIO.read(imageFile);
int orientation = 0;
try {
orientation = (Integer) new VegaImageMetadataExtractor(imageFile).extract(Requirements.REQUIRE_BASICS).get(ImageMetadataTag.ORIENTATION);
} catch (Exception ex) {
ex.printStackTrace();
}
BufferedImage rotatedImg = originalImage;
switch (orientation) {
case 0:
// Normal portrait, continue
break;
case 90:
// Rotate clockwise 270 degrees
rotatedImg = ImageUtils.transpose(originalImage, IppTransposeType.ROTATE_270);
break;
case 180:
// Rotate clockwise 180 degrees
rotatedImg = ImageUtils.transpose(originalImage, IppTransposeType.ROTATE_180);
break;
case 270:
// Rotate clockwise 90 degrees
rotatedImg = ImageUtils.transpose(originalImage, IppTransposeType.ROTATE_90);
break;
default:
break;
}
try {
ImageIO.write(rotatedImg, "jpg", new File(imagePath));
} catch (IOException e) {
e.printStackTrace();
}
}
private static void rotate90(String imagePath) throws IOException, ImageMetadataException {
File imageFile = new File(imagePath);
BufferedImage originalImage = ImageIO.read(imageFile);
BufferedImage rotatedImg = originalImage;
// Normal portrait, continue
// Rotate clockwise 270 degrees
// rotatedImg = ImageUtils.transpose(originalImage, IppTransposeType.ROTATE_270);
// // Rotate clockwise 180 degrees
// rotatedImg = ImageUtils.transpose(originalImage, IppTransposeType.ROTATE_180);
// Rotate clockwise 90 degrees
rotatedImg = ImageUtils.transpose(originalImage, IppTransposeType.ROTATE_90);
try {
ImageIO.write(rotatedImg, "jpg", new File(imagePath));
} catch (IOException e) {
e.printStackTrace();
}
}
private static void rotate270(String imagePath) throws IOException, ImageMetadataException {
File imageFile = new File(imagePath);
BufferedImage originalImage = ImageIO.read(imageFile);
BufferedImage rotatedImg = originalImage;
// Normal portrait, continue
// Rotate clockwise 270 degrees
// rotatedImg = ImageUtils.transpose(originalImage, IppTransposeType.ROTATE_270);
// // Rotate clockwise 180 degrees
// rotatedImg = ImageUtils.transpose(originalImage, IppTransposeType.ROTATE_180);
// Rotate clockwise 90 degrees
rotatedImg = ImageUtils.transpose(originalImage, IppTransposeType.ROTATE_270);
try {
ImageIO.write(rotatedImg, "jpg", new File(imagePath));
} catch (IOException e) {
e.printStackTrace();
}
}
private static BufferedImage cropImage(File filePath, int x, int y, int w, int h){
try {
BufferedImage originalImgage = ImageIO.read(filePath);
BufferedImage subImgage = originalImgage.getSubimage(x, y, w, h);
return subImgage;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private void processFacialExpression(String imageDirecotory) {
String str = null;
String path = System.getProperty("user.dir");
String faceImagesPath = imageDirecotory + "/Results/Faces";
String exePath = path + "/Other/models/FacialExpression/pyinstaller/predictBatchFastForWindows.exe";
String metaPath = path + "/Other/models/FacialExpression/checkpoints/my_model-9909.meta";
String checkpointsPath = path + "/Other/models/FacialExpression/checkpoints";
// Now Trying to call the exe file from python code with all dependencies included!
try {
ProcessBuilder pb = new ProcessBuilder(exePath, faceImagesPath, metaPath, checkpointsPath);
Process p = pb.start();
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:");
while ((str = stdInput.readLine()) != null) {
System.out.println(str);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):");
while ((str = stdError.readLine()) != null) {
System.out.println(str);
}
}
catch (IOException e1) {
System.err.println("Exception happened - here's what I know: ");
e1.printStackTrace();
}
}
private void processBKGdetection(String imageDirecotory) {
String str = null;
String path = System.getProperty("user.dir");
String exePath = path + "/Other/models/BKGdetection/pyinstaller/predictBatchFastForWindows.exe";
String metaPath = path + "/Other/models/BKGdetection/checkpoints/my_model-9600.meta";
String checkpointsPath = path + "/Other/models/BKGdetection/checkpoints";
// Now Trying to call the exe file from python code with all dependencies included!
try {
ProcessBuilder pb = new ProcessBuilder(exePath, imageDirecotory, metaPath, checkpointsPath);
Process p = pb.start();
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:");
while ((str = stdInput.readLine()) != null) {
System.out.println(str);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):");
while ((str = stdError.readLine()) != null) {
System.out.println(str);
}
}
catch (IOException e1) {
System.err.println("Exception happened - here's what I know: ");
e1.printStackTrace();
}
}
private void processCapGownDetection(String imageDirecotory) {
String str = null;
String path = System.getProperty("user.dir");
String exePath = path + "/Other/models/CapAndGown/pyinstaller/predictBatchFastForWindows.exe";
String metaPath = path + "/Other/models/CapAndGown/checkpoints/my_model-9500.meta";
String checkpointsPath = path + "/Other/models/CapAndGown/checkpoints";
// Now Trying to call the exe file from python code with all dependencies included!
try {
ProcessBuilder pb = new ProcessBuilder(exePath, imageDirecotory, metaPath, checkpointsPath);
Process p = pb.start();
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:");
while ((str = stdInput.readLine()) != null) {
System.out.println(str);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):");
while ((str = stdError.readLine()) != null) {
System.out.println(str);
}
}
catch (IOException e1) {
System.err.println("Exception happened - here's what I know: ");
e1.printStackTrace();
}
}
private void processGenderID(String imageDirecotory) {
String str = null;
String path = System.getProperty("user.dir");
String exePath = path + "/Other/models/GenderIDNonFaces/pyinstaller/predictBatchFastForWindows.exe";
String metaPath = path + "/Other/models/GenderIDNonFaces/checkpoints/my_model-9600.meta";
String checkpointsPath = path + "/Other/models/GenderIDNonFaces/checkpoints";
// Now Trying to call the exe file from python code with all dependencies included!
try {
ProcessBuilder pb = new ProcessBuilder(exePath, imageDirecotory, metaPath, checkpointsPath);
Process p = pb.start();
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:");
while ((str = stdInput.readLine()) != null) {
System.out.println(str);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):");
while ((str = stdError.readLine()) != null) {
System.out.println(str);
}
}
catch (IOException e1) {
System.err.println("Exception happened - here's what I know: ");
e1.printStackTrace();
}
}
private void prcoessPoseEstimation(List<String> listOfAcceptableImages, String myDirectoryPath) throws ImageMetadataException, IOException {
// For testing purposes
String textFilePathList = myDirectoryPath + "/Results/" + "listOfAcceptableImages.txt";
Path textFilePathListPath = Paths.get(textFilePathList);
for(int ii = 0; ii < listOfAcceptableImages.size(); ii++)
{
String imgPath = listOfAcceptableImages.get(ii);
// System.out.println(imgPath);
appendStringToFile(imgPath, textFilePathListPath);
}
// end of For testing purposes
String textFilePath = myDirectoryPath + "/Results/" + "PoseResults.txt";
Path results = Paths.get(textFilePath);
File file = new File(results.toString());
try {
Files.deleteIfExists(file.toPath());
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
}
for(int ii = 0; ii < listOfAcceptableImages.size(); ii++)
{
String imgPath = listOfAcceptableImages.get(ii);
// System.out.println(imgPath);
appendStringToFile(imgPath, results);
// Then check to see if any faces are found
Finder faceFinder = new Finder();
String stringLandmarks = faceFinder.DetectLandmarks(imgPath, -1);
int[] binLandmarks = faceFinder.ParseMPEG4Landmarks(stringLandmarks);
int faceCount = Finder.GetFaceCount(binLandmarks );
// System.out.println("Face count = " + faceCount);
int faceConfidence = 0;
int faceConfidenceFinal = 0;
int faceId = 0;
// Chose only the high confidence faces
if(faceCount > 0)
{
for( int i = 0; i < faceCount; ++i )
{
faceConfidence = Finder.GetFeatureForFace(binLandmarks, FeatureIndex.ConfidenceFactorFace, i + 1);
// System.out.println( "Face Confidence : " + faceConfidence);
if(faceConfidence > faceConfidenceThreshold)
{
faceConfidenceFinal = faceConfidence;
// System.out.println( "Face Confidence Final : " + faceConfidenceFinal);
faceId = i + 1;
// System.out.println( "Face ID : " + faceId);
}
}
}
if(faceCount > 0 && faceConfidenceFinal > faceConfidenceThreshold)
{
int chinX = Finder.GetFeatureForFace(binLandmarks, FeatureIndex.ChinX, faceId);
int chinY = Finder.GetFeatureForFace(binLandmarks, FeatureIndex.ChinY, faceId);
int eyeLeftX = Finder.GetFeatureForFace(binLandmarks, FeatureIndex.EyeLeftCentreX, faceId);
int eyeLeftY = Finder.GetFeatureForFace(binLandmarks, FeatureIndex.EyeLeftCentreY, faceId);
int eyeRightX = Finder.GetFeatureForFace(binLandmarks, FeatureIndex.EyeRightCentreX, faceId);
int eyeRightY = Finder.GetFeatureForFace(binLandmarks, FeatureIndex.EyeRightCentreY, faceId);
String pose = "NA";
if(chinX > 0 && chinY > 0 && eyeLeftX > 0 && eyeLeftY > 0 &&
eyeRightX > 0 && eyeRightY > 0)
{
FaceFeatureForPose faceFeatureForPose = findFaceFeatures(imgPath, faceCount, chinX, chinY,
eyeLeftX, eyeLeftY, eyeRightX, eyeRightY);
String orientation = findOrientation(imgPath);
// System.out.println("Orientation" + orientation);
double faceMeasure = 0;
if(orientation.equals("horizontal")){
faceMeasure = faceFeatureForPose.eyeToChinToImageWidthRatio;
}else if(orientation.equals("vertical")){
faceMeasure = faceFeatureForPose.eyeToChinToImageHeightRatio;
}
if(faceMeasure<thresholdFullLengthHigh){
pose = "FullLength";
System.out.println("Pose:" + pose);
appendStringToFile(pose, results);
}else if(faceMeasure>=thresholdThreeQuarterLow && faceMeasure<thresholdThreeQuarterHigh){
pose = "ThreeQuarterLength";
System.out.println("Pose:" + pose);
appendStringToFile(pose, results);
}else if(faceMeasure>=thresholdHalfLengthLow && faceMeasure<thresholdHalfLengthHigh){
pose = "HalfLength";
System.out.println("Pose:" + pose);
appendStringToFile(pose, results);
}else if(faceMeasure>=thresholdHeadAndShouldersLow && faceMeasure<thresholdHeadAndShouldersHigh){
pose = "HeadAndShoulders";
System.out.println("Pose:" + pose);
appendStringToFile(pose, results);
}else if(faceMeasure>=thresholdCloseUpLow){
pose = "CloseUp";
System.out.println("Pose:" + pose);
appendStringToFile(pose, results);
}
}else{ // if chin x,y < 0 or eye x,y < 0, then skip this image.
System.out.println("ERROR! Could not find the Chin or Eye! Continuing to next image.");
pose = "NA";
appendStringToFile(pose, results);
}
}
}
}
public FaceFeatureForPose findFaceFeatures(String imagePath,
int faceCount, int chinX, int chinY, int eyeLeftX, int eyeLeftY, int eyeRightX,
int eyeRightY) throws ImageMetadataException, IOException
{
BufferedImage bimg = ImageIO.read(new File(imagePath));
int imageWidth = bimg.getWidth();
int imageHeight = bimg.getHeight();
FaceFeatureForPose returnedResults = new FaceFeatureForPose();
returnedResults.eyeToChinToImageHeightRatio = 0;
returnedResults.eyeToChinToImageWidthRatio = 0;
if(faceCount > 0)
{
int eyePointMiddleX = (int) (eyeLeftX + eyeRightX)/2;
int eyePointMiddleY = (int) (eyeLeftY + eyeRightY)/2;
double eyeToChinDistance = Math.sqrt((eyePointMiddleX - chinX)*(eyePointMiddleX - chinX) +
(eyePointMiddleY - chinY)*(eyePointMiddleY - chinY));
double eyeToChinToImageHeightRatio = eyeToChinDistance / imageHeight;
// System.out.printf("Eye to Chin to Image Height = %.2f ", eyeToChinToImageHeightRatio);
double eyeToChinToImageWidthRatio = eyeToChinDistance / imageWidth;
// System.out.printf("Eye to Chin to Image Width = %.2f ", eyeToChinToImageWidthRatio);
returnedResults.eyeToChinToImageHeightRatio = eyeToChinToImageHeightRatio;
returnedResults.eyeToChinToImageWidthRatio = eyeToChinToImageWidthRatio;
}
return returnedResults;
}
public static void appendStringToFile(String message, Path file) throws IOException {
try {
final Path path = file;
Files.write(file, Arrays.asList(message), StandardCharsets.UTF_8,
Files.exists(path) ? StandardOpenOption.APPEND : StandardOpenOption.CREATE);
} catch (final IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
}
}
private String findOrientation(String imagePath) throws IOException {
File imageFile = new File(imagePath);
BufferedImage bufferedImage = ImageIO.read(imageFile);
int imageWidth = bufferedImage.getWidth();
int imageHeight = bufferedImage.getHeight();
String orientation = "";
if(imageWidth > imageHeight){
orientation = "horizontal";
}else{
orientation = "vertical";
}
// System.out.println("Orientation:" + orientation);
return orientation;
}
public int[] calculateRGB(String imagePath, int faceCount,
int[] binLandmarks, int eyeRightX, int eyeRightY) throws ImageMetadataException, IOException
{
int[] averageRGB = new int[3];
BufferedImage bufferedImage = ImageIO.read(new File(imagePath));
int cropWidthStart = (int) (eyeRightX/4);
int cropWidthEnd = (int) (eyeRightX*3/4);
int cropHeightStart = (int) (eyeRightY/4);
int cropHeightEnd = (int) (eyeRightY*3/4);
// int cropWidthStart = 5;
// int cropWidthEnd = bufferedImage.getWidth() - 5;
// int cropHeightStart = 5;
// int cropHeightEnd = bufferedImage.getHeight()/10;
int cropWidth = cropWidthEnd - cropWidthStart + 1;
int cropHeight = cropHeightEnd - cropHeightStart + 1;
// System.out.printf("cropWidthStart = %d, cropHeightStart=%d, cropWidth=%d, cropHeight=%d",
// cropWidthStart, cropHeightStart, cropWidth, cropHeight);