|
| 1 | +#!/usr/bin/env node |
| 2 | +const path = require('path'); |
| 3 | +const fs = require('fs'); |
| 4 | +const { createWorker } = require('../../'); |
| 5 | + |
| 6 | +const [,, imagePath] = process.argv; |
| 7 | +const image = path.resolve(__dirname, (imagePath || '../data/meditations.jpg')); |
| 8 | + |
| 9 | +console.log(`Recognizing ${image}`); |
| 10 | + |
| 11 | +// Tesseract.js returns images (imageColor, imageGrey, imageBinary) as strings |
| 12 | +// to be used as source tags. |
| 13 | +// This function converts to Uint8Array data for saving to disk. |
| 14 | +const convertImage = (imageSrc) => { |
| 15 | + const data = atob(imageSrc.split(',')[1]) |
| 16 | + .split('') |
| 17 | + .map((c) => c.charCodeAt(0)); |
| 18 | + |
| 19 | + return new Uint8Array(data); |
| 20 | +} |
| 21 | + |
| 22 | +(async () => { |
| 23 | + const worker = await createWorker(); |
| 24 | + await worker.loadLanguage('eng'); |
| 25 | + await worker.initialize('eng'); |
| 26 | + const { data: { imageColor, imageGrey, imageBinary } } = await worker.recognize(image, {rotateAuto: true}, {imageColor: true, imageGrey: true, imageBinary: true}); |
| 27 | + |
| 28 | + console.log('Saving intermediate images: imageColor.png, imageGrey.png, imageBinary.png'); |
| 29 | + |
| 30 | + fs.writeFileSync('imageColor.png', convertImage(imageColor)); |
| 31 | + fs.writeFileSync('imageGrey.png', convertImage(imageGrey)); |
| 32 | + fs.writeFileSync('imageBinary.png', convertImage(imageBinary)); |
| 33 | + |
| 34 | + await worker.terminate(); |
| 35 | +})(); |
0 commit comments