赞
踩
这里是抠出人物的前景图,背景为透明
前提条件,你已经搭建好php环境
access_token:必须参数,参考“Access Token获取”。
这个就在讲解 ,最简单的方式 在浏览器输入接口地址
https://aip.baidubce.com/rest/2.0/image-classify/v1/body_analysis?access_token=24.f9ba9c5241b67688bb4adbed8bc91dec.2592000.1485570332.282335-8574074
向授权服务地址https://aip.baidubce.com/oauth/2.0/token发送请求(推荐使用POST),并在URL中带上以下参数:
grant_type: 必须参数,固定为client_credentials; client_id: 必须参数,应用的API Key;
client_secret: 必须参数,应用的Secret Key; 帮对应的参数传递进去即可,
自己去百度AI平台 找到对应的模块创建一个应用
下面直接上代码
在你的PHP运行环境的www根目录下创建一个文件夹
txfg 文件夹
在里面建立对应文件
index.html 代码如下
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>图像分割技术</title> </head> <body> <form method="post" action="./trfg.php" enctype="multipart/form-data"> <table border=0 cellspacing=0 cellpadding=0 align=center width="100%"> <tr> <td width=55 height=20 align="center"><input type="hidden" name="MAX_FILE_SIZE" value="2000000">文件 </TD> <td height="16"> <input name="file" type="file" /> <!--这里指定了上传后所在临时数组的名称--> <input type="submit" name="submit" value="开始上传" /> </td> </tr> </table> </form> </body> </html>
trfg.php 代码如下
<?php header('Access-Control-Allow-Origin: *'); // 解决前段javascript跨域请求 $filename = $_FILES['file']['name']; $tmp_name = $_FILES['file']['tmp_name']; //将服务器上的临时文件移动到指定目录下 //使用该方法move_uploaded_file($tmp_name , $destination) move_uploaded_file($tmp_name , "./files/".$filename); $urls ='./files/'.$filename; /** * 发起http post请求(REST API), 并获取REST请求的结果 * @param string $url * @param string $param * @return - http response body if succeeds, else false. */ function request_post($url = '', $param = ''){ if (empty($url) || empty($param)) { return false; } $postUrl = $url; $curlPost = $param; // 初始化curl $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $postUrl); curl_setopt($curl, CURLOPT_HEADER, 0); // 要求结果为字符串且输出到屏幕上 curl_setopt($curl,CURLOPT_RETURNTRANSFER,1); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//跳过证书验证 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // post提交方式 curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost); // 运行curl $data = curl_exec($curl); curl_close($curl); return $data; } $token = '自己的access_token'; $url = 'https://aip.baidubce.com/rest/2.0/image-classify/v1/body_seg?access_token=' . $token; $img1 = file_get_contents($urls); $img = base64_encode($img1); $type= 'foreground'; $bodys = array( 'image' => $img, 'type' =>$type ); $res = request_post($url, $bodys); $data = json_decode($res,true); $imgbg = "data:image/png;base64,".$data['foreground']; echo "<div style='width: 400px;height: 250px;border: 1px solid red;margin:100px auto;'> <img src=".$imgbg." style='width:100%;height:100%;background-size: cover;' /> </div>";
注意上面的$token = ‘自己的access_token’; 这里要换成的自己的access_token,上面的图片自己根据宽度自己调整
效果如下 我们网上下载一张明星的图片
经过百度AI人像分割后的图片如下
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。