I'm Sham
一个在通往码农道路上走走停停的行政文员

通过百度OCR接口来实现小程序文字识别

因为图书管理需要,有的从接口获取的图书简介是没有的,那如果自己一个个敲进去显然耗时很长,而很多书籍在开头或者封皮上都会印有书籍简介,那Sham就想着用文字识别OCR来实现。

最终选择了百度的OCR接口,因为标准识别赠送5万次/天的识别,无比适合,这里就不去介绍如何申请接口了,可以自行去看介绍申请,网址:

https://cloud.baidu.com/product/ocr_general

下面就将下Sham是如何用接口在小程序上实现的

首先是配置服务器端,用的是PHP,代码如下:

<?php
  header('Content-type: application/json');

  //获取百度接口的token
  $url = 'https://aip.baidubce.com/oauth/2.0/token';
  $post_data['grant_type']  = 'client_credentials';
  $post_data['client_id'] = '这里输入百度OCR接口的id';  
  $post_data['client_secret'] = '这里输入百度OCR接口的secret';
  $o = "";
  foreach ( $post_data as $k => $v ) 
  {
  	$o.= "$k=" . urlencode( $v ). "&" ;
  }
  $post_data = substr($o,0,-1);
  $res = json_decode(request_post($url, $post_data),true);
  
  
  // 允许上传的图片后缀
  $allowedExts = array("gif", "jpeg", "jpg", "JPG", "pjpeg", "png", "x-png");
  $temp = explode(".", $_FILES["file"]["name"]);
  // echo $_FILES["file"]["size"];
  $extension = end($temp);     // 获取文件后缀名
  if ((($_FILES["file"]["type"] == "image/gif")
  || ($_FILES["file"]["type"] == "image/jpeg")
  || ($_FILES["file"]["type"] == "image/jpg")
  || ($_FILES["file"]["type"] == "image/JPG")
  || ($_FILES["file"]["type"] == "image/pjpeg")
  || ($_FILES["file"]["type"] == "image/x-png")
  || ($_FILES["file"]["type"] == "image/png"))
  && ($_FILES["file"]["size"] < 20480000)   // 小于 200 kb
  && in_array($extension, $allowedExts))
  {
    $uploaded_file=$_FILES['file']['tmp_name'];

  //通过token来访问ocr接口实现图片识别成文字
    $token = $res['access_token'];
    $url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=' . $token;
    $img = file_get_contents($uploaded_file);
    $img = base64_encode($img);
    $bodys = array('image' => $img);
    $ress = json_decode(request_post($url, $bodys),true);
    $words_result = $ress['words_result'];
    $content ='';
    for($i=0;$i<count($words_result);$i++){
      $content.=$words_result[$i]['words'];
    }
    echo $content;

  }else{
    echo "上传错误";
  }
 
  //CURL post提交方式
  function request_post($url = '', $param = '') {
    if (empty($url) || empty($param)) {
      return false;
    }
    
    $postUrl = $url;
    $curlPost = $param;
    $curl = curl_init();//初始化curl
    curl_setopt($curl, CURLOPT_URL,$postUrl);//抓取指定网页
    curl_setopt($curl, CURLOPT_HEADER, 0);//设置header
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
    curl_setopt($curl, CURLOPT_POST, 1);//post提交方式
    curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
    $data = curl_exec($curl);//运行curl
    curl_close($curl);
    
    return $data;
  }
  
?>

然后是小程序端通过上传图片功能来实现传图片给服务器端用于识别并获取返回结果

scanocr(e){
	var that = this;
	wx.chooseImage({  //从本地相册选择图片或使用相机拍照
	  count: 1, // 默认9
	  sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
	  sourceType: ['camera'], // 可以指定来源是相册还是相机,默认二者都有
	  success: function (res) {
		////console.log(res)
		// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
		var tempFilePaths = res.tempFilePaths
		wx.showToast({
		  title: '正在上传中',
		  icon: 'loading',
		  duration: 150000
		})
		//console.log(tempFilePaths)
		  wx.uploadFile({
			url: photourl + 'ocr.php',  //记得定义个photourl或者替换城网址
			filePath: tempFilePaths[0],
			name: 'file',
			formData:{
			},
			success: function (res) {
			  wx.hideToast();
			  console.log(res.data)
			  that.setData({
				ocrres:res.data
			  })
			}
		  })
	  }
	})
},

这样,你就能实现OCR功能啦

赞(0) 赏杯咖啡!
未经允许不得转载:Sham@双目瞿 » 通过百度OCR接口来实现小程序文字识别

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

如果你觉得文章好,请赏1杯速溶咖啡给Sham吧!

微信扫一扫打赏