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