拍照识别图片中的文字(调研)

592 阅读1分钟

1、打开摄像头

HTML5有打开摄像头功能:MediaDevices.getUserMedia()

核心代码

var constraints = { audio: true, video: { width: 1280, height: 720 } }; 

navigator.mediaDevices.getUserMedia(constraints)
.then(function(mediaStream) {
  var video = document.querySelector('video');
  video.srcObject = mediaStream;
  video.onloadedmetadata = function(e) {
    video.play();
  };
})
.catch(function(err) { console.log(err.name + ": " + err.message); }); // 总是在最后检查错误

JavaScript实现图片文字识别与读取(实现ORC)

Tesseract.js

引入Tesseract.js

Tesseract.recognize的识别方法有两个配置参数

第一个参数可以是本地的一个图片,也可以是网络上的一个图片地址,还可以是一个base64格式的二进制图片格式;

第二个参数就是配置信息,包括识别的语种等等。这里classify_bln_numeric_mode表示假定图片中只有数字,大家可以根据自己需要去设置不同的值

function recognize_image(){
	document.getElementById('transcription').innerText = "(等待中...)"
	Tesseract.recognize("./显示底部桌面.png", {
	  lang: 'chi_sim',
    classify_bln_numeric_mode: 1
}).then(function(result){
		console.log('哈哈',result.text);  //识别出的文字
		document.getElementById('transcription').className = "done"
 document.getElementById('transcription').innerText = result.text;
});
}				 
 </script>
 <div id="main">
 <!-- CODE大全:www.codedq.net -->
 <img id="pic" src="./显示底部桌面.png" "recognize_image()">
 <div id="transcription"></div>
 </div>

Tesseract.create({
    workerPath: '/path/to/worker.js',
    langPath: 'https://localhost/',
    corePath: 'https://localhost/index.js',
}).recognize("http://xxx/xxx.jpg", {
    lang: 'eng',
    classify_bln_numeric_mode: 1
}).then(function(result){
    $("#code").val(result.text);
});

workerPath: worker.js路径,worker.js可以从第一步中下载的dist目录中获取

langPath: 语言资源包请求地址,默认 cdn.rawgit.com/naptha/tess…

语言包url可以通过 langPath + langCode + '.traineddata.gz’计算得到,例如英语的语言包地址在上例中就是 https://localhost/eng.traineddata.gz。这里说的语言是指图片中待识别的内容是何种语言,可以在 recognize 方法中通过第二个参数设置,上例中设置语言为 eng,完整的可取语言列表参见 github.com/naptha/tess… corePath: index.js 路径,默认 cdn.rawgit.com/naptha/tess…