一个新闻的启示:农业AI的硬需求
最近尼泊尔因巴拿马病、Kharaj害虫等问题收紧农产品进口检疫。其实这类场景在全球农业中每天都在发生。对开发者来说,这意味着农业领域有大量未被满足的数字化需求 —— 比如用AI快速筛查入境农产品中的病害。
与其等政府招标,不如先跑通一个能用的Demo。本文带你从零开始搭建一个植物病害图像识别API,输入叶子照片,返回病害名称和置信度。代码全部可运行,项目结构直接套。
技术选型:轻量、可部署、低成本
| 组件 | 选择 | 理由 |
|---|---|---|
| 模型 | MobileNetV2 (预训练) | 体积小(14MB),适合边缘设备,精度足够做原型 |
| 框架 | TensorFlow 2.x | 生态成熟,TFLite转换方便 |
| 数据集 | PlantVillage (公开) | 包含14种植物、38类病害,共5.4万张图片 |
| API服务 | FastAPI | 异步支持,自动生成文档,部署简单 |
| 容器化 | Docker | 环境一致,便于迁移到服务器或边缘盒 |
个人看法:农业AI场景往往面临网络差、计算资源有限,千万别一上来就上ResNet152。MobileNetV2 + TFLite是性价比最高的起点。后续可以换成EfficientNet-Lite,但初期够用。
核心代码实现
1. 数据集准备
下载PlantVillage数据集(约1.1GB),按类别分文件夹:
bash
1
2
wget https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz # 示例,实际用PlantVillage
# 真实下载:https://data.mendeley.com/datasets/tywbtsjrjv/1
目录结构:
text
1
2
3
4
5
6
7
dataset/
train/
Apple___Apple_scab/
Apple___Black_rot/
...
validation/
...
2. 训练脚本(关键片段)
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import tensorflow as tf
from tensorflow.keras.applications import MobileNetV2
from tensorflow.keras.layers import Dense, GlobalAveragePooling2D
from tensorflow.keras.models import Model
# 数据增强
train_datagen = tf.keras.preprocessing.image.ImageDataGenerator(
rescale=1./255,
rotation_range=30,
zoom_range=0.2,
horizontal_flip=True
)
train_generator = train_datagen.flow_from_directory(
'dataset/train',
target_size=(224, 224),
batch_size=32,
class_mode='categorical'
)
# 加载预训练模型(不含顶层)
base_model = MobileNetV2(weights='imagenet', include_top=False, input_shape=(224,224,3))
base_model.trainable = False # 冻结特征提取层
# 添加分类头
x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dense(128, activation='relu')(x)
predictions = Dense(train_generator.num_classes, activation='softmax')(x)
model = Model(inputs=base_model.input, outputs=predictions)
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# 训练
history = model.fit(train_generator, epochs=10)
# 保存为TensorFlow SavedModel
model.save('plant_disease_model.h5')
注意:10个epoch在GTX 1060上约需30分钟。如果只想测试API,可以用我预先训练好的模型(链接见文末)。
3. 导出为TFLite(可选,但推荐)
python
1
2
3
4
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
with open('model.tflite', 'wb') as f:
f.write(tflite_model)
TFLite模型大小约4MB,可以在树莓派上运行。
4. FastAPI服务
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
from fastapi import FastAPI, File, UploadFile
import tensorflow as tf
import numpy as np
import json
app = FastAPI()
# 加载模型
model = tf.keras.models.load_model('plant_disease_model.h5')
class_indices = json.load(open('class_indices.json')) # 格式:{"0": "Apple___Apple_scab", ...}
@app.post("/predict")
async def predict(file: UploadFile = File(...)):
contents = await file.read()
img = tf.image.decode_image(contents, channels=3)
img = tf.image.resize(img, [224, 224])
img = img / 255.0
img = tf.expand_dims(img, 0)
predictions = model.predict(img)
class_idx = np.argmax(predictions[0])
confidence = float(predictions[0][class_idx])
return {
"disease": class_indices[str(class_idx)],
"confidence": round(confidence, 4)
}
@app.get("/")
def root():
return {"message": "Plant Disease Detection API ready"}
启动:uvicorn main:app --reload,访问 http://localhost:8000/docs 即可测试。
项目结构和配置
text
1
2
3
4
5
6
7
8
9
10
11
12
13
project/
├── main.py # FastAPI应用
├── requirements.txt # tensorflow, fastapi, uvicorn, python-multipart
├── Dockerfile
├── .dockerignore
├── model/
│ ├── plant_disease_model.h5
│ └── class_indices.json
├── scripts/
│ └── train.py # 训练脚本
└── dataset/
├── train/
└── validation/
Dockerfile关键内容:
dockerfile
1
2
3
4
5
6
FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
上线要注意的坑
- 模型大小:h5模型约60MB,如果服务器带宽小,建议用TFLite(4MB)或TensorFlow Serving(更专业但配置复杂)。
- 并发处理:FastAPI单线程下模型预测是同步阻塞。可以用
run_in_executor或直接上TensorFlow Serving。个人建议:如果QPS<10,当前方案足够;如果需要高并发,把模型加载到共享内存或用Ray Serve。 - 数据集版权:PlantVillage数据集遵循CC0,可商用。但注意实际部署需用本地数据微调,避免地域差异导致精度下降。
- 图像预处理:用户上传的图片可能很大,务必先压缩再推理。上面代码已经做了resize,但建议前端限制2MB大小。
- 边界情况:如果上传非植物图片,模型会强行分类到一个已知类别,置信度可能虚高。可以添加一个“非植物”阈值(如最高置信度<0.5则返回“未知”)。
对开发者的真正建议
尼泊尔这次检疫事件背后,是农业供应链对快速、低成本检测工具的强烈需求。作为开发者,你可以:
- 把这个API嵌入到海关查验的移动APP中,拍照即出结果;
- 或者结合无人机巡田数据,做病害早期预警;
- 甚至用联邦学习,让各地农场共享模型却不泄露数据。
别再观望了。 趁大厂还没全面覆盖农业AI,先用这个Demo跑通业务逻辑,你就有机会拿到农业数据的一手话语权。
代码已上传GitHub:github.com/yeqingyuan/plant-disease-api(示例地址)