handwritten-mathematics-recogniser
Version:
Easy and abstracted way to recognise handwritten mathematics in a browser or in a web view.
105 lines (103 loc) • 3.33 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
class Transformer {
static serializeImage(image) {
const serializedImage = new Array(784);
for (let y = 0; y < 28; y++) {
for (let x = 0; x < 28; x++) {
let mean = 0;
for (let v = 0; v < 10; v++) {
for (let h = 0; h < 10; h++) {
mean += image[y * 10 + v][x * 10 + h];
}
}
mean = (1 - mean / 100);
serializedImage[x * 28 + y] = (mean - 0.5) / 0.5;
}
}
return serializedImage;
}
static subsample(image, source = 64, target = 32) {
const columns = image[0].length;
const rows = image.length;
const array = Array.from({ length: target }, () => Array.from({ length: target }, () => 1));
const ratio = source / target;
for (let y = 0; y < target; y++) {
for (let x = 0; x < target; x++) {
let sum = 0;
for (let v = 0; v < ratio; v++) {
for (let h = 0; h < ratio; h++) {
sum += image[y * ratio + v][x * ratio + h];
}
}
const mean = sum / (ratio * ratio);
array[y][x] = Math.round(mean);
}
}
return array;
}
static getBoundingBox(layer, treshold = 0.01) {
const rows = layer.length;
const columns = layer[0].length;
let minX = columns;
let minY = rows;
let maxX = -1;
let maxY = -1;
for (let y = 0; y < rows; y++) {
for (let x = 0; x < columns; x++) {
if (layer[y][x] < treshold) {
minX = Math.min(minX, x);
maxX = Math.max(maxX, x);
minY = Math.min(minY, y);
maxY = Math.max(maxY, y);
}
}
}
return {
min: {
x: minX,
y: minY
},
max: {
x: maxX,
y: maxY
}
};
}
static flattenImage(image) {
return [].concat.apply([], image);
}
static getCenter(image) {
const rows = image.length;
const columns = image[0].length;
let meanX = 0;
let meanY = 0;
let totalIntensities = 0;
for (let y = 0; y < rows; y++) {
for (let x = 0; x < columns; x++) {
const intensity = (1 - image[y][x]);
totalIntensities += intensity;
meanX += x * intensity;
meanY += y * intensity;
}
}
const centerX = meanX / totalIntensities;
const centerY = meanY / totalIntensities;
return {
x: centerX,
y: centerY
};
}
static invertColors(givenImage) {
const image = [];
for (let y = 0; y < givenImage.length; y++) {
image[y] = [];
for (let x = 0; x < givenImage[y].length; x++) {
image[y][x] = 1 - givenImage[y][x];
}
}
return image;
}
}
exports.Transformer = Transformer;
//# sourceMappingURL=transformer.js.map