如何在Google Colaboratory中访问Raspberry Pi Picamera实现病害检测
植物病害检测系统:树莓派Picamera的Web访问解决方案
问题根源
Colab上的Gradio Web应用运行在云端服务器,其webcam组件调用的是访问该应用的终端设备(如你的电脑)摄像头,无法直接访问树莓派本地的Picamera。要实现需求,需将检测服务部署到树莓派本地,直接调用硬件摄像头。
解决方案:树莓派本地部署Gradio检测服务
1. 准备工作
- 将Colab中训练好的模型导出为TensorFlow Lite格式(适配树莓派低性能环境,建议做INT8量化),通过SFTP或U盘传到树莓派。
- 确保树莓派已启用摄像头:
选择sudo raspi-configInterface Options > Camera,启用后重启树莓派。
2. 安装依赖包
树莓派Bullseye系统推荐使用Picamera2替代旧版picamera,执行以下命令安装依赖:
pip install gradio opencv-python picamera2 tensorflow-lite
3. 编写检测代码
创建plant_disease_detect.py文件,内容如下:
import gradio as gr import numpy as np from picamera2 import Picamera2 from tensorflow.lite.python.interpreter import Interpreter # 加载TFLite模型 MODEL_PATH = "your_tflite_model.tflite" interpreter = Interpreter(model_path=MODEL_PATH) interpreter.allocate_tensors() input_details = interpreter.get_input_details() output_details = interpreter.get_output_details() INPUT_SHAPE = input_details[0]['shape'][1:3] # 模型输入尺寸,如(224,224) # 初始化Picamera2 picam2 = Picamera2() picam2.configure( picam2.create_preview_configuration( main={"format": "RGB888", "size": INPUT_SHAPE} ) ) picam2.start() def preprocess_image(image): # 适配模型输入要求(根据你的训练预处理逻辑调整) image = np.resize(image, INPUT_SHAPE) image = np.expand_dims(image, axis=0) image = image / 255.0 # 归一化,若训练时用其他方式需对应修改 return image.astype(np.float32) def detect_disease(image): processed_img = preprocess_image(image) interpreter.set_tensor(input_details[0]['index'], processed_img) interpreter.invoke() output = interpreter.get_tensor(output_details[0]['index']) # 解析检测结果(根据你的模型输出格式调整) class_idx = np.argmax(output) confidence = output[0][class_idx] # 替换为你的病害类别名称 disease_classes = ["健康", "黑斑病", "锈病", "白粉病"] return f"检测结果:{disease_classes[class_idx]}\n置信度:{confidence:.2f}" # 构建Gradio界面 with gr.Blocks() as demo: gr.Markdown("# 植物叶片病害检测") with gr.Row(): img_input = gr.Image(source="camera", label="拍摄叶片", height=INPUT_SHAPE[0]) result_box = gr.Textbox(label="检测结果", lines=2) detect_btn = gr.Button("开始检测") detect_btn.click(fn=detect_disease, inputs=img_input, outputs=result_box) # 启动服务:局域网内可通过树莓派IP访问,公网可加share=True生成临时链接 demo.launch(server_name="0.0.0.0", server_port=7860)
4. 运行并访问服务
- 执行代码:
python plant_disease_detect.py - 在同一局域网的设备浏览器中,输入
http://[树莓派IP]:7860即可访问Web界面,直接调用Picamera拍摄并完成病害检测。
注意事项
- 若树莓派性能不足,可进一步对TFLite模型做量化压缩,或降低模型输入尺寸。
- 若Gradio的
camera组件调用失败,可改用Picamera2直接捕获图像并传入检测函数,避免组件兼容性问题。
内容的提问来源于stack exchange,提问作者DAMO
相关产品推荐
相关产品推荐

