您的位置:首页 > 编程语言 > PHP开发

百度OCR文字识别PHP的Demo

2015-09-23 20:38 1246 查看
原帖:http://tieba.baidu.com/p/3850888578
作者:syjsu

<?php

if(isset( $_FILES['image'] )){

$ch = curl_init();
$url = 'http://apis.baidu.com/apistore/idlocr/ocr';
$header = array(
'Content-Type:application/x-www-form-urlencoded',
'apikey:26530e4fbcb99bfcdaf4aedb21d50805',
);

//测试本地文件
$data = file_get_contents($_FILES['image']['tmp_name']);

//测试远程文件
//$data_temp = file_get_contents("ht tp:// 远程图片链接");

$data_temp = base64_encode($data_temp);
$data_temp = urlencode($data_temp);

$data = "fromdevice=pc&clientip=10.10.10.0&detecttype=LocateRecognize&languagetype=CHN_ENG&imagetype=1&image=".$data_temp;

echo "文件".$data;

// 添加apikey到header
curl_setopt($ch, CURLOPT_HTTPHEADER , $header);
// 添加参数
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// 执行HTTP请求
curl_setopt($ch , CURLOPT_URL , $url);
$res = curl_exec($ch);

$temp_var = json_decode($res,true);

//echo "返回到的结果是:";var_dump($temp_var);
//var_dump($data);

if($temp_var["errNum"] == 0){
$temp = $temp_var["retData"][0];
echo "识别到的文字是:".$temp["word"];

//echo "识别到的数组是:";var_dump($temp);

}
else{
echo "识别出错:".$temp_var["errMsg"];
}

}else{

echo "请输入要识别的图片";

}

?>

我顺便也发我客户端上传图片去PHP服务器的代码给大家参考
IOS和Android客户端实现的是拍照,然后把照片发送到PHP服务器上进行OCR文字识别
用的是Unity3D(C#)来写的
/**
* 上传图像识别的代码
*/
public UnityEngine.UI.Text myText;
private IEnumerator IRequestJPG()
{

Rect rect = new Rect( Screen.width*0.25f, Screen.height*0.25f, Screen.width*0.5f, Screen.height*0.5f);
Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24,false); 

// 读取屏幕像素信息并存储为纹理数据
yield return new WaitForEndOfFrame();
screenShot.ReadPixels(rect, 0, 0);
screenShot.Apply();
mCameraTexture = screenShot;
byte[] bs = screenShot.EncodeToJPG();
File.WriteAllBytes(Application.persistentDataPath + "uploadpicture.jpg", bs);

print(Application.persistentDataPath);

WWWForm form = new WWWForm();

form.AddBinaryData("image",bs,"image","image/jpg");
WWW w ww = new WWW("http://服务器的域名/ocr_main.php",form);
yield return www;
if(w ww.error != null){
print(w ww.error);
}
myText.text = w ww.text;
print(w ww.text);
}

最后,请移步百度APIStore,寻找属于你的API!!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: