File size: 9,907 Bytes
403f212
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# CropGuard GH β€” System Documentation

**Image-Based Crop Disease Detection System for Smallholder Farmers in Ghana**
Final Year Project Β· Oppong David Β· BTech Computer Technology, Kumasi Technical University

---

## 1. What this is

CropGuard is the working implementation of the system designed in the project report. A farmer photographs a diseased crop leaf and instantly receives:

- the **disease name** (55 classes across 14 crops cultivated in Ghana),
- a **confidence score**,
- a **severity level** (Early / Moderate / Severe) with colour coding,
- an **urgency level** (Routine / Urgent / Emergency), and
- a numbered list of **treatment steps** plus suggested products.

It ships in **two forms**, both included here:

| Deliverable | File | Use it for |
|---|---|---|
| **Ready-to-use HTML app** | `cropguard.html` | Open in any browser/phone. Works immediately (on-device estimate). No install. Covers all 14 Ghanaian crops when connected to the model. Bilingual (English + Twi toggle). |
| **Full production system** | `cropguard-system/` | The real stack from Chapter 3: trained MobileNetV2 model + FastAPI backend + React frontend. |

The HTML app can **also** connect to the trained backend β€” open Settings and paste the API URL, or set `localStorage.cropguard_api`. When no server is set it falls back to a genuine on-device colour/lesion analyser so it is never broken.

---

## 2. Architecture

The system follows the three-component client–server model described in Β§3.3:

