步骤 1:注册百度开发者账号并创建人脸识别应用

  1. 访问 百度智能云官网 注册账号。
  2. 登录后,在控制台创建人脸识别应用,获取 API Key 和 Secret Key,这两个密钥用于后续调用 API 进行身份验证。

步骤 2:创建 React 项目

打开终端,执行以下命令创建一个新的 React 项目:

npx create-react-app face-recognition-react
cd face-recognition-react

步骤 3:安装必要的依赖

在项目根目录下,安装 axios 用于发送 HTTP 请求:

npm install axios

步骤 4:编写 React 代码

在 src 目录下创建一个 FaceRecognition.js 文件,代码如下:

import React, { useState } from 'react';
import axios from 'axios';

const FaceRecognition = () => {
  const [imageUrl, setImageUrl] = useState('');
  const [result, setResult] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  // 百度 API 的相关信息
  const API_KEY = 'your_api_key';
  const SECRET_KEY = 'your_secret_key';
  const ACCESS_TOKEN_URL = `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${API_KEY}&client_secret=${SECRET_KEY}`;
  const FACE_DETECT_URL = 'https://aip.baidubce.com/rest/2.0/face/v3/detect';

  const getAccessToken = async () => {
    try {
      const response = await axios.get(ACCESS_TOKEN_URL);
      return response.data.access_token;
    } catch (err) {
      setError('获取访问令牌失败,请检查 API Key 和 Secret Key。');
      console.error('获取访问令牌失败:', err);
      return null;
    }
  };

  const handleDetect = async () => {
    if (!imageUrl) {
      setError('请输入有效的图片 URL。');
      return;
    }
    setLoading(true);
    setError(null);
    setResult(null);

    const accessToken = await getAccessToken();
    if (!accessToken) {
      setLoading(false);
      return;
    }

    try {
      const response = await axios.post(
        `${FACE_DETECT_URL}?access_token=${accessToken}`,
        {
          image: encodeURIComponent(imageUrl),
          image_type: 'URL',
          face_field: 'age,beauty,expression,face_shape,gender,glasses,landmark,race,qualities'
        },
        {
          headers: {
            'Content-Type': 'application/json'
          }
        }
      );
      setResult(response.data);
    } catch (err) {
      setError('人脸识别失败,请检查图片 URL 或网络连接。');
      console.error('人脸识别失败:', err);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <h1>人脸识别</h1>
      <input
        type="text"
        placeholder="输入图片 URL"
        value={imageUrl}
        onChange={(e) => setImageUrl(e.target.value)}
      />
      <button onClick={handleDetect} disabled={loading}>
        {loading ? '识别中...' : '开始识别'}
      </button>
      {error && <p style={{ color: 'red' }}>{error}</p>}
      {result && (
        <pre>
          {JSON.stringify(result, null, 2)}
        </pre>
      )}
    </div>
  );
};

export default FaceRecognition;

步骤 5:在 App.js 中使用 FaceRecognition 组件

import React from 'react';
import FaceRecognition from './FaceRecognition';

function App() {
  return (
    <div className="App">
      <FaceRecognition />
    </div>
  );
}

export default App;

步骤 6:运行项目

在终端中执行以下命令启动开发服务器:

npm start

代码说明

  1. 获取访问令牌:通过 getAccessToken 函数向百度 API 服务器请求访问令牌,该令牌用于后续的人脸识别请求。
  2. 人脸识别:在 handleDetect 函数中,首先检查输入的图片 URL 是否有效,然后获取访问令牌,最后发送人脸识别请求。
  3. 状态管理:使用 useState 钩子管理图片 URL、识别结果、加载状态和错误信息。
  4. 界面交互:提供一个输入框用于输入图片 URL,一个按钮用于触发识别操作,并显示识别结果或错误信息。

注意事项

  • 请将 API_KEY 和 SECRET_KEY 替换为你自己的百度人脸识别应用的密钥。
  • 百度人脸识别 API 有一定的调用限制和费用标准,请根据实际需求进行使用

别在最能吃苦的年纪选择安逸,现在的努力,是为了将来能有更多的选择。

相信自己,你一定可以做到

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