<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>百度AI植物识别</title> <style> body { display: flex; flex-direction: column; align-items: center; } video { width: 100%; max-width: 640px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); } .loading-spinner { display: none; width: 40px; height: 40px; border: 4px solid rgba(0, 0, 0, 0.1); border-left-color: #7986cb; border-radius: 50%; animation: spin 1s linear infinite; margin: 20px 0; } @keyframes spin { to { transform: rotate(360deg); } } #result { margin: 20px; padding: 15px; max-width: 640px; width: 100%; border: 1px solid #eee; border-radius: 8px; } #capture { margin: 20px 0; padding: 12px 32px; font-size: 16px; background: #4CAF50; color: white; border: none; border-radius: 25px; cursor: pointer; transition: all 0.3s; } #capture:disabled { background: #cccccc; cursor: not-allowed; } .result-item { margin: 10px 0; padding: 10px; background: #f8f8f8; border-radius: 4px; } </style> </head> <body> <video id="preview" autoplay playsinline></video> <div class="loading-spinner"></div> <button id="capture">拍摄识别</button> <div id="result"></div> <script> // 百度AI配置 const config = { apiKey: 'z3X2W5zIn2qXSp95bhlj6cA6', secretKey: 'zdZvfijzBpgdgm172jFGtxGQe4yrVaUH', plantApi: 'https://aip.baidubce.com/rest/2.0/image-classify/v1/plant' }; // DOM元素 const video = document.getElementById('preview'); const captureBtn = document.getElementById('capture'); const loadingSpinner = document.querySelector('.loading-spinner'); const resultDiv = document.getElementById('result'); let accessToken = ''; // 初始化摄像头 async function initCamera() { try { const stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: "environm
时间: 2025-03-28 07:26:01 浏览: 46
### 百度AI植物识别的HTML实现
百度AI提供了丰富的API接口来支持开发者快速集成其功能,其中包括植物识别的功能。以下是基于百度AI开放平台的植物识别服务的一个简单HTML实现示例。
#### 准备工作
在使用百度AI的服务之前,需要完成以下准备工作:
- 注册并登录百度AI开放平台账户。
- 创建应用以获取 `API Key` 和 `Secret Key`。
- 使用这些密钥调用百度AI的相关接口。
#### 实现代码
下面是一个简单的HTML页面,展示如何通过JavaScript调用来上传图片并请求百度AI的植物识别服务:
```html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>百度AI植物识别</title>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
<h3>百度AI植物识别示例</h3>
<input type="file" id="imageFile" accept="image/*"/>
<button onclick="uploadImage()">识别植物</button>
<p id="result">识别结果将显示在这里...</p>
<script>
function uploadImage() {
const fileInput = document.getElementById('imageFile');
if (!fileInput.files.length) {
alert("请选择一张图片!");
return;
}
const file = fileInput.files[0];
const reader = new FileReader();
reader.onloadend = async () => {
try {
const base64String = reader.result.split(',')[1]; // 获取Base64编码部分
const response = await callBaiduPlantRecognition(base64String);
displayResult(response.data); // 显示返回的结果
} catch (error) {
console.error(error);
alert("发生错误:" + error.message);
}
};
reader.readAsDataURL(file);
}
async function callBaiduPlantRecognition(imageData) {
const apiKey = 'YOUR_API_KEY'; // 替换为您的API Key
const secretKey = 'YOUR_SECRET_KEY'; // 替换为您的Secret Key
// 请求AccessToken
const accessTokenResponse = await axios.get(
`https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${apiKey}&client_secret=${secretKey}`
);
const accessToken = accessTokenResponse.data.access_token;
// 调用植物识别API
const plantRecognitionResponse = await axios.post(
`https://aip.baidubce.com/rest/2.0/image-classify/v1/plant?access_token=${accessToken}`,
null,
{ params: { image: imageData }, headers: { 'Content-Type': 'application/x-www-form-urlencoded' }}
);
return plantRecognitionResponse; // 返回响应数据
}
function displayResult(data) {
let resultText = '';
if (data && data.result) {
data.result.forEach(item => {
resultText += `<strong>${item.name}</strong>: ${Math.round(item.prob * 100)}%<br>`;
});
} else {
resultText = '未检测到任何植物';
}
document.getElementById('result').innerHTML = resultText;
}
</script>
</body>
</html>
```
上述代码实现了以下几个核心功能:
1. 用户可以通过文件输入框选择本地的一张图片。
2. 图片被转换成Base64字符串并通过Axios库发送给百度AI的植物识别API[^1]。
3. 接口返回的数据会被解析,并将可能的植物名称及其置信度分数显示出来。
#### 关键点说明
- **API Key和Secret Key**: 需要替换模板中的占位符为自己申请的实际值。
- **跨域问题**: 如果遇到浏览器端无法正常访问的情况,请确认是否涉及CORS策略限制,并尝试调整服务器配置或代理设置。
- **依赖库**: 此处引入了第三方轻量级HTTP客户端 Axios 来简化网络请求操作[^2]。
---
###
阅读全文
相关推荐
















