| 77 | } |
| 78 | |
| 79 | recognize() { |
| 80 | const {ctx, w: width, bg} = this; |
| 81 | const {width: patchWidth, height: patchHeight} = this.patch; |
| 82 | const posY = this.y + PUZZLE_PAD + ((patchHeight - PUZZLE_PAD) / 2) - (PUZZLE_GAP / 2); |
| 83 | // const cData = ctx.getImageData(0, a.y + 10 + 20 - 4, 360, 8).data; |
| 84 | const cData = bg.getImageData(0, posY, width, PUZZLE_GAP).data; |
| 85 | const lumas = []; |
| 86 | |
| 87 | for (let x = 0; x < width; x++) { |
| 88 | let sum = 0; |
| 89 | |
| 90 | // y xais |
| 91 | for (let y = 0; y < PUZZLE_GAP; y++) { |
| 92 | let idx = x * 4 + y * (width * 4); |
| 93 | let r = cData[idx]; |
| 94 | let g = cData[idx + 1]; |
| 95 | let b = cData[idx + 2]; |
| 96 | let luma = 0.2126 * r + 0.7152 * g + 0.0722 * b; |
| 97 | |
| 98 | sum += luma; |
| 99 | } |
| 100 | |
| 101 | lumas.push(sum / PUZZLE_GAP); |
| 102 | } |
| 103 | |
| 104 | const n = 2; // minium macroscopic image width (px) |
| 105 | const margin = patchWidth - PUZZLE_PAD; |
| 106 | const diff = 20; // macroscopic brightness difference |
| 107 | const radius = PUZZLE_PAD; |
| 108 | for (let i = 0, len = lumas.length - 2 * 4; i < len; i++) { |
| 109 | const left = (lumas[i] + lumas[i + 1]) / n; |
| 110 | const right = (lumas[i + 2] + lumas[i + 3]) / n; |
| 111 | const mi = margin + i; |
| 112 | const mLeft = (lumas[mi] + lumas[mi + 1]) / n; |
| 113 | const mRigth = (lumas[mi + 2] + lumas[mi + 3]) / n; |
| 114 | |
| 115 | if (left - right > diff && mLeft - mRigth < -diff) { |
| 116 | const pieces = lumas.slice(i + 2, margin + i + 2); |
| 117 | const median = pieces.sort((x1, x2) => x1 - x2)[20]; |
| 118 | const avg = Math.avg(pieces); |
| 119 | |
| 120 | // noise reducation |
| 121 | if (median > left || median > mRigth) return; |
| 122 | if (avg > 100) return; |
| 123 | // console.table({left,right,mLeft,mRigth,median}); |
| 124 | // ctx.fillRect(i+n-radius, 0, 1, 360); |
| 125 | // console.log(i+n-radius); |
| 126 | return i + n - radius; |
| 127 | } |
| 128 | } |
| 129 | |
| 130 | // not found |
| 131 | return -1; |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | const DATA = { |