```
   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”         HTTPS / multipart        β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
   β”‚   Frontend (client)     β”‚  ── POST /predict (image) ──▢    β”‚   Backend (server)        β”‚
   β”‚  React app  OR          β”‚                                  β”‚   FastAPI                 β”‚
   β”‚  single-file HTML        β”‚  ◀── JSON diagnosis ──────       β”‚   β”œβ”€ MobileNetV2 model    β”‚
   β”‚  (camera + gallery)      β”‚                                  β”‚   β”œβ”€ severity estimator   β”‚
   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                                  β”‚   └─ recommendations.json β”‚
                                                                 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

- **Inference runs on the server**, so the model can be updated without users reinstalling anything and old phones still work (Β§3.3).
- **Communication is a stateless REST API** returning JSON (Β§3.3).
- **Uploaded images are never stored** β€” they are processed in memory and discarded (Β§3.10.2 / Β§3.13 privacy-by-design).

---

## 3. The model (`backend/train.py`)

A transfer-learning classifier (MobileNetV2 **or** EfficientNetB0, via `--arch`), built as specified in Β§3.6:

**Accuracy target ~98%.** MobileNetV2 reaches roughly 97–98% on this benchmark; for the full multi-crop set use `--arch efficientnet` (EfficientNetB0), which typically reaches **98–99%**, in line with the published literature (Mohanty et al. 2016 = 99.35%, Ferentinos 2018 = 99.53%). The figure is reported honestly from the held-out test set at the end of training β€” it is never assumed. Label smoothing, class weighting and field-condition augmentation are included to push real-world accuracy toward the target.

- **Input:** 224Γ—224 RGB, normalised with ImageNet mean/std.
- **Backbone:** MobileNetV2 or EfficientNetB0 pre-trained on ImageNet.
- **Head:** Global Average Pooling β†’ BatchNorm β†’ Dense(512, ReLU, L2=1e-4) β†’ Dropout(0.4) β†’ Dense(softmax).
- **Two-phase fine-tuning (Β§3.6.3):** Phase 1 trains the head with the backbone frozen (Adam, lr=1e-3, ~20 epochs); Phase 2 unfreezes the top 30% of the backbone (Adam, lr=1e-4, ~30 epochs) with `EarlyStopping` and `ReduceLROnPlateau`.
- **Loss:** categorical cross-entropy with label smoothing (0.05).
- **Class imbalance (Β§3.7.1):** balanced class weights computed with scikit-learn.
- **Augmentation (Β§3.5.2):** flip, rotation, zoom, brightness and contrast jitter.

### Dataset layout expected

```
data/
  train/<class_name>/*.jpg
  val/<class_name>/*.jpg
  test/<class_name>/*.jpg
```

Class folder names must match the keys in `recommendations.json`:

```
maize_healthy maize_gls maize_nclb maize_rust maize_msv maize_faw
cassava_healthy cassava_cmd cassava_cbsd cassava_cbb
tomato_healthy tomato_early tomato_late tomato_wilt tomato_septoria tomato_tylcv
cocoa_healthy cocoa_blackpod cocoa_cssvd cocoa_capsid
cashew_healthy cashew_anthracnose cashew_gumosis cashew_leafminer
plantain_healthy plantain_sigatoka plantain_bbtv plantain_panama
yam_healthy yam_anthracnose yam_mosaic
pepper_healthy pepper_bacterialspot pepper_anthracnose
cowpea_healthy cowpea_blight cowpea_mosaic cowpea_cercospora
groundnut_healthy groundnut_leafspot groundnut_rosette groundnut_rust
rice_healthy rice_blast rice_blb rice_brownspot
okra_healthy okra_yvmv okra_leafspot
gardenegg_healthy gardenegg_wilt gardenegg_leafspot
mango_healthy mango_anthracnose mango_bacterialspot
```

**Covering all crops:** the system is not limited to a fixed list. To add any
further crop, drop a labelled folder of its images into `train/`, `val/` and
`test/`, add a matching record to `recommendations.json`, and retrain β€” no code
change is required.

Recommended sources (Β§3.4), Ghana-relevant: the **CCMT dataset** (Cashew, Cassava, Maize, Tomato β€” field images collected in Ghana), **cassava** disease datasets, **cocoa** (CRIG/COCOBOD imagery), the **rice / cowpea / groundnut** sets from African research programmes, and **PlantVillage/PlantDoc** for tomato, pepper and mango. Locally collected field photographs are added where possible.

### Train

```bash
cd backend
pip install -r requirements.txt
python train.py --data ./data --arch efficientnet --epochs-head 20 --epochs-fine 30
# -> model/crop_model.keras  and  model/classes.json
```

---

## 4. The backend API (`backend/app.py`)

```bash
cd backend
uvicorn app:app --host 0.0.0.0 --port 8000
```

Interactive docs are auto-generated at `http://localhost:8000/docs`.

| Method | Endpoint | Returns |
|---|---|---|
| GET | `/health` | `{"status":"ok","model_loaded":bool}` |
| GET | `/diseases` | the full treatment knowledge base |
| POST | `/predict` | diagnosis JSON (below) |

**`POST /predict`** β€” send `multipart/form-data` with field `file` = the image.

```json
{
  "class_id": "tomato_late",
  "confidence": 0.94,
  "severity": "moderate",
  "diseased_ratio": 0.42,
  "disease": {
    "crop": "Tomato",
    "name": "Late Blight",
    "cause": "An aggressive water-mould (Phytophthora infestans)...",
    "treatment": ["Act today...", "..."],
    "products": ["Chlorothalonil", "Mancozeb", "Metalaxyl-M"]
  }
}
```

**Severity (Β§3.8)** is computed by `estimate_severity()` using colour thresholding: it measures the ratio of chlorotic (yellow), necrotic (dark) and lesion (brown) pixels to total leaf pixels, then maps `<0.20 β†’ early`, `<0.55 β†’ moderate`, else `severe`.

---

## 5. The React frontend (`frontend/src/CropGuard.jsx`)

The four-step flow from Β§3.10.4 β€” **home β†’ preview β†’ loading β†’ result** β€” with camera capture, gallery upload, confidence bar, colour-coded severity, treatment steps and the safety disclaimer.

```bash
cd frontend
npm create vite@latest . -- --template react   # if starting fresh
npm install
echo "VITE_API_URL=http://localhost:8000" > .env
# drop CropGuard.jsx into src/ and render <CropGuard/> from App.jsx
npm run dev
```

---

## 6. The standalone HTML app (`cropguard.html`)

A single self-contained file β€” open it directly on a phone or host it anywhere static (Netlify, GitHub Pages, a CDN). It implements the full farmer UI in English **and Twi**, with:

- camera capture + gallery upload,
- a **real on-device analyser** (canvas pixel analysis of green vs. chlorotic/necrotic/lesion area) so it works with zero backend,
- **optional backend mode** β€” if `localStorage.cropguard_api` is set to your FastAPI URL it sends images to the trained model instead,
- severity colour coding, urgency icons, treatment steps, product suggestions, disease explanation, feedback and share.

To point it at the real model, run in the browser console:
```js
localStorage.setItem('cropguard_api', 'https://your-api-host:8000');
```

> **Note on the on-device fallback:** the heuristic analyser is honest and deterministic (it inspects actual leaf colour and damage area), but it is **not** the trained CNN. For graded, research-quality accuracy, connect the HTML app to the FastAPI backend running your trained model.

---

## 7. Deployment notes (Β§3.11)

- **Backend:** MobileNetV2 is light (~300M multiply-adds/inference) so a CPU-only instance serves several concurrent users; CORS and HTTPS should be enabled in production.
- **Frontend:** ship the React build or `cropguard.html` as static files behind a CDN for fast loads across Ghana.
- **Privacy:** no login, no accounts, no image storage.

---

## 8. Mapping to the report

| Report section | Where it lives in the code |
|---|---|
| Β§3.3 System architecture | client–server split (frontends ↔ `app.py`) |
| Β§3.4 Dataset | `train.py` `image_dataset_from_directory` layout |
| Β§3.5 Preprocessing & augmentation | `standardise()`, `build_augmenter()` |
| Β§3.6 MobileNetV2 + custom head + 2-phase fine-tune | `build_model()`, `main()` |
| Β§3.7 Loss, class weights, LR schedule | `class_weights_from_dir()`, callbacks |
| Β§3.8 Severity classification | `estimate_severity()` (backend) / `analyseOnDevice()` (HTML) |
| Β§3.9 Treatment recommendations | `recommendations.json` |
| Β§3.10 Web app & mobile-first UI | `cropguard.html`, `CropGuard.jsx` |
| Β§3.13 Privacy / ethics | in-memory image handling, no storage |