-
Notifications
You must be signed in to change notification settings - Fork 1
/
coin_trainer.py
1545 lines (1325 loc) · 49.6 KB
/
coin_trainer.py
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
import sys
sys.path.append( "../lib/" )
import easygui as eg
from img_processing_tools import *
from PIL import ImageStat, Image, ImageDraw
import cv, cv2
import time
import math
import mahotas
from mahotas.features import surf
import numpy as np
import cPickle as pickle
import csv
import milk
from threading import *
from pylab import *
import scipy.spatial
from CoinServoDriver import *
from coin_tools import *
import glob
import pylab
#from SimpleCV import *
import itertools
from skimage.feature import hog
from skimage.feature import daisy
#from skimage import data
#import matplotlib.pyplot as plt
from skimage import data, color, exposure
from skimage.feature import match_template
#for Structural SIMilarity
import numpy
import scipy.ndimage
from numpy.ma.core import exp
from scipy.constants.constants import pi
import serial
#import matplotlib.pyplot as plt
VIDEO_CAM = 0
CROP_SIZE = 45
MOTOR_POWER = 25
def get_new_coin(servo, dc_motor):
servo.arm_down()
base_frame = snap_shot(VIDEO_CAM )
#time.sleep(1)
new_coin = False
print 'CoinID Motor Driver Comm OPEN:', dc_motor.isOpen()
print 'Connected to: ', dc_motor.portstr
pilimg1 = CVtoPIL(CVtoGray(base_frame))
print "pilimg1 = ", pilimg1
while not new_coin:
if new_coin == False: move_motor(dc_motor, "F", MOTOR_POWER)
if new_coin == False: time.sleep(.6)
motor_stop(dc_motor)
if new_coin == False: time.sleep(.9)
frame = snap_shot(VIDEO_CAM)
pilimg2 = CVtoPIL(CVtoGray(frame))
rms_dif = rmsdiff(pilimg1, pilimg2)
print "RMS Dif:", rms_dif
if rms_dif > 20:
print "New coin...", rms_dif
sys.stdout.write('\a') #beep
new_coin = True
def move_motor(dc_motor, direction, speed):
if direction == "F":
cmd_str = direction + str(speed) + '%\r'
print cmd_str
dc_motor.write ('GO\r')
time.sleep(.01)
dc_motor.write (cmd_str)
time.sleep(.01)
dc_motor.write ('GO\r')
time.sleep(.01)
def motor_stop(dc_motor):
dc_motor.write ('X\r\n')
def snap_shot(usb_device):
print "snapshot called"
#capture from camera at location 0
now = time.time()
webcam1 = None
frame = None
#try:
while webcam1 == None:
webcam1 = cv2.VideoCapture(usb_device)
#webcam1 = cv.CreateCameraCapture(usb_device)
#time.sleep(.05)
#cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_WIDTH, 640)
#cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_HEIGHT, 480)
time.sleep(.1)
for i in range(6):
ret, frame = webcam1.read()
frame = array2cv(frame)
#cv.GrabFrame(webcam1)
#frame = cv.QueryFrame(webcam1)
#except:
# print "******* Could not open WEBCAM *******"
# print "Unexpected error:", sys.exc_info()[0]
#raise
#sys.exit(-1)
#print frame
#print webcam1
#while webcam1 != None:
cv2.VideoCapture(usb_device).release()
#print webcam1
#time.sleep(1)
#print webcam1
return frame
def display_image(img_filename, wait_time):
global ready_to_display
while ready_to_display != True:
time.sleep(1)
#print "waiting"
#time.sleep(wait_time)
img = imread(img_filename)
#img = CVtoPIL(array2cv(img))
#img = img.transpose(1)
#img = img.transpose(2)
#img.save("pil.png")
pylab.ion()
#print "a:", a
pylab.imshow(img)
pylab.draw()
'''
The function to compute SSIM
@param param: img_mat_1 1st 2D matrix
@param param: img_mat_2 2nd 2D matrix
'''
def compute_ssim(img_mat_1, img_mat_2):
#Variables for Gaussian kernel definition
gaussian_kernel_sigma=1.5
gaussian_kernel_width=11
gaussian_kernel=numpy.zeros((gaussian_kernel_width,gaussian_kernel_width))
#Fill Gaussian kernel
for i in range(gaussian_kernel_width):
for j in range(gaussian_kernel_width):
gaussian_kernel[i,j]=\
(1/(2*pi*(gaussian_kernel_sigma**2)))*\
exp(-(((i-5)**2)+((j-5)**2))/(2*(gaussian_kernel_sigma**2)))
#Convert image matrices to double precision (like in the Matlab version)
img_mat_1=img_mat_1.astype(numpy.float)
img_mat_2=img_mat_2.astype(numpy.float)
#Squares of input matrices
img_mat_1_sq=img_mat_1**2
img_mat_2_sq=img_mat_2**2
img_mat_12=img_mat_1*img_mat_2
#Means obtained by Gaussian filtering of inputs
img_mat_mu_1=scipy.ndimage.filters.convolve(img_mat_1,gaussian_kernel)
img_mat_mu_2=scipy.ndimage.filters.convolve(img_mat_2,gaussian_kernel)
#Squares of means
img_mat_mu_1_sq=img_mat_mu_1**2
img_mat_mu_2_sq=img_mat_mu_2**2
img_mat_mu_12=img_mat_mu_1*img_mat_mu_2
#Variances obtained by Gaussian filtering of inputs' squares
img_mat_sigma_1_sq=scipy.ndimage.filters.convolve(img_mat_1_sq,gaussian_kernel)
img_mat_sigma_2_sq=scipy.ndimage.filters.convolve(img_mat_2_sq,gaussian_kernel)
#Covariance
img_mat_sigma_12=scipy.ndimage.filters.convolve(img_mat_12,gaussian_kernel)
#Centered squares of variances
img_mat_sigma_1_sq=img_mat_sigma_1_sq-img_mat_mu_1_sq
img_mat_sigma_2_sq=img_mat_sigma_2_sq-img_mat_mu_2_sq
img_mat_sigma_12=img_mat_sigma_12-img_mat_mu_12;
#c1/c2 constants
#First use: manual fitting
c_1=6.5025
c_2=58.5225
#Second use: change k1,k2 & c1,c2 depend on L (width of color map)
l=255
k_1=0.01
c_1=(k_1*l)**2
k_2=0.03
c_2=(k_2*l)**2
#Numerator of SSIM
num_ssim=(2*img_mat_mu_12+c_1)*(2*img_mat_sigma_12+c_2)
#Denominator of SSIM
den_ssim=(img_mat_mu_1_sq+img_mat_mu_2_sq+c_1)*\
(img_mat_sigma_1_sq+img_mat_sigma_2_sq+c_2)
#SSIM
ssim_map=num_ssim/den_ssim
index=numpy.average(ssim_map)
return index
def template_matching(img_to_match, database_img):
img_to_match_cropped_coin_only = preprocess_img(img_to_match)
database_img_cropped_coin_only = preprocess_img(database_img)
img_to_match_coin_center = find_center_of_coin(img_to_match_cropped_coin_only)
print "Coin only Center of img_to_match_cropped_coin_only:", img_to_match_coin_center
database_img_coin_center = find_center_of_coin(database_img_cropped_coin_only)
print "Coin only Center of database_img_cropped_coin_only:",database_img_coin_center
img_to_match_final_cropped = cv2array(center_crop(img_to_match_cropped_coin_only, img_to_match_coin_center, CROP_SIZE))
database_img_final_cropped = cv2array(center_crop(database_img_cropped_coin_only, database_img_coin_center, CROP_SIZE))
result = match_template(image, coin)
ij = np.unravel_index(np.argmax(result), result.shape)
x, y = ij[::-1]
print x,y
sys.exit(-1)
def preprocess_houghlines (img, num_lines):
temp_img = img
#print img, temp_img
#sys.exit(-1)
USE_STANDARD = True
x = 140
if USE_STANDARD: x = 280
lines = np.array([[[]]])
while len(lines[0]) < num_lines:
try:
edges = cv2.Canny(temp_img, (int(x/2)), x , apertureSize=3)
#time.sleep(.5)
#cv2.imwrite("houghlines_canny.png", edges)
if USE_STANDARD:
lines = cv2.HoughLines(edges, 1, math.pi/180,num_lines)
else:
lines = cv2.HoughLinesP(edges, 1, math.pi/180, 40, None, 40, 10);
if lines == None:
lines = np.array([[[]]])
x = x -2
except:
x = x -2
print "canny threshold: ", x , " Lines: ", len(lines[0])
cv2.imwrite("houghlines_canny_center_cropped.png",edges)
#temp_top_lines = lines[0][:num_lines]
#top_lines = []
#coin_center = ( (int(edges.shape[0]/2),int(edges.shape[1]/2)), edges.shape[0])
#cropped = cv2array(center_crop(array2cv(edges), coin_center, CROP_SIZE))
#cv2.imwrite("houghlines_canny_center_cropped2.png",cropped)
return edges
def houghlines(img, num_lines):
"""
Python: cv2.HoughLinesP(image, rho, theta, threshold[, lines[, minLineLength[, maxLineGap]]]) -> lines
Parameters:
image - 8-bit, single-channel binary source image. The image may be modified by the function.
lines - Output vector of lines. Each line is represented by a 4-element vector, where and are the ending points of each detected line segment.
rho - Distance resolution of the accumulator in pixels.
theta - Angle resolution of the accumulator in radians.
threshold - Accumulator threshold parameter. Only those lines are returned that get enough votes ( ).
minLineLength - Minimum line length. Line segments shorter than that are rejected.
maxLineGap - Maximum allowed gap between points on the same line to link them.
"""
USE_STANDARD = True
x = 140
if USE_STANDARD: x = 480
lines = np.array([[[]]])
while len(lines[0]) < num_lines:
try:
edges = cv2.Canny(img, (int(x/2)), x , apertureSize=3)
if USE_STANDARD:
lines = cv2.HoughLines(edges, 1, math.pi/180,num_lines)
else:
lines = cv2.HoughLinesP(edges, 1, math.pi/180, 40, None, 40, 10);
if lines == None:
lines = np.array([[[]]])
x = x -2
except:
x = x -2
time.sleep(.5)
cv2.imwrite("houghlines_canny.png", edges)
print "x: ", x , " Lines: ", len(lines[0])
temp_top_lines = lines[0][:num_lines]
top_lines = []
coin_center = ( (int(edges.shape[0]/2),int(edges.shape[1]/2)), edges.shape[0])
cropped = cv2array(center_crop(array2cv(edges), coin_center, 10))
print cropped.shape, np.sum(cropped)
#get surf features
#features_surf = surf.surf(edges)
#features_surf = surf.surf(np.mean(img,2))
#print "SURF:", features_surf, " len:", len(features_surf)
#raw_input("Press Enter to continue...")
#sorted_features_surf = sort(features_surf[:25])
#print "SORTED SURF:", sorted_features_surf
#raw_input("Press Enter to continue...")
#return [np.sum(cropped)]
#return sorted_features_surf.flatten()
sys.exit(-1)
if USE_STANDARD:
# for houghlines proper
top_lines = np.asarray(top_lines)
############# Line sort descending (longest to shortest)
top_lines = temp_top_lines[temp_top_lines[:,0].argsort()][::-1]#.flatten()
#top_lines = top_lines[:int(num_lines/2)]
top_lines = top_lines[:5]
print "STANDARD LINES sorted:", top_lines
#sys.exit(-1)
else:
##for houghlineP
for line in temp_top_lines:
dist = scipy.spatial.distance.cdist(([[line[0],line[1]]]), ([[line[2], line[3]]]), 'euclidean')
top_lines.append([line[0],line[1], line[2], line[3], dist[0][0]])
top_lines = np.asarray(top_lines)
############# Line sort descending (longest to shortest)
top_lines = top_lines[top_lines[:,4].argsort()][::-1]#.flatten()
#top_lines = top_lines[:int(num_lines/2)]
top_lines = top_lines[:5]
print "PROB LINES sorted:", top_lines
#hough lines comparison
#theta = atan( (double)(pt2.y - pt1.y)/(pt2.x - pt1.x) ); /*slope of line*/
#degree = theta*180/CV_PI;
features_to_return = []
###### Draw lines on temp img
temp_img = img
if USE_STANDARD:
for (rho, theta) in top_lines:
a = cos(theta)
b = sin(theta)
x0 = a * rho
y0 = b * rho
degree = theta*180/math.pi;
pt1 = (cv.Round(x0 + 1000*(-b)), cv.Round(y0 + 1000*(a)))
pt2 = (cv.Round(x0 - 1000*(-b)), cv.Round(y0 - 1000*(a)))
#if pt2[1] > 380 and pt2[1] < 550:
cv2.line(temp_img, pt1, pt2, (0,0,255), 2)
print degree, rho, theta, pt1, pt2, a, b, x0, y0
features_to_return.append(degree)
else:
for line in top_lines:
#print line, line[0]
pt1 = (int(line[0]),int(line[1]))
pt2 = (int(line[2]),int(line[3]))
cv2.line(temp_img, pt1, pt2, (0,0,255), 2)
cv2.imwrite("houghlines_canny.png", edges)
cv2.imwrite("houghlines.png", temp_img)
#sys.exit(-1)
#raw_input("Press Enter to continue...")
return np.array(features_to_return).flatten()
'''
###distance from center
center_pt = np.array([int(img.shape[0]/2),int(img.shape[1]/2)])
center_dist = []
for point in top_lines:
line_pt1 = np.array([point[0], point[1]])
line_pt2 = np.array([point[2], point[3]])
pt1_dist = scipy.spatial.distance.cdist([center_pt], [line_pt1], 'euclidean')
pt2_dist = scipy.spatial.distance.cdist([center_pt], [line_pt2], 'euclidean')
center_dist.append([pt1_dist[0][0], pt2_dist[0][0]])
center_dist = np.array([center_dist]).flatten()
#avg_feature_histo = np.histogram(avg_features, bins=20)[0]
avg_feature_sum =np.sum(center_dist )
avg_feature_std =np.std(center_dist )
avg_feature_median =np.median(center_dist )
avg_feature_mean = np.mean(center_dist )
avg_feature_var = np.var(center_dist )
#print "histo:", avg_feature_histo, len(avg_feature_histo)
print "center_dist:" , center_dist
print "dist SUM:", avg_feature_sum
print "dist STD:", avg_feature_std
print "dist MEDIAN:", avg_feature_median
print "dist MEAN:", avg_feature_mean
print "dist VAR:", avg_feature_var
center_dist = np.append(center_dist,avg_feature_sum)
center_dist = np.append(center_dist,avg_feature_std)
center_dist = np.append(center_dist,avg_feature_median)
center_dist = np.append(center_dist,avg_feature_mean)
center_dist = np.append(center_dist,avg_feature_var)
print center_dist, len(center_dist)
features_to_return = []
features_to_return.append([avg_feature_sum, avg_feature_std, avg_feature_median, avg_feature_mean, avg_feature_var])
#print "to return:", np.array(features_to_return).flatten()
#raw_input("Press Enter to continue...")
#return np.array(features_to_return).flatten()
#return (center_dist[0], center_dist[1])
####distance from 1st 3 pts
'''
'''
x = np.array([top_lines[0][0], top_lines[0][1]])
y = np.array([top_lines[0][2], top_lines[0][3]])
z = np.array([top_lines[1][0], top_lines[1][1]])
total_lines_point_dist = []
for point in top_lines:
line_pt1 = np.array([point[0], point[1]])
line_pt2 = np.array([point[2], point[3]])
pt1_x_dist = scipy.spatial.distance.cdist([x], [line_pt1], 'euclidean')
pt1_y_dist = scipy.spatial.distance.cdist([y], [line_pt1], 'euclidean')
pt1_z_dist = scipy.spatial.distance.cdist([z], [line_pt1], 'euclidean')
pt2_y_dist = scipy.spatial.distance.cdist([y], [line_pt2], 'euclidean')
pt2_z_dist = scipy.spatial.distance.cdist([z], [line_pt2], 'euclidean')
#print line_pt1, pt1_x_dist, pt1_y_dist, pt1_z_dist, line_pt2, pt2_x_dist, pt2_y_dist, pt2_z_dist
total_lines_point_dist.append([pt1_x_dist[0][0], pt1_y_dist[0][0], pt1_z_dist[0][0], pt2_x_dist[0][0], pt2_y_dist[0][0], pt2_z_dist[0][0]])
total_lines_point_dist = np.array(total_lines_point_dist)#.flatten()
print "total_lines_point_dist:"; print total_lines_point_dist; print
#print np.histogram(total_lines_point_dist, bins=20)[0]
#time.sleep(2)
#sys.exit(-1)
'''
#if USE_STANDARD:
#return top_lines.flatten()
#else:
#return total_lines_point_dist.flatten()
def features360(img, preprocess=True, coin_center=None, step360=360, averaging=False, classID=0):
#print type(img)
if preprocess == True:
cropped_coin_only = preprocess_img(img)
else:
cropped_coin_only = img
print cropped_coin_only
#if str(type(cropped_coin_only)) == "<type 'numpy.ndarray'>":
# cropped_coin_only = array2cv(cropped_coin_only)
#print cropped_coin_only
if coin_center == None:
coin_center = find_center_of_coin(cropped_coin_only)
print "Coin only Center of Coin", coin_center
#sys.exit(-1)
totals_array = []
for x in xrange(0, 360, step360):
rotated_img = rotate_image(cropped_coin_only,x)
#print type(rotated_img)
cv2.imwrite("rotated.png", cv2array(rotated_img))
rotated_img = array2cv(preprocess_houghlines (cv2array(rotated_img), 80))
cropped = cv2array(center_crop(rotated_img, coin_center, CROP_SIZE))
cv2.imwrite("rotated_processed.png", cropped)
#raw_input("kkk")
features = find_features(cropped)
print "Degree:", x#, " Totals:", features
features_to_return = []
if averaging == False:
features_to_return = features
#totals_array.append(features[0])
#totals_array.append(features[1])
#print "totals_array:", totals_array
if classID != 0 and len(features_to_return) > 0 : save_data(features_to_return, classID)
############ Averaging
if averaging == True:
if len(totals_array) != 0:
totals_array = np.sum([totals_array,features], axis = 0)
else:
totals_array = features
#sys.exit(-1)
if x > 0:
xdiv = int (x / step360)
div_array = []
#Build divisor array (number of features to get avg)
#print features
for i in range( len(features)):
div_array.append(xdiv)
#print div_array
avg_features = np.divide(totals_array,div_array).flatten()
print "avg features:", avg_features
#print scipy.spatial.distance.cdist([features.flatten()], [avg_features.flatten()], 'euclidean')
avg_feature_histo = np.histogram(avg_features, bins=20)[0]
avg_feature_sum =np.sum(avg_features.flatten())
avg_feature_std =np.std(avg_features.flatten())
avg_feature_median =np.median(avg_features.flatten())
avg_feature_mean = np.mean(avg_features.flatten())
avg_feature_var = np.var(avg_features.flatten())
print "histo:", avg_feature_histo, len(avg_feature_histo)
print "dist SUM:", avg_feature_sum
print "dist STD:", avg_feature_std
print "dist MEDIAN:", avg_feature_median
print "dist MEAN:", avg_feature_mean
print "dist VAR:", avg_feature_var
if averaging == True:
for i in avg_features:
#print i, avg_feature_histo
features_to_return.append(i)
for i in avg_feature_histo:
#print i, avg_feature_histo
features_to_return.append(i)
features_to_return.extend([avg_feature_sum,avg_feature_std, avg_feature_median, avg_feature_mean , avg_feature_var])
#features_to_return = totals_array
print "features_to_return:", features_to_return, len(features)
#sys.exit(-1)
if classID != 0 and averaging == True: save_data(features_to_return, classID)
return features_to_return
def preprocess_img(img1):
print "Greying image"
grey = array2cv(cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY))
print "Smoothing Image"
cv.Smooth(grey,grey,cv.CV_GAUSSIAN,3,3)
print "Finding Center of Coin"
coin_center = find_center_of_coin(grey)
print "Center of Coin:", coin_center
z = 3
while True:
try:
diameter = int(coin_center[1]/z)
print "trying cropped coin diameter:", diameter
cropped_coin_only = center_crop(grey, coin_center, diameter)
break
except:
z = z + .1
print "Final cropped coin diameter: ", diameter
#cv2.imwrite("cropped_coin.png", cv2array(cropped_coin_only))
#########################################
# Display Results
#######################
#display =Thread(target=display_image, args=("cropped.png",.05,))
#display.daemon=True
#display.start()
print "Finished preprocessing..."
return cropped_coin_only
#return cropped
def binary_compare(img):
#print img, type(img), img.shape
#time.sleep(5)
#print img[0]
img = resize_img(array2cv(img), .25)
cv2.imwrite("postprocessed_img.png", cv2array(img))
features = []
features = flatten(cv2array(img))
return features
def goodfeatures(img):
#print type(img)
#img = array2cv(preprocess_img(img))
features = cv2.goodFeaturesToTrack(img, maxCorners=50, qualityLevel=0.1, minDistance=10)
features = features[:40]
return features.flatten()
def find_features(img):
#img = preprocess_img(img)
#features = houghlines(img, 20)
#features = features360_avg(img)
#features = features360(img, preprocess=True, coin_center=None, step360=1, averaging=False, classID=0)
#features = binary_compare(img)
#features = goodfeatures(img)
#print img, type(img)
#gray scale the image if neccessary
#if img.shape[2] == 3:
# img = img.mean(2)
#img = mahotas.imread(imname, as_grey=True)
#features = mahotas.features.haralick(img).mean(0)
#f2 = features
#print 'haralick features:', features, len(features), type(features[0])
#features = mahotas.features.lbp(img, 1, 8)
#f2 = np.concatenate((f2,features))
#print 'LBP features:', features, len(features), type(features[0])
#features = mahotas.features.tas(img)
#f2 = np.concatenate((f2,features))
#print 'TAS features:', features, len(features), type(features[0])
#features = mahotas.features.zernike_moments(np.mean(img,2), 2, degree=8)
#print 'ZERNIKE features:', features, len(features), type(features[0])
#f2 = np.concatenate((f2,features))
#hu_moments = []
#hu_moments = np.array(cv.GetHuMoments(cv.Moments(cv.fromarray(img))))
#print "HU_MOMENTS: ", hu_moments
#features = flatten(hu_moments)
#f2 = np.concatenate((f2,features))
#features = f2
#DAISY
#gray scale the image if neccessary
if img.shape[2] != None:
img = img.mean(2)
img_step = int(img.shape[1]/4)
img_radius = int(img.shape[1]/10)
descs, descs_img = daisy(img, step=img_step, radius=img_radius, rings=2, histograms=8, orientations=8, normalization='l2', visualize=True)
features = descs.ravel()
print type(descs_img), type(array2cv(descs_img))
cv2.imwrite("descs_img.png", cv2array(array2cv(descs_img)))
#raw_input ("press enter")
#plt.axis('off')
#plt.imshow(descs_img)
#descs_num = descs.shape[0] * descs.shape[1]
#plt.title('%i DAISY descriptors extracted:' % descs_num)
#plt.show()
#print len(features.ravel())
#print len(features[0][0])
#print "All Features: ", features, len(features)
'''
#features_surf = surf.surf(np.mean(img,2))
#print "SURF:", features_surf, " len:", len(features_surf)
try:
import milk
# spoints includes both the detection information (such as the position
# and the scale) as well as the descriptor (i.e., what the area around
# the point looks like). We only want to use the descriptor for
# clustering. The descriptor starts at position 5:
descrs = features_surf[:,5:]
# We use 5 colours just because if it was much larger, then the colours
# would look too similar in the output.
k = 5
surf_pts_to_ID = 50
values, _ = milk.kmeans(descrs, k)
colors = np.array([(255-52*i,25+52*i,37**i % 101) for i in xrange(k)])
except:
values = np.zeros(100)
colors = [(255,0,0)]
surf_img = surf.show_surf(np.mean(img,2), features_surf[:surf_pts_to_ID], values, colors)
#imshow(surf_img)
#show()
'''
#houghlines opencv
#try:
#gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#gray = CVtoGray(numpy2CV(img))
#print gray
#except:
# print "no houghlines available"
#img1 = mahotas.imread('temp.png')
#T_otsu = mahotas.thresholding.otsu(img1)
#seeds,_ = mahotas.label(img > T_otsu)
#labeled = mahotas.cwatershed(img1.max() - img1, seeds)
#imshow(labeled)
#show()
'''
for x in hu_moments[0]:
if x < 0: x = (x * -1)
print math.log10(x)
distmin = 0
degree = 0
for x in range(359):
img2 = cv.CloneImage(array2cv(grey))
#img2 = rotate_image(img2, x)
#print type(img2)
img2 = CVtoPIL(img2)
img2 = img2.rotate(x, expand=1)
#print type(img2)
img2 = PILtoCV(img2,1)
cv.ShowImage("45", img2)
cv.WaitKey()
#print type(img2)
hu_moments2 = []
hu_moments2 = np.array(cv.GetHuMoments(cv.Moments(cv.GetMat(img2))))
hu_moments2 = hu_moments2.reshape(1, (hu_moments2.shape[0]))
distance_btw_images = scipy.spatial.distance.cdist(hu_moments, hu_moments2,'euclidean')
if (distance_btw_images < distmin): degree = x
print x, ": ", log10(distance_btw_images )
#print "HUMOMENTS2: ", hu_moments2
#for x in hu_moments2:
# print math.log10(x)
print "degree = ", degree
'''
return features
def classify(model, features):
return model.apply(features)
def grab_frame_from_video(video):
frame = video.read()
return frame
def predict_class_360(img, step360=360):
cropped_coin_only = preprocess_img(img)
coin_center = find_center_of_coin(cropped_coin_only)
print "Coin only Center of Coin", coin_center
#sys.exit(-1)
classID_votes = [0,0,0,0]
#model = pickle.load( open( "coinvision_ai_model.mdl", "rb" ) )
for x in xrange(0, 360, step360):
rotated_img = rotate_image(cropped_coin_only,x)
cropped = cv2array(center_crop(rotated_img, coin_center, CROP_SIZE))
cv2.imwrite("rotated.png", cropped)
#features = features360(rotated_img, preprocess=False,coin_center=coin_center, step360=360, averaging=False, classID=0)
classID = predict_class(cropped)
if classID == 1: answer = "Jefferson HEADS"
if classID == 2: answer = "Monticello TAILS"
if classID == 3: answer = "Other HEADS"
if classID == 4: answer = "Other TAILS"
print "predicted classID:", answer
classID_votes[classID-1] = classID_votes[classID-1] +1
print "classID_votes:", classID_votes, classID_votes.index(max(classID_votes))
#time.sleep(1)
final_classID_vote = classID_votes.index(max(classID_votes)) + 1
'''
from sklearn import svm
model = pickle.load( open( "coinvision_ai_model_svc.mdl", "rb" ) )
print model.predict(features)
from sklearn.neighbors import KNeighborsClassifier
#neigh = KNeighborsClassifier(n_neighbors=3)
neigh= pickle.load( open( "coinvision_ai_model_knn.mdl", "rb" ) )
print neigh.predict(features)
#print neigh.predict_proba(1)
'''
#eg.msgbox("predicted classID:"+answer)
return final_classID_vote
def predict_class(img):
features = find_features(img)
classID = 0
#from sklearn import svm
#model_svm = pickle.load( open( "coinvision_ai_model_svc.mdl", "rb" ) )
#classID_svm = model_svm.predict(features)
#print "SVM predicted classID:", classID_svm
#print "SVM predicted prob:", model_svm.predict_proba(features)
#from sklearn.neighbors import KNeighborsClassifier
#KNN_clf = KNeighborsClassifier(n_neighbors=3)
#KNN_clf = pickle.load( open( "coinvision_ai_model_knn.mdl", "rb" ) )
#KNN_classID = KNN_clf.predict(features)
#print "KNN predicted classID:", KNN_classID
#print "KNN predicted prob:", KNN_clf.predict_proba(features)
from sklearn.svm import LinearSVC
LinearSVC_clf = LinearSVC()
LinearSVC_clf = pickle.load( open( "coinvision_ai_model_lr.mdl", "rb" ) )
LinearSVC_class = LinearSVC_clf.predict(features)
print "LinearSVC_clf predicted classID:", LinearSVC_class
#print "LinearSVC predicted prob:", LinearSVC_clf.predict_proba(features)
#from sklearn.linear_model import LogisticRegression
#clf2 = pickle.load(open( "coinvision_ai_model_clf2.mdl", "rb" ) )
#print "LR2 predicted classID:",clf2.predict(features)
#print "LR2 predicted prob:", clf2.predict_proba(features)
#try:
#model = pickle.load( open( "coinvision_ai_model.mdl", "rb" ) )
#classID = classify(model, features)
classID = LinearSVC_class
#print "classID: = ", classID
if classID == 1: answer = "Jefferson HEADS"
if classID == 2: answer = "Monticello TAILS"
if classID == 3: answer = "Other HEADS"
if classID == 4: answer = "Other TAILS"
print "predicted classID:", answer
#eg.msgbox("predicted classID:"+answer)
return classID
#except:
print "could not predict...bad data"
def save_data(features, classID):
data_filename = 'coinvision_feature_data.csv'
###########################
print 'writing image features to file: ', data_filename
# delete data file and write header
#f_handle = open(data_filename, 'w')
#f_handle.write(str("classid, lbp, i3_histogram, rgb_histogram, sum_I3, sum2_I3, median_I3, avg_I3, var_I3, stddev_I3, rms_I3"))
#f_handle.write('\n')
#f_handle.close()
#write class data to file
f_handle = open(data_filename, 'a')
f_handle.write(str(classID))
f_handle.write(', ')
f_handle.close()
f_handle = open(data_filename, 'a')
for i in range(len(features)):
f_handle.write(str(features[i]))
f_handle.write(" ")
f_handle.write('\n')
f_handle.close()
def process_all_images():
path = "../coin_images/"
#print path+'jheads/*.jpg'
steps = 30
for name in glob.glob(path+'jheads/*.jpg'):
classID = "1"
print name
img = cv2.imread(name)
#features = find_features(img)
#save_data(features, classID)
features360(img, step360=steps, averaging=False, classID=1)
for name in glob.glob(path+'jtails/*.jpg'):
classID = "2"
print name
img = cv2.imread(name)
#img = preprocess_img(img)
#features = find_features(img)
#save_data(features, classID)
features360(img, step360=steps, averaging=False, classID=2)
for name in glob.glob(path+'oheads/*.jpg'):
classID = "3"
print name
img = cv2.imread(name)
#img = preprocess_img(img)
#features = find_features(img)
#save_data(features, classID)
features360(img, step360=steps, averaging=False, classID=3)
for name in glob.glob(path+'otails/*.jpg'):
classID = "4"
print name
img = cv2.imread(name)
#img = preprocess_img(img)
#features = find_features(img)
#save_data(features, classID)
features360(img, step360=steps, averaging=False, classID=4)
def train_ai():
data = []
classID = []
features = []
features_temp_array = []
'''
#SIMPLECV
#bows
feature_extractors = []
extractor_names = []
# Training data set paths for classification(suppervised learnning)
image_dirs = ['../coin_images/jheads/',
'../coin_images/jtails/',
'../coin_images/oheads/',
'../coin_images/otails/',
]
# Different class labels for multi class classification
class_names = ['jhead','jtail','ohead', 'otail']
#preprocess all training images
for directory in image_dirs:
for filename in glob.glob(directory + '/*.jpg'):
print "Processing:", filename
img = cv2.imread(filename)
temp_img = preprocess_houghlines (img, 100)
temp_str = filename.rsplit('/')
temp_str = temp_str[len(temp_str)-1]
temp_str = directory + '/temp/' + temp_str
print temp_str
cv2.imwrite(temp_str, temp_img)
#raw_input('press enter to continue : ')
#sys.exit(-1)
#build array of directories for bow
#image_dirs2 = []
#for directory in image_dirs:
# image_dirs2.append(directory + '/temp/')
#print image_dirs2
# Different class labels for multi class classification
extractor_name = 'hue'
if extractor_name == 'bow':
feature_extractor = BOFFeatureExtractor() # feature extrator for bag of words methodology
feature_extractor.generate(image_dirs,imgs_per_dir=40) # code book generation
elif extractor_name == 'hue':
feature_extractor = HueHistogramFeatureExtractor()
elif extractor_name == 'morphology':
feature_extractor = MorphologyFeatureExtractor()
elif extractor_name == 'haar':
feature_extractor = HaarLikeFeatureExtractor()
elif extractor_name == 'edge':
feature_extractor = EdgeHistogramFeatureExtractor()
image_dirs2 = image_dirs
#bow_features = BOFFeatureExtractor()
#bow_features.generate(image_dirs2,imgs_per_dir=40, verbose=True) # code book generation
#bow_features.generate(image_dirs2,imgs_per_dir=200,numcodes=256,sz=(11,11),img_layout=(16,16),padding=4 )
#bow_features.save('codebook.png','bow.txt')
#print "extractor_names:", extractor_names, feature_extractors
# initializing classifier with appropriate feature extractors list
#print type(bow_features), bow_features, bow_features.getFieldNames(), bow_features.getNumFields()
#raw_input('bow saved...Enter : ')
#bow_features = None
#bow_features = BOFFeatureExtractor()
#print type(bow_features), bow_features, bow_features.getFieldNames(), bow_features.getNumFields()
#bow_features.load('bow.txt')
#print type(bow_features), bow_features, bow_features.getFieldNames(), bow_features.getNumFields()
feature_extractors.append(feature_extractor)
#raw_input('bow loaded Enter : ')
#extractor_names.append(extractor_name)
classifier_name = 'naive'
if classifier_name == 'naive':
classifier = NaiveBayesClassifier(feature_extractors)
elif classifier_name == 'svm':
classifier = SVMClassifier(feature_extractors)
elif classifier_name == 'knn':
classifier = KNNClassifier(feature_extractors, 2)
elif classifier_name == 'tree':
classifier = TreeClassifier(feature_extractors)
# train the classifier to generate hypothesis function for classification
#print "image_dirs:", image_dirs, class_names
classifier.train(image_dirs2,class_names,disp=None,savedata='features.txt',verbose=True)
print 'classifier:', type(classifier), classifier
raw_input('press enter to continue :')
#pickle.dump( classifier, open( "coinvision_ai_model2.mdl", "wb" ),2 )
#classifier.save('coinvision_ai_model.mdl')
print 'classifier:', type(classifier), classifier
#classifier = NaiveBayesClassifier.load('coinvision_ai_model.mdl')
#raw_input('press enter to continue : let me try loading bow file')
#classifier2 = NaiveBayesClassifier.load('coinvision_ai_model.mdl')
#classifier2.setFeatureExtractors(feature_extractors)
#print 'classifier2:', type(classifier2), classifier2
#classifier.load("coinvision_ai_model.mdl")
#classifier2.load('coinvision_ai_model.mdl')
#print 'classifier:', type(classifier2), classifier2
raw_input('press enter to continue : ')
print 'testing ai:'
test_images_path = "../coin_images/unclassified"
extension = "*.jpg"
if not test_images_path:
path = os.getcwd() #get the current directory
else:
path = test_images_path
directory = os.path.join(path, extension)
files = glob.glob(directory)
count = 0 # counting the total number of training images
error = 0 # conuting the total number of misclassification by the trained classifier
for image_file in files:
new_image = Image(image_file)
category = classifier.classify(new_image)
print "image_file:", image_file + " classified as: " + category
if image_file[-9] == 't':
if category == 'jhead' or category == 'ohead':
print "INCORRECT CLASSIFICATION"
error += 1
if image_file[-9] == 'h':
if category == 'jtail' or category == 'otail':
print "INCORRECT CLASSIFICATION"
error += 1
count += 1
# reporting the results