-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpolynomialTime.py
More file actions
executable file
·1655 lines (1477 loc) · 60.5 KB
/
polynomialTime.py
File metadata and controls
executable file
·1655 lines (1477 loc) · 60.5 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
import pygame
from pygame.locals import *
import pygame_textinput
import sys
import cv2
import numpy as np
import string
import matplotlib.pyplot as plt
import pylab
import operator
import os
from fractions import Fraction
import copy
# taken from 15-112 course page
def almostEqual(d1, d2, epsilon=10**-7):
# note: use math.isclose() outside 15-112 with Python version 3.5 or later
return (abs(d2 - d1) < epsilon)
# wrote for 15-112 week1 practice
def distance(x1, y1, x2, y2):
return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5
# truncates a float n to number of places specified
def truncate(n, places):
a = str(n)
return float(a[:places + 1])
# i edited these sources to work with my data and openCV framework and to work with my desire to recognize math and expoonents
# i did however, modify this function to recognize exponents with spacing
# ie 6x6 would show 36 but 6x^6 would graph it
# credit for ml and image manipulation goes to these sources
# machine learning credit:
# https://www.youtube.com/watch?v=c96w1JS28AY (links to github in video)
# https://github.com/MicrocontrollersAndMore/OpenCV_KNN_Character_Recognition_Machine_Learning/blob/master/train_and_test.py
MIN_CONTOUR_AREA = 100
RESIZED_IMAGE_WIDTH = 20
RESIZED_IMAGE_HEIGHT = 30
class ContourWithData():
npaContour = None
boundingRect = None
intRectX = 0
intRectY = 0
intRectWidth = 0
intRectHeight = 0
fltArea = 0.0
def calculateRectTopLeftPointAndWidthAndHeight(self):
[intX, intY, intWidth, intHeight] = self.boundingRect
self.intRectX = intX
self.intRectY = intY
self.intRectWidth = intWidth
self.intRectHeight = intHeight
def checkIfContourIsValid(self):
if self.fltArea < MIN_CONTOUR_AREA: return False
return True
def main(img):
allContoursWithData = []
validContoursWithData = []
npaClassifications = np.loadtxt("classificationsNew.txt", np.float32)
npaFlattenedImages = np.loadtxt("flattened_imagesNew.txt", np.float32)
npaClassifications = npaClassifications.reshape((npaClassifications.size, 1))
kNearest = cv2.ml.KNearest_create()
kNearest.train(npaFlattenedImages, cv2.ml.ROW_SAMPLE, npaClassifications)
imgTestingNumbers = cv2.imread(img)
imgGray = cv2.cvtColor(imgTestingNumbers, cv2.COLOR_BGR2GRAY)
imgBlurred = cv2.GaussianBlur(imgGray, (5,5), 0)
imgThresh = cv2.adaptiveThreshold(imgBlurred, 255,
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY_INV, 11, 2)
imgThreshCopy = imgThresh.copy()
imgContours, npaContours, npaHierarchy = cv2.findContours(imgThreshCopy,
cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
for npaContour in npaContours:
contourWithData = ContourWithData()
contourWithData.npaContour = npaContour
contourWithData.boundingRect = cv2.boundingRect(contourWithData.npaContour)
contourWithData.calculateRectTopLeftPointAndWidthAndHeight()
contourWithData.fltArea = cv2.contourArea(contourWithData.npaContour)
allContoursWithData.append(contourWithData)
for contourWithData in allContoursWithData:
if contourWithData.checkIfContourIsValid():
validContoursWithData.append(contourWithData)
validContoursWithData.sort(key = operator.attrgetter("intRectX"))
strFinalString = ""
rectList = []
for contourWithData in validContoursWithData:
cv2.rectangle(imgTestingNumbers,
(contourWithData.intRectX, contourWithData.intRectY),
(contourWithData.intRectX + contourWithData.intRectWidth, contourWithData.intRectY + contourWithData.intRectHeight), # lower right corner
(0, 255, 0),
2)
rectList.append((contourWithData.intRectX, contourWithData.intRectY,
contourWithData.intRectX + contourWithData.intRectWidth,
contourWithData.intRectY + contourWithData.intRectHeight))
averageArea, averageY = findAverages(rectList)
for contourWithData in validContoursWithData:
imgROI = imgThresh[contourWithData.intRectY : contourWithData.intRectY + contourWithData.intRectHeight,
contourWithData.intRectX : contourWithData.intRectX + contourWithData.intRectWidth]
imgROIResized = cv2.resize(imgROI, (RESIZED_IMAGE_WIDTH, RESIZED_IMAGE_HEIGHT))
npaROIResized = imgROIResized.reshape((1, RESIZED_IMAGE_WIDTH * RESIZED_IMAGE_HEIGHT))
npaROIResized = np.float32(npaROIResized)
retval, npaResults, neigh_resp, dists = kNearest.findNearest(npaROIResized, k=2)
strCurrentChar = str(chr(int(npaResults[0][0])))
if strCurrentChar == 'X':
strCurrentChar = 'x'
if strCurrentChar == 'd' or strCurrentChar == 's':
strCurrentChar = '-'
if contourWithData.intRectY + contourWithData.intRectHeight < averageY:
spacingChar = '^'
# elif strFinalString != '' and strFinalString[-1] == 'x' and strCurrentChar.isdigit():
# strFinalString += '^'
else:
spacingChar = ''
strFinalString += spacingChar + strCurrentChar
# print("\n" + strFinalString + "\n")
# for testing purposes
# cv2.imshow("imgTestingNumbers", imgTestingNumbers)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
return strFinalString
######################################################################
# colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# gives popup to edit what the scanner thought that the input was
def showInfo(s):
# the following three lines suppress the extra tkinter box that would
# show up with my dialog box
# they are taken from
# (next two lines are URL to keep under 80 chars)
# http://stackoverflow.com/questions/17280637/
# tkinter-messagebox-without-window
# by user BuvinJ
root = tk.Tk()
root.overrideredirect(1)
root.withdraw()
response = simpledialog.askstring('Edit',
'Make any changes you need:',
initialvalue=s)
return response
def findAverages(a):
averageY = []
averageArea = []
for (x0, y0, x1, y1) in a:
averageY.append((y0 + y1) / 2)
averageArea.append((x1 - x0) * (y1 - y0))
return listAvg(averageArea), listAvg(averageY)
def listAvg(a):
if a == []:
return 0
total = 0
for n in a:
total += n
return total / len(a)
##############################
# evaluate
##############################
def sign(n):
return 1 if n >= 0 else -1
# takes a value and removes all occurences of that value froma list
def removeAllFromList(a, value):
for i in range(len(a)):
if a[i] == value:
a.pop(i)
return a
# technically returns a random key from a dictionary and what it maps to
# i use this as a helper function for a special case where a dictionary
# only has one entry, so it returns that key and its value
def getOnlyElement(d):
a = list(d.keys())
key = a[0]
return key, d[key]
# returns which to values of the domain return values of the codomain with
# opposite values
def oppositeSign(p, a, b, c):
fA = evaluatePolynomial(p, a)
fC = evaluatePolynomial(p, c)
if sign(fA) == sign(fC):
return b, c
else:
return a, c
# finds a root of a given function given a root between two values of the domain
def findRoot(p, a, b):
epsilon = 10 ** -8
if sign(evaluatePolynomial(p, a)) == sign(evaluatePolynomial(p, b)):
return None
elif abs(evaluatePolynomial(p, a)) < epsilon:
return a
elif abs(evaluatePolynomial(p, b)) < epsilon:
return b
elif abs(a - b) < epsilon:
return abs(a + b) / 2
else:
fA = evaluatePolynomial(p, a)
fB = evaluatePolynomial(p, b)
c = (a * fB - b * fA) / (fB - fA)
a, b = oppositeSign(p, a, b, c)
return findRoot(p, a, b)
def subtractPolynomials(p3, p4):
p1 = copy.copy(p3)
p2 = copy.copy(p4)
for key in p2:
if key in p1:
p1[key] = p1[key] - p2[key]
else:
p1[key] = -1 * p2[key]
return p1
def findIntersection(p1, p2):
p = subtractPolynomials(p1, p2)
return findZeros(p)
# finds the intersections of all polynomials in a list a
def findAllIntersections(a):
intersections = []
for i in range(len(a) - 1):
for j in range(i+ 1, len(a)):
intersections.append(findIntersection(a[i], a[j]))
c = flatten(intersections)
return removeAllFromList(c, None)
# returns a dictionary with the degrees of a polynomial mapping to their
# coefficients given a polynomial entered as a string
# (of the form a_n x^n + ... + a_1 x + a_0)
def parsePolynomial(p):
p = p.replace('-', '+-')
d = dict()
for term in p.split('+'):
try:
num = (float(term))
if 0 not in d:
d[0] = 0
d[0] += num
except:
if term[-1] in string.ascii_lowercase:
if 1 not in d:
d[1] = 0
if term[:-1] == '':
coeff = 1
elif term[:-1] == '-':
coeff = -1
else:
coeff = float(term[:-1])
d[1] += coeff
else:
coeff = getCoeff(term)
exp = float(getExp(term))
if exp not in d:
d[exp] = 0
if coeff == '':
coeff = 1
elif coeff == '-':
coeff = -1
else:
coeff = float(coeff)
d[exp] += coeff
return d
# takes a parsed polynomial and gives back its original string
def parsedToString(p):
result = ''
first = True
for key in sorted(p.keys())[::-1]:
sgn = sign(p[key])
signChar = '' if sgn == -1 or first else '+'
if almostEqual(int(p[key]), p[key]):
result += '%s%ix^%i' % (signChar, p[key], key)
# result += '%s%fx^%f' % (signChar, p[key], key)
elif True:
result += '%s%0.2fx^%i' % (signChar, p[key], key)
elif key == 1:
try:
result += '%s%ix' % (signChar, p[key])
except:
result += '%s%fx' % (signChar, p[key])
else:
result += str(p[key])
first = False
return result
def getExp(term):
results = getCoeff(term[::-1])
fixedResults = results[::-1]
return fixedResults
def getCoeff(term):
coeff = ''
for c in term:
if c == '-':
coeff += c
else:
try:
coeff += c
float(coeff)
except:
return coeff[:-1]
def takeDerivative(polynomial):
derivative = dict()
for key in polynomial.keys():
if key != 0:
derivative[key - 1] = key * polynomial[key]
return derivative
def indefiniteIntegral(polynomial):
integral = dict()
for key in polynomial.keys():
integral[key + 1] = polynomial[key] / (key + 1)
integral[0] = 'c'
return integral
# returns value of a polynomial at x
def evaluatePolynomial(polynomial, x):
total = 0
for key in polynomial:
total += x ** key * polynomial[key]
return total
def derivativeAtPoint(polynomial, x):
derivative = takeDerivative(polynomial)
return evaluatePolynomial(derivative, x)
def nthDerivative(polynomial, n):
for i in range(n):
polynomial = takeDerivative(polynomial)
return polynomial
def definiteIntegral(polynomial, a, b):
integral = indefiniteIntegral(polynomial)
del integral[0]
fA = evaluatePolynomial(integral, a)
fB = evaluatePolynomial(integral, b)
return fB - fA + 0.0 # + 0.0 converts back to float
# finds all of the zeros of a given polynomial
def findZeros(polynomial):
if len(polynomial) == 1:
degree, value = getOnlyElement(polynomial)
if degree == 0:
if value != 0:
return None
else: # this is the line y = 0
return 'all reals'
else:
return [0]
# all polynomials with two terms are easily solved, so we stop and solve
elif len(polynomial) == 2:
return solveLenTwo(polynomial)
else:
derivativeList = findZeros(takeDerivative(polynomial))
derivativeList = removeAllFromList(derivativeList, None)
if derivativeList == []:
return findEdgeRoot(polynomial, 0, True, True)
elif len(derivativeList) == 1: # in this case we check both ends
x = derivativeList[0]
return findEdgeRoot(polynomial, x, True, True)
else:
roots = []
derivativeList = sorted(derivativeList)
xI = derivativeList[0]
xN = derivativeList[-1]
# start and end give the roots at the edges
start = findEdgeRoot(polynomial, xI, True, False)
end = findEdgeRoot(polynomial, xN, False, True)
roots.append(start)
roots.append(end)
# check between each derivative - we can have at most one root
# on this region
for i in range(len(derivativeList) - 1):
x1 = derivativeList[i]
x2 = derivativeList[i + 1]
roots.append(findRoot(polynomial, x1, x2))
return removeAllFromList(flatten(roots), None)
def solveLenTwo(polynomial):
roots = []
smallerDegree = min(polynomial.keys())
largerDegree = max(polynomial.keys())
if smallerDegree != 0: # like checking if we can factor out an x
roots.append(0)
minCoeff = polynomial[smallerDegree]
maxCoeff = polynomial[largerDegree]
rhs = - minCoeff / maxCoeff # solving the equation for x**n
# avoiding complex roots for even powers, if they are real then we have
# plus or minus the root
if (largerDegree - smallerDegree) % 2 == 0 and rhs >= 0:
root = rhs ** (1 / (largerDegree - smallerDegree))
roots.extend([root , - root])
elif (largerDegree - smallerDegree) % 2 == 1:
roots.append(rhs ** (1 / (largerDegree - smallerDegree)))
return roots
# finds the roots of a function when we do not have two derivatives to check
# between
# left and right are booleans and determine whether or not we check in that
# direction
def findEdgeRoot(polynomial, x, left, right):
roots = []
# we should only check for roots if either the second derivative is > 0 and
# the function is less than zero or vice versa
secondDerivative = nthDerivative(polynomial, 2)
concavitySign = sign(evaluatePolynomial(secondDerivative, x))
polySign = sign(evaluatePolynomial(polynomial, x))
delta = -1 # the magnitude of delta is arbitrary, only the sign matters
while left and concavitySign != polySign:
if findRoot(polynomial, x, x + delta) != None:
roots.append(findRoot(polynomial, x, x + delta))
break
else:
delta -= 1
delta = 1
while right and concavitySign != polySign:
if findRoot(polynomial, x, x + delta) != None:
roots.append(findRoot(polynomial, x, x + delta))
break
else:
delta += 1
return roots
# flattens lists containing lists to a single list with only their elements
# we were shown a function in 112 lab that serves this same purpose,
# but were never given a chance to write it down
def flatten(a):
if a == []:
return a
elif isinstance(a, list):
return flatten(a[0]) + flatten(a[1:])
else:
return [a]
# checks if a string has multiple letters in it
def doubleLetters(s):
for c in s:
if c in string.ascii_lowercase and c != 'x':
return True
return False
# returns what to do with our results from scanning
def evaluateResults(data, s):
try:
temp = parsePolynomial(s)
if 'x' not in s or doubleLetters(s):
a = 1/0
data.results = s
data.polynomialScreen = True
data.zeros.append(findZeros(parsePolynomial(s)))
data.zeros = flatten(data.zeros)
data.previousScreen = 'polynomial'
if data.batchCounter != 3:
data.functionList.append(data.results)
polyPlot(data)
return
except:
pass
try:
temp = evaluatePEMDAS(s)
data.results = s
data.results = data.results.replace('x', '*')
data.arithmeticScreen = True
data.previousScreen = 'arithmetic'
return
except:
pass
data.results = s
data.noneFound = True
# this function takes in the index of an operation and a string and returns the
# numbers that are on either side of that operation, as well as the indices
# of the string corresponding to the first digit of the first number and
# the last digit of the last number
def findAdjacentNumbers(s, i):
start = i - 1
while((s[start].isdigit() or
s[start] == '.') and start >= 0):
start -= 1
startNumber = float(s[start + 1: i])
end = i + 1
while(end < len(s) and
(s[end].isdigit() or s[end] == '.')):
end += 1
endNumber = float(s[i + 1: end])
return startNumber, endNumber, start + 1, end
def evaluate(a, b, op):
# I just decided to store my strings to evaluate with '^' instead
# of '**' just to that there is one less character which makes some of
# my other code more simple
if op == '^':
return a ** b
elif op == '*':
return a * b
elif op == '-':
return a - b
elif op == '+':
return a + b
elif op == '/':
if b == 0:
return 'error'
else:
return a / b
# this function finds the operation that we must do next, going through PEMDAS
def findOperation(s):
i = s.find('^')
if i != -1:
return i
i = s.find('*')
j = s.find('/')
# if only one of the two is present, we return that one
# otherwise we provide which one occurs first, provided one of them occurs
if i == -1 and j != -1:
return j
elif j == -1 and i != -1:
return i
elif i != -1 and j != -1:
return i if i < j else j
i = s.find('+')
j = s.find('-')
if i == -1 and j != -1:
return j
elif j == -1 and i != -1:
return i
else:
return i if i < j else j
def evaluatePEMDAS(expression, l=None):
if l == []:
l.append(expression)
s = ''
for c in expression:
if c == 'x':
s += '*'
else:
s += c
if s == '':
return 0 if l is not None else 0, [0]
# we will see if s can be written is a float
# and thus also a positive or negative integer - in this case, we are done
try:
float(s)
flt = True
except:
flt = False
if flt:
return float(s) if l is not None else float(s), [float(s)]
else:
i = findOperation(s)
a, b, start, end = findAdjacentNumbers(s, i)
newVal = evaluate(a, b, s[i])
newStr = s.replace(s[start: end], str(newVal), 1)
if isinstance(l, list):
l.append(newStr)
if l is None:
return evaluatePEMDAS(newStr)
else:
return evaluatePEMDAS(newStr, l), l
# this function gets the slope and intercept of both sides of a
# linear equation
def getEquations(s):
i = s.find('=')
lhs = s[:i]
rhs = s[i + 1:]
return getSlopeIntercept(lhs), getSlopeIntercept(rhs)
def solveQuadratic(s):
a, b, c = getCoefficients(s)
roots = np.roots([a, b, c])
return roots
def digitSearchBack(s, i):
while i > 0 and not s[i].isdigit:
i -= 1
return i
def fixFunction(fn):
new = ''
for c in fn:
if new != '' and c == 'x' and new[-1].isdigit():
new += '*x'
else:
new += c
new = new.replace('^', '**')
return new
def polyPlot(data):
pylab.figure()
data.parsedList = [parsePolynomial(p) for p in data.functionList]
data.intersections = findAllIntersections(data.parsedList.copy())
data.intersections = [float('%0.2f' % n) for n in data.intersections]
for fn in data.functionList:
if fn is not None:
p = fixFunction(fn)
x = np.arange(-7, 7, .01)
y = eval(p)
pylab.plot(x, y, label=p)
for zero in data.zeros:
pylab.plot(zero, 0, 'gs')
if len(data.parsedList) > 1:
p = data.parsedList[1]
points = [(xx, evaluatePolynomial(p, xx)) for xx in data.intersections]
for (x1, y1) in points:
pylab.plot(x1, y1, 'rs')
pylab.legend(loc='upper left')
pylab.savefig('resultGraph.png', dpi=500)
####################################################################
# graphics
####################################################################
# http://stackoverflow.com/questions/19306211/opencv-cv2-image-to-pygame-image
# function given by user High schooler with modification suggested by lgonato
def cvimage_to_pygame(image):
"""Convert cvimage into a pygame image"""
return pygame.image.frombuffer(image.tostring(), image.shape[1::-1], "RGB")
# this function gives the x and y value needed to center a given block of
# text at a given x and y
def centerText(font, text, x, y):
drawX = x - (font.size(text)[0] // 2)
drawY = y - (font.size(text)[1] // 2)
return (drawX, drawY)
# useful for finding if user clicked on text on screen
# returns cords of box surrounding the text
def giveTextBounds(font, text, x, y):
x0 = x - (font.size(text)[0] // 2)
y0 = y - (font.size(text)[1] // 2)
x1 = x + (font.size(text)[0] // 2)
y1 = y + (font.size(text)[1] // 2)
return (x0, y0, x1, y1)
# once we apply this to what we want to write on the screen,
# we simply do surface.blit(label, cords)
def giveLabelCords(message, fontSize, cx, cy, color=BLACK):
font = pygame.font.SysFont('cambriacambriamath', fontSize)
label = font.render(message, True, color)
cords = centerText(font, message, cx, cy)
return label, cords
# moves the scanning rectangle on screen
def moveRect(data):
(x, y) = data.webCords
delta = 20
x0, y0 = data.rectX + data.rectXoffset, data.rectY + data.rectYoffset
x1, y1 = x0 + data.rectWidth, y0 + data.rectHeight
# decides which edge we are moving
if abs(x - x0) < delta and y < y1 and y > y0:
data.leftEdge = True
elif abs(x - x1) < delta and y < y1 and y > y0:
data.rightEdge = True
elif abs(y - y0) < delta and x < x1 and x > x0:
data.lowerEdge = True
elif abs(y - y1) < delta and x < x1 and x > x0:
data.upperEdge = True
# this prevents my program from crashing if the users resizes the rectangle
# to be too small
def fixDimensions(data):
if data.rectWidth < 20:
data.rectWidth = 25
elif data.rectHeight < 20:
data.rectHeight = 25
def keyPressedWebcam(event, data):
if event == ord('c'):
if data.camSelected == 'batch' and data.batchCounter < 3:
try:
x, y = data.rectX + data.rectXoffset, data.rectY + data.rectYoffset
width, height = data.rectWidth, data.rectHeight
# method of indexing np array given at url by user martin giesler
# http://stackoverflow.com/questions/903853/how-do-you-extract-a-column-from-a-multi-dimensional-array/903867
rowIdx = np.array([i for i in range(y, y + height)])
colIdx = np.array([j for j in range(x, x + width)])
scanFrame = np.fliplr(data.frame[rowIdx[:, None], colIdx])
cv2.imwrite('test123.png', scanFrame)
data.results = main('test123.png')
a = parsePolynomial(data.results)
data.functionList.append(data.results)
data.batchCounter += 1
data.parsedList = [parsePolynomial(p) for p in data.functionList]
data.intersections = findAllIntersections(data.parsedList.copy())
except:
pass
else:
data.arithmeticScreen = False
data.polynomialScreen = False
# resizing what we scan by indexing into np.array
x, y = data.rectX + data.rectXoffset, data.rectY + data.rectYoffset
width, height = data.rectWidth, data.rectHeight
# same citation as above indexing into np arrays
rowIdx = np.array([i for i in range(y, y + height)])
colIdx = np.array([j for j in range(x, x + width)])
scanFrame = np.fliplr(data.frame[rowIdx[:, None], colIdx])
cv2.imwrite('test123.png', scanFrame)
if data.batchCounter != 3:
data.results = main('test123.png')
data.webcam = False
data.capturing = False
evaluateResults(data, data.results)
data.previousScreen = 'webcam'
elif event == 275: # ords for arrow keys
data.rectXoffset += 10
elif event == 276:
data.rectXoffset -= 10
elif event == 274:
data.rectYoffset += 10
elif event == 273:
data.rectYoffset -= 10
elif event == ord('q') or event == 8: # 8 is backspace
data.start = True
data.webcam = False
data.capturing = False
def keyPressedHelp(event, data):
if event == K_LEFT and not data.cameraHelp and not data.graphHelp:
data.help = False
data.start = True
elif event == K_LEFT and data.cameraHelp:
data.cameraHelp = False
elif event == K_LEFT and data.graphHelp:
data.graphHelp = False
data.cameraHelp = True
elif event == K_RIGHT and not data.graphHelp and not data.cameraHelp:
data.cameraHelp = True
elif event == K_RIGHT and not data.graphHelp and data.cameraHelp:
data.cameraHelp = False
data.graphHelp = True
elif event == K_RIGHT and data.graphHelp:
data.help = False
data.graphHelp = False
data.start = True
def keyPressedPolynomial(event, data):
if event == ord('z') and data.undoList != []:
a = data.undoList.pop()
data.functionList.append(a)
data.deleted = True
polyPlot(data)
elif event == ord('y') and len(data.functionList) > 1 and data.undoList != []:
a = data.functionList.pop()
data.undoList.append(a)
data.deleted = True
polyPlot(data)
def keyPressedEdit(event, data, textinput):
# evaluating our results
if event == K_RETURN:
data.changed = True
data.functionList = []
data.zeros = []
data.intersections = []
data.arithmeticScreen = False
data.polynomialScreen = False
data.results = textinput.get_text()
data.editScreen = False
textinput.erase_text()
data.writtenResults = False
evaluateResults(data, data.results)
# data.resultsScreen = True
def keyPressed(event, data):
if data.webcam:
keyPressedWebcam(event, data)
elif data.help:
keyPressedHelp(event, data)
elif data.polynomialScreen:
keyPressedPolynomial(event, data)
elif data.editScreen:
keyPressedEdit(event, data)
def startMousePressed(data, x, y):
(helpX0, helpY0, helpX1, helpY1) = data.helpBox
(scanX0, scanY0, scanX1, scanY1) = data.scanBox
if(x > helpX0 and x < helpX1 and y > helpY0 and y < helpY1):
data.start = False
data.help = True
elif(x > scanX0 and x < scanX1 and y > scanY0 and y < scanY1):
data.start = False
data.intro = False
data.webcam = True
data.capturing = True
def arithmeticMousePressed(data, x, y):
(backX0, backY0, backX1, backY1) = data.backBox
(editX0, editY0, editX1, editY1) = data.editBox
if(x > backX0 and x < backX1 and y > backY0 and y < backY1):
data.confirmed = False
data.webcam = True
data.capturing = True
data.results = None
data.evaluatedResults = None
data.clearPlot = True
elif(x > editX0 and x < editX1 and y > editY0 and y < editY1):
data.editScreen = True
data.previousScreen = 'arithmetic'
data.resultsSreen = False
def polynomialMousePressed(data, x, y):
(backX0, backY0, backX1, backY1) = data.backBox
(editX0, editY0, editX1, editY1) = data.editBox
if(x > backX0 and x < backX1 and y > backY0 and y < backY1):
data.confirmed = False
data.webcam = True
data.capturing = True
data.results = None
data.evaluatedResults = None
data.drawPolynomialScreen = False
data.clearPlot = True
data.zeros = []
data.functionList = []
data.batchCounter = 0
data.camSelected = 'single'
elif(x > editX0 and x < editX1 and y > editY0 and y < editY1):
data.polynomialScreen = False
data.editScreen = True
data.previousScreen = 'polynomial'
def noneFoundMousePressed(data, x, y):
(backX0, backY0, backX1, backY1) = data.backBox
(editX0, editY0, editX1, editY1) = data.editBox
if(x > backX0 and x < backX1 and y > backY0 and y < backY1):
data.confirmed = False
data.noneFound = False
data.webcam = True
data.capturing = True
data.results = None
data.evaluatedResults = None
data.clearPlot = True
elif(x > editX0 and x < editX1 and y > editY0 and y < editY1):
data.noneFound = False
data.editScreen = True
data.previousScreen = 'none'
def mousePressed(event, data):
(x, y) = pygame.mouse.get_pos()
if data.start:
startMousePressed(data, x, y)
elif data.arithmeticScreen:
arithmeticMousePressed(data, x, y)
elif data.polynomialScreen:
polynomialMousePressed(data, x, y)
elif data.noneFound:
noneFoundMousePressed(data, x, y)
def init(data):
data.zeros = []
data.clearPlot = True
data.capturing = False
data.frame = None
data.webcam = False
data.help = False
data.events = None
data.start = True
data.helpBox = None
data.scanBox = None
data.backBox = None
data.derivativeBox = None
data.integralBox = None
data.zerosBox = None
data.eval = None
data.results = None
data.resultsScreen = False
data.plotted = False
data.arithmeticScreen = False
data.polynomialScreen = False
data.noneFound = False
data.editBox = None
data.editScreen = False
data.result = True
data.confirmed = False
data.evaluatedResults = None
data.functionList = []
data.parsedList = []
data.writtenResults = False
data.rectX = int(.2 * data.width)
data.rectY = int(.2 * data.height)
data.rectWidth = int(.6 * data.width)
data.rectHeight = int(.3 * data.height)
data.rectXoffset = 0
data.rectYoffset = 0
data.rectSizeMultiplier = 1
data.scanColor = BLACK
data.helpColor = BLACK
data.rectDragging = False
data.webCords = (-1, -1)
data.leftEdge = False
data.rightEdge = False
data.upperEdge = False
data.lowerEdge = False # lower y value, higher on screen
data.batchBox = None
data.singleBox = None
data.doneBox = None
data.backColor = WHITE
data.singleColor = WHITE
data.batchColor = WHITE
data.loadColor = WHITE
data.camSelected = 'single'
data.batchCounter = 0
data.shutterCenter = None
data.shutterInnerRadius = 35
data.shutterColor = BLACK