-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
570 lines (420 loc) · 14.6 KB
/
index.js
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
class sudoku{
constructor(){
this.grid = []
this.tempGrid = []
}
// // https://www.youtube.com/watch?v=G_UYXzGuqvM
solve(grid){
// this.grid[0][0] = 8
// // this.solve()
// return
for (let i=0;i<=8;i++){
for (let j=0;j<=8;j++){
if (grid[i][j]==0){
for (let k=1;k<=9;k++){
if (this.possible(i,j,k)){
grid[i][j] = k
this.solve(grid)
grid[i][j] = 0
}
}
return
}
}
}
this.grid = JSON.parse(JSON.stringify(grid))
}
possible(x,y,n){
`Is n possible in position x,y`
for (let i=0;i<9;i++){
if (this.grid[x][i] == n){
return false
}
if (this.grid [i][y]==n){
return false
}
}
let x0 = (Math.floor(x/3))*3
let y0 = (Math.floor(y/3))*3
for (let i=0;i<=2;i++){
for (let j=0;j<=2;j++){
if (this.grid[x0+i][y0+j]==n){
return false
}
}
}
return true
}
}
let model;
class imagingExtraction{
constructor(img,threshValue=130){
this.size = new cv.Size(28, 28)
this.img = cv.imread(img);
this.initialImaging(threshValue)
this.lineDetection()
// contours, hierarchy = cv2.findContours(thresholdGray,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
// img = cv2.drawContours(img, contours, -1, (0,255,0), 3)
this.drawLines()
this.findDifferences()
// print("Y Mean:",np.mean(Ydiffs),"Y Median",np.median(Ydiffs))
// print("X Mean:",np.mean(Xdiffs),"X Median",np.median(Xdiffs))
let success = this.findBoxes()
if (!success){
this.img = cv.imread(img);
threshValue = 225
this.initialImaging(threshValue)
this.lineDetection()
// contours, hierarchy = cv2.findContours(thresholdGray,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
// img = cv2.drawContours(img, contours, -1, (0,255,0), 3)
this.drawLines()
this.findDifferences()
this.findBoxes()
}
// predict
// this.finalGrid = np.array(self.finalGrid)
this.predict()
updateGridHTML(this.finalGrid)
updateGridObject(sudokuGrid.grid)
let r = (window.innerHeight/2 ) / this.img.rows
let dim = [Math.round(this.img.cols * r), (window.innerHeight/2 )]
cv.resize(this.img,this.img, new cv.Size(dim[0], dim[1]),0,0)
cv.imshow('canvasOutput', this.img);
// this.img.delete()
// this.hardThreshold.delete()
// this.thresholdGray.delete()
// this.gray.delete()
// this.edges.delete()
// this.lines.delete()
}
auto_canny(image, sigma=0.33){
// compute the median of the single channel pixel intensities
// let v = [].concat.apply([], image.data);
// let v = median(image.data)
let v=255
// apply automatic Canny edge detection using the computed median
let lower = Math.round(Math.max(0, (1.0 - sigma) * v))
let upper = Math.round(Math.min(255, (1.0 + sigma) * v))
let edged = new cv.Mat()
cv.Canny(image,edged, lower, upper,3,false)
// return the edged image
return edged
}
initialImaging(threshValue){
if (this.img.rows > 750){
cv.resize(this.img,this.img, new cv.Size(0, 0),0.4,0.4)
}
else {
// Initialize arguments for the filter
let top = Math.round(0.01 * this.img.rows) // shape[0] = rows
let bottom = top
let left = Math.round(0.01 * this.img.cols) // shape[1] = cols
let right = left
// cv.copyMakeBorder(src, dst, 10, 10, 10, 10, cv.BORDER_CONSTANT, s);
cv.copyMakeBorder(this.img,this.img, top, bottom, left, right, cv.BORDER_CONSTANT, new cv.Scalar(0, 0, 0, 255))
}
this.gray = new cv.Mat()
cv.cvtColor(this.img, this.gray, cv.COLOR_BGR2GRAY)
// cv.GaussianBlur(this.gray,this.gray, new cv.Size(1, 1), cv.BORDER_DEFAULT)
this.hardThreshold = new cv.Mat()
this.thresholdGray = new cv.Mat()
cv.threshold(this.gray,this.thresholdGray, threshValue, 255, cv.THRESH_BINARY_INV)
// 130 or 225
cv.threshold(this.gray,this.hardThreshold, 200, 255, cv.THRESH_BINARY_INV)
}
lineDetection(){
// https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_houghlines/py_houghlines.html
// edges = cv2.Canny(thresholdGray,100,200, apertureSize=3)
this.edges = this.auto_canny(this.thresholdGray)
this.lines = new cv.Mat();
cv.HoughLines(this.edges,this.lines, 1, Math.PI / 180, 145, 0, 0, 0, Math.PI)
}
drawLines(){
this.horizontal = []
this.vertical = []
for (let i=0;i<this.lines.rows; i++){
let rho = this.lines.data32F[i * 2];
let theta = this.lines.data32F[i * 2 + 1];
let a = Math.cos(theta);
let b = Math.sin(theta);
let x0 = a * rho;
let y0 = b * rho;
let startPoint = {x: x0 - 1000 * b, y: y0 + 1000 * a};
let endPoint = {x: x0 + 1000 * b, y: y0 - 1000 * a};
if (1.55 < theta && theta < 1.58) {
this.horizontal.push(rho);
cv.line(this.img, startPoint, endPoint, [255, 0, 0, 255],2);
}
else if (theta < 0.05) {
this.vertical.push(rho)
cv.line(this.img, startPoint, endPoint, [255, 0, 0, 255],2);
}
}
this.vertical.sort(function(a,b){
return a-b
})
this.horizontal.sort(function(a,b){
return a-b
})
}
findDifferences(){
let largestXDiff = 0
this.Xdiffs = []
for (let i=this.vertical.length - 1;i>0;i--){
let diff = this.vertical[i] - this.vertical[i - 1]
// print(this.vertical[i],this.vertical[i-1],diff)
if (diff > largestXDiff) largestXDiff = diff
this.Xdiffs.push([Math.round(this.vertical[i - 1]), Math.round(this.vertical[i]), diff])
}
// Xdiffs.append(diff)
this.Xdiffs.sort(function(a,b){
return a[0]-b[0]
})
// print("\n\n\n\nYDiffs")
let largestYDiff = 0
this.Ydiffs = []
for (let i=this.horizontal.length - 1;i>0;i--){
let diff = this.horizontal[i] - this.horizontal[i - 1]
// print(this.horizontal[i],this.horizontal[i-1],diff)
if (diff > largestYDiff) largestYDiff = diff
this.Ydiffs.push([Math.round(this.horizontal[i - 1]), Math.round(this.horizontal[i]), diff])
// Ydiffs.append(diff)
}
this.Ydiffs.sort(function(a,b){
return a[0]-b[0]
})
// print(Ydiffs)
}
findBoxes(){
let only_diffs = []
let only_diffs2 = []
for (let i=0;i<this.Ydiffs.length;i++){
if (this.Ydiffs[i][2] > 5){
only_diffs.push(this.Ydiffs[i][2])
}
}
for (let i=0;i<this.Xdiffs.length;i++){
if (this.Xdiffs[i][2] > 5){
only_diffs2.push(this.Xdiffs[i][2])
}
}
let boxMax;
let boxMin;
if (this.img.rows < 400){
boxMin = Math.round(Math.ceil((mean([mean(only_diffs), median(only_diffs), mean(only_diffs2), median(only_diffs2)])) * 0.6))
// boxMax = Math.round((mean([mean(only_diffs),median(only_diffs),mean(only_diffs2),median(only_diffs2)]))*1.5)
boxMax = Math.round(Math.ceil((mean([mean(only_diffs), median(only_diffs), mean(only_diffs2), median(only_diffs2)])) * 1.7))
}
else{
boxMin = Math.round(Math.ceil((mean([mean(only_diffs), median(only_diffs), mean(only_diffs2), median(only_diffs2)])) * 0.7))
// boxMax = Math.round((mean([mean(only_diffs),median(only_diffs),mean(only_diffs2),median(only_diffs2)]))*1.5)
boxMax = Math.round(Math.ceil((mean([mean(only_diffs), median(only_diffs), mean(only_diffs2), median(only_diffs2)])) * 1.3))
}
// print(boxMin, boxMax)
// print(this.Ydiffs)
// print(this.Xdiffs)
let image = 1
this.finalGrid = []
this.means = []
for (let i=0;i<this.Ydiffs.length;i++){
let regions = []
if (this.finalGrid.length == 9) break
if (this.Ydiffs[i][2] > boxMin && this.Ydiffs[i][2] < boxMax){
for (let j=0;j< this.Xdiffs.length;j++){
if (regions.length == 9) break
if (this.Xdiffs[j][2] > boxMin && this.Xdiffs[j][2] < boxMax){
// You can try more different parameters
// let rect = new cv.Rect(100, 100, 200, 200);
// dst = src.roi(rect);
// RECT is of form (xCoordinate , yCoordinate, width, height)
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// let rect = new cv.Rect(this.Ydiffs[j][0], this.Xdiffs[i][0], this.Ydiffs[j][1]-this.Ydiffs[j][0], this.Xdiffs[i][1]-this.Xdiffs[i][0]);
let rect = new cv.Rect(this.Xdiffs[j][0],this.Ydiffs[i][0], this.Xdiffs[j][1]-this.Xdiffs[j][0], this.Ydiffs[i][1]-this.Ydiffs[i][0]);
let roi = this.hardThreshold.roi(rect)
cv.resize(roi,roi, this.size,0,0,cv.INTER_AREA)
if (mean(roi.data) < 100) cv.bitwise_not(roi,roi)
roi = roi.roi(new cv.Rect(3,3,25,25))
// let tempROI = roi.roi(new cv.Rect(0,0,roi.cols-1,1))
// // rows,cols
// while (mean2d(tempROI) < 100) {
// roi = roi.roi(new cv.Rect(1,0,roi.cols-1,roi.rows))
// tempROI = roi.roi(new cv.Rect(0,0,roi.cols-1,1))
// }
// tempROI = roi.roi(new cv.Rect(0,0,1,roi.rows-1))
// while (mean2d(tempROI) < 100) {
// roi = roi.roi(new cv.Rect(0,1,roi.cols,roi.rows-1))
// tempROI = roi.roi(new cv.Rect(0,0,1,roi.rows-1))
// }
cv.resize(roi,roi, this.size,0,0,cv.INTER_AREA)
// cv2.imshow("roi"+str(image),roi)
// print(image,np.mean(roi))
this.means.push(mean2d(roi.roi(new cv.Rect(4,4,roi.rows-4,roi.cols-4))))
regions.push(roi)
image += 1
}
}
if (regions.length == 9) this.finalGrid.push(regions)
else{
if (regions.length == 0) continue
//print("region length", len(regions))
if (regions.length < 9) return false// ERROR
// for i in range(len(regions)):
// cv2.imshow(str(i), regions[i])
}
}
}
cv.imshow('canvasOutput2', this.finalGrid[4][1]);
// cv.imshow('canvasOutput3', this.finalGrid[2][1]);
// cv.imshow('canvasOutput4', this.finalGrid[2][2]);
// cv.imshow('canvasOutput5', this.finalGrid[2][3]);
// cv.imshow('canvasOutput6', this.finalGrid[2][4]);
// cv.imshow('canvasOutput7', this.finalGrid[2][5]);
// cv.imshow('canvasOutput8', this.finalGrid[2][6]);
// cv.imshow('canvasOutput9', this.finalGrid[2][7]);
// cv.imshow('canvasOutput10', this.finalGrid[2][8]);
return true
}
predict(){
let values = []
let tempValues = []
for (let i=0; i<this.means.length;i++){
if (this.means[i] < 245){
let tempImage = tf.tensor1d(this.finalGrid[Math.floor(i / 9)][i % 9].data)
const predictOut = model.predict(tempImage.reshape([1,28,28,1]))
const yPred = predictOut.argMax(-1);
tempValues.push(yPred.dataSync()[0]+1)
}
else{
tempValues.push(0)
}
if (tempValues.length ==9){
values.push(tempValues)
tempValues = []
}
}
this.finalGrid = JSON.parse(JSON.stringify(values))
}
}
function median (array){
if (array.length==0) return 0
array.sort()
let half = Math.floor(array.length /2)
if (array % 2 ==0) return array[half]
return Math.round((array[half-1] + array[half] )/2)
}
function mean(array){
let sum = array.reduce((a, b) => a + b, 0)
return sum/array.length
}
function mean2d(array){
return mean(array.data)
}
var sudokuGrid;
function main() {
// document.getElementById("blah").innerHTML
sudokuGrid = new sudoku()
updateGridObject(sudokuGrid.grid)
}
function updateGridObject(grid){
grid = []
for (let i=0;i<9;i++){
let row = document.getElementById("row"+(i+1)).children
grid[i] = []
for (let j=0;j<9;j++){
if (row.item(j).innerHTML == ""){
grid[i][j] = 0
}
else{
grid[i][j] = parseInt(row.item(j).innerHTML)
}
}
// grid.grid.push(rowArray)
}
console.log("updating object")
sudokuGrid.grid = grid
}
function updateGridHTML(grid){
for (let i=0;i<9;i++){
let row = document.getElementById("row"+(i+1)).children
for (let j=0;j<9;j++){
if (grid[i][j].toString()=="0"){
row.item(j).innerHTML = ""
}
else{
row.item(j).innerHTML = grid[i][j].toString()
}
}
// grid.grid.push(rowArray)
}
console.log("updating HTML")
}
function clearGridHTML(){
document.getElementById("fileInput").value = null;
const context = document.getElementById("canvasOutput").getContext('2d');
context.clearRect(0, 0, document.getElementById("canvasOutput").width, document.getElementById("canvasOutput").height);
for (let i=0;i<9;i++){
let row = document.getElementById("row"+(i+1)).children
for (let j=0;j<9;j++){
row.item(j).innerHTML = ""
}
// grid.grid.push(rowArray)
}
updateGridObject(sudokuGrid.grid)
}
function onOpenCvReady() {
document.getElementById('status').innerHTML = 'If you would like to import an image of a sudoku,<br> please enter the file below';
}
let keypressed = {}
document.addEventListener("DOMContentLoaded",function(){
// Key events and animations
document.onkeydown = function (ev) {
// https://stackoverflow.com/questions/35394937/keyboardevent-keycode-deprecated-what-does-this-mean-in-practice
/*
var code;
if (ev.key !== undefined) {
code = ev.key;
if (code >=0 && code <=9){
updateGridObject(sudokuGrid.grid)
}
}
else if (ev.keyIdentifier !== undefined) {
code = ev.keyIdentifier;
if (code >=0 && code <=9){
updateGridObject(sudokuGrid.grid)
}
}
else if (ev.keyCode !== undefined) {
code = ev.keyCode;
// 48 is 0
// 49 is 1 etc
if (code >=48 && code <=57){
updateGridObject(sudokuGrid.grid)
}
}
// for events on update/ multi key presses
keypressed[code] = true;*/
}
let solveBtn = document.getElementById("solveButton")
function solve (){
updateGridObject(sudokuGrid.grid)
sudokuGrid.solve(sudokuGrid.grid)
updateGridHTML(sudokuGrid.grid)
}
solveBtn.addEventListener("click",solve)
let clearBtn = document.getElementById("clearButton")
clearBtn.addEventListener("click",clearGridHTML)
// TODO: Add step-by-step animation of how backtracking works - with skip one step, skip 10 steps or skip 100 steps
let imgElement = document.getElementById('imageSrc');
let inputElement = document.getElementById('fileInput');
inputElement.addEventListener('change', (e) => {
imgElement.src = URL.createObjectURL(e.target.files[0]);
}, false);
imgElement.onload = function() {
let image = new imagingExtraction(imgElement)
};
async function initModel(){
// return await tf.models.modelFromJSON(myModelJSON)
model = await tf.loadLayersModel('https://raw.githubusercontent.com/Julian-Wyatt/Sudoku/master/Model/js/model.json');
}
initModel()
});