Node.js Image to Text (KTP INDONESIA)
To run this code, you need to ensure you have installed the necessary dependencies, particularly Tesseract.js. You can install Tesseract.js using npm:
npm install tesseract.js
Copy Paste This Code:
const Tesseract = require('tesseract.js'); async function recognizeKTP(imagePath) { try { // Run OCR on the provided image const { data: { text } } = await Tesseract.recognize( imagePath, 'ind', // Set the language to Indonesian { logger: m => console.log(m) } // Optional logger function to see progress ); // Extract relevant fields from the recognized text const ktpData = { NIK: '', Nama: '', TglLahir: '', TempatLahir: '', JenisKelamin: '', Alamat: '', GolDarah: '', Agama: '', StatusPerkawinan: '', Pekerjaan: '', Kewarganegaraan: '', Propinsi: '', Kabupaten: '', BerlakuHingga: '' }; const lines = text.split('\n'); lines.forEach((line, index) => { if (index === 0) { ktpData.Propinsi = line; } else if (index === 1) { ktpData.Kabupaten = line; } if (line.includes('NIK')) { ktpData.NIK = line.split(': ')[1]; } else if (line.includes('Nama')) { ktpData.Nama = line.split(': ')[1]; } else if (line.includes('Tempat/Tgl Lahir')) { let currData = line.split(': '); let tempatTanggalLahir = currData[1].split(', '); let tempatLahir = tempatTanggalLahir[0]; let tanggalLahir = tempatTanggalLahir[1].substring(0, 10); ktpData.TglLahir = tanggalLahir; ktpData.TempatLahir = tempatLahir; } else if (line.includes('Jenis Kelamin')) { let currData = line.split(': '); let currData1 = currData[1].split(' — '); ktpData.JenisKelamin = currData1[0]; ktpData.GolDarah = currData1[1].split(':')[1]; } else if (line.includes('Alamat')) { ktpData.Alamat = line.split(': ')[1]; } else if (line.includes('Gol. Darah')) { let currData = line.split(': '); let currData1 = currData[1].split(' — '); } else if (line.includes('Agama')) { ktpData.Agama = line.split(': ')[1]; } else if (line.includes('Status Perkawinan')) { ktpData.StatusPerkawinan = line.split(': ')[1]; } else if (line.includes('Pekerjaan')) { ktpData.Pekerjaan = line.split(': ')[1]; } else if (line.includes('Kewarganegaraan')) { ktpData.Kewarganegaraan = line.split(': ')[1].substring(0, 3); } else if (line.includes('Berlaku Hingga')) { ktpData.BerlakuHingga = line.split(': ')[1].substring(0, 10); } }); console.log('KTP Data:', ktpData); } catch (error) { console.error('Error:', error); } } // Replace 'media/ktp1.jpeg' with the path to your KTP image file recognizeKTP('media/ktp1.jpeg');
Komentar
Posting Komentar