通过FastAPI提供HTTP接口控制海康工业相机拍照
pip install -r requirements.txt
python camera_api.py
服务将在 http://localhost:8000 启动
启动服务后访问:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
GET /cameras
响应示例:json { "success": true, "count": 2, "cameras": [ { "index": 0, "type": "GigE", "model": "MV-CS200-10GC", "serial": "00J12345678", "ip": "192.168.1.100", "user_defined_name": "Camera1" } ] }
GET /capture?ip=192.168.1.100&filename=test_image
POST /capturejson { "ip": "192.168.1.100", "filename": "test_image", "save_bmp": true, "save_jpg": true, "timeout": 3000 }
响应示例:json { "success": true, "message": "拍照成功", "files": ["test_image.bmp", "test_image.jpg"], "camera_info": { "type": "GigE", "model": "MV-CS200-10GC", "serial": "00J12345678", "ip": "192.168.1.100" } }
GET /capture_by_serial?serial=00J12345678&filename=test_image
GET /capture_by_index?index=0&filename=test_image
GET /image/test_image.jpg
GET /health
import requests
# 列出所有相机
response = requests.get("http://localhost:8000/cameras")
cameras = response.json()["cameras"]
# 通过IP地址拍照
response = requests.get(
"http://localhost:8000/capture",
params={
"ip": "192.168.1.100",
"filename": "my_image"
}
)
result = response.json()
print(f"保存的文件: {result['files']}")
# 下载图片
response = requests.get("http://localhost:8000/image/my_image.jpg")
with open("downloaded.jpg", "wb") as f:
f.write(response.content)
# 列出相机
curl http://localhost:8000/cameras
# 拍照(GET)
curl "http://localhost:8000/capture?ip=192.168.1.100&filename=test_image"
# 拍照(POST)
curl -X POST http://localhost:8000/capture \
-H "Content-Type: application/json" \
-d '{"ip":"192.168.1.100","filename":"test_image"}'
# 下载图片
curl -O http://localhost:8000/image/test_image.jpg
// 列出相机
fetch('http://localhost:8000/cameras')
.then(res => res.json())
.then(data => console.log(data));
// 拍照
fetch('http://localhost:8000/capture?ip=192.168.1.100&filename=test_image')
.then(res => res.json())
.then(data => console.log(data));
// 下载图片
fetch('http://localhost:8000/image/test_image.jpg')
.then(res => res.blob())
.then(blob => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'test_image.jpg';
a.click();
});
运行测试客户端:
python test_api.py
camera_api.py - FastAPI服务主文件camera_manager.py - 相机管理类test_api.py - API测试客户端test.py - 基础测试脚本example_multi_camera.py - 多相机使用示例requirements.txt - Python依赖python camera_api.py