IsmatS commited on
Commit
74c8362
·
1 Parent(s): 1e40ca7
crop_desease_detection.ipynb DELETED
The diff for this file is too large to render. See raw diff
 
crop_desease_detection.py CHANGED
@@ -1,18 +1,3 @@
1
- # -*- coding: utf-8 -*-
2
- """crop_desease_detection.ipynb
3
-
4
- Automatically generated by Colab.
5
-
6
- Original file is located at
7
- https://colab.research.google.com/drive/1PCO8YxMl3tqzsbMVP1iiSylwED-u_VfW
8
- """
9
-
10
-
11
-
12
-
13
-
14
-
15
-
16
  # Complete Pipeline for Tree Disease Detection with PDT Dataset
17
 
18
  # Cell 1: Install required packages
@@ -64,7 +49,7 @@ else:
64
  # Extract the zip file
65
  extract_path = '/content/PDT_dataset_extracted'
66
  os.makedirs(extract_path, exist_ok=True)
67
-
68
  print(f"Extracting {zip_file_path} to {extract_path}")
69
  with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:
70
  zip_ref.extractall(extract_path)
@@ -82,25 +67,25 @@ def explore_dataset_structure(base_path):
82
  'val_path': None,
83
  'test_path': None
84
  }
85
-
86
  for root, dirs, files in os.walk(base_path):
87
  # Look for YOLO_txt directory
88
  if 'YOLO_txt' in root:
89
  dataset_info['yolo_txt_path'] = root
90
  print(f"Found YOLO_txt at: {root}")
91
-
92
  # Check for train/val/test
93
  for split in ['train', 'val', 'test']:
94
  split_path = os.path.join(root, split)
95
  if os.path.exists(split_path):
96
  dataset_info[f'{split}_path'] = split_path
97
  print(f"Found {split} at: {split_path}")
98
-
99
  # Look for VOC_xml directory
100
  if 'VOC_xml' in root:
101
  dataset_info['voc_xml_path'] = root
102
  print(f"Found VOC_xml at: {root}")
103
-
104
  return dataset_info
105
 
106
  dataset_info = explore_dataset_structure('/content/PDT_dataset_extracted')
@@ -109,57 +94,57 @@ dataset_info = explore_dataset_structure('/content/PDT_dataset_extracted')
109
  def setup_yolo_dataset(dataset_info, output_dir='/content/PDT_yolo'):
110
  """Setup YOLO dataset from the extracted PDT dataset"""
111
  print(f"\nSetting up YOLO dataset to {output_dir}")
112
-
113
  # Clean output directory
114
  if os.path.exists(output_dir):
115
  shutil.rmtree(output_dir)
116
  os.makedirs(output_dir, exist_ok=True)
117
-
118
  # Create directory structure
119
  for split in ['train', 'val', 'test']:
120
  os.makedirs(os.path.join(output_dir, 'images', split), exist_ok=True)
121
  os.makedirs(os.path.join(output_dir, 'labels', split), exist_ok=True)
122
-
123
  total_copied = 0
124
-
125
  # Process each split
126
  for split in ['train', 'val', 'test']:
127
  split_path = dataset_info[f'{split}_path']
128
-
129
  if not split_path or not os.path.exists(split_path):
130
  print(f"Warning: {split} split not found")
131
  continue
132
-
133
  print(f"\nProcessing {split} from: {split_path}")
134
-
135
  # Find images and labels directories
136
  img_dir = os.path.join(split_path, 'images')
137
  lbl_dir = os.path.join(split_path, 'labels')
138
-
139
  if not os.path.exists(img_dir) or not os.path.exists(lbl_dir):
140
  print(f"Warning: Could not find images or labels for {split}")
141
  continue
142
-
143
  # Copy images and labels
144
  img_files = [f for f in os.listdir(img_dir) if f.endswith(('.jpg', '.jpeg', '.png'))]
145
  print(f"Found {len(img_files)} images in {split}")
146
-
147
  for img_file in img_files:
148
  # Copy image
149
  src_img = os.path.join(img_dir, img_file)
150
  dst_img = os.path.join(output_dir, 'images', split, img_file)
151
  shutil.copy2(src_img, dst_img)
152
-
153
  # Copy corresponding label
154
  base_name = os.path.splitext(img_file)[0]
155
  txt_file = base_name + '.txt'
156
  src_txt = os.path.join(lbl_dir, txt_file)
157
  dst_txt = os.path.join(output_dir, 'labels', split, txt_file)
158
-
159
  if os.path.exists(src_txt):
160
  shutil.copy2(src_txt, dst_txt)
161
  total_copied += 1
162
-
163
  # Create data.yaml
164
  data_yaml_content = f"""# PDT dataset configuration
165
  path: {os.path.abspath(output_dir)}
@@ -172,14 +157,14 @@ names:
172
  0: unhealthy
173
  nc: 1
174
  """
175
-
176
  yaml_path = os.path.join(output_dir, 'data.yaml')
177
  with open(yaml_path, 'w') as f:
178
  f.write(data_yaml_content)
179
-
180
  print(f"\nDataset setup completed!")
181
  print(f"Total images copied: {total_copied}")
182
-
183
  # Verify the dataset
184
  for split in ['train', 'val', 'test']:
185
  img_dir = os.path.join(output_dir, 'images', split)
@@ -188,7 +173,7 @@ nc: 1
188
  img_count = len([f for f in os.listdir(img_dir) if f.endswith(('.jpg', '.jpeg', '.png'))])
189
  lbl_count = len([f for f in os.listdir(lbl_dir) if f.endswith('.txt')])
190
  print(f"{split}: {img_count} images, {lbl_count} labels")
191
-
192
  return yaml_path
193
 
194
  # Setup the dataset
@@ -252,10 +237,10 @@ axes = axes.ravel()
252
 
253
  for i, img_name in enumerate(val_images[:6]):
254
  img_path = os.path.join(val_img_dir, img_name)
255
-
256
  # Run inference
257
  results = model(img_path, conf=0.25)
258
-
259
  # Plot results
260
  img_with_boxes = results[0].plot()
261
  axes[i].imshow(cv2.cvtColor(img_with_boxes, cv2.COLOR_BGR2RGB))
@@ -273,7 +258,7 @@ plt.show()
273
  def detect_tree_disease(image_path, conf_threshold=0.25):
274
  """Detect unhealthy trees in an image"""
275
  results = model(image_path, conf=conf_threshold)
276
-
277
  detections = []
278
  for result in results:
279
  boxes = result.boxes
@@ -285,7 +270,7 @@ def detect_tree_disease(image_path, conf_threshold=0.25):
285
  'class': 'unhealthy'
286
  }
287
  detections.append(detection)
288
-
289
  # Visualize
290
  img_with_boxes = results[0].plot()
291
  plt.figure(figsize=(12, 8))
@@ -293,7 +278,7 @@ def detect_tree_disease(image_path, conf_threshold=0.25):
293
  plt.axis('off')
294
  plt.title(f'Detected {len(detections)} unhealthy tree(s)')
295
  plt.show()
296
-
297
  return detections
298
 
299
  # Cell 10: Save the model
@@ -307,19 +292,19 @@ from google.colab import drive
307
 
308
  try:
309
  drive.mount('/content/drive')
310
-
311
  save_dir = '/content/drive/MyDrive/tree_disease_detection'
312
  os.makedirs(save_dir, exist_ok=True)
313
-
314
  # Copy files
315
  shutil.copy(best_model_path, os.path.join(save_dir, 'best_model.pt'))
316
  shutil.copy(final_model_path, os.path.join(save_dir, 'tree_disease_detector.pt'))
317
-
318
  # Copy training results
319
  results_png = 'runs/train/yolov8s_pdt/results.png'
320
  if os.path.exists(results_png):
321
  shutil.copy(results_png, os.path.join(save_dir, 'training_results.png'))
322
-
323
  print(f"Results saved to Google Drive: {save_dir}")
324
  except:
325
  print("Google Drive not mounted. Results saved locally.")
@@ -333,269 +318,4 @@ print("The model is ready for tree disease detection!")
333
 
334
  # Test with your own image
335
  print("\nTo test with your own image:")
336
- print("detections = detect_tree_disease('path/to/your/image.jpg')")
337
-
338
-
339
-
340
-
341
-
342
-
343
-
344
-
345
-
346
- # Cell 1: Install Hugging Face Hub
347
- !pip install huggingface_hub
348
-
349
- # Cell 2: Login to Hugging Face
350
- from huggingface_hub import login, HfApi, create_repo
351
- import os
352
- import shutil
353
-
354
- # Login to Hugging Face (you'll need your token)
355
- # Get your token from: https://huggingface.co/settings/tokens
356
- login()
357
-
358
- # Cell 3: Prepare model files for upload
359
- # Create a directory for model files
360
- model_dir = "pdt_tree_disease_model"
361
- os.makedirs(model_dir, exist_ok=True)
362
-
363
- # Copy the trained model
364
- best_model_path = 'runs/train/yolov8s_pdt/weights/best.pt'
365
- if os.path.exists(best_model_path):
366
- shutil.copy(best_model_path, os.path.join(model_dir, "best.pt"))
367
-
368
- # Copy the final saved model
369
- if os.path.exists('tree_disease_detector.pt'):
370
- shutil.copy('tree_disease_detector.pt', os.path.join(model_dir, "tree_disease_detector.pt"))
371
-
372
- # Copy training results
373
- results_path = 'runs/train/yolov8s_pdt/results.png'
374
- if os.path.exists(results_path):
375
- shutil.copy(results_path, os.path.join(model_dir, "training_results.png"))
376
-
377
- # Copy confusion matrix if exists
378
- confusion_matrix_path = 'runs/train/yolov8s_pdt/confusion_matrix.png'
379
- if os.path.exists(confusion_matrix_path):
380
- shutil.copy(confusion_matrix_path, os.path.join(model_dir, "confusion_matrix.png"))
381
-
382
- # Copy other training plots
383
- for plot_file in ['F1_curve.png', 'P_curve.png', 'R_curve.png', 'PR_curve.png']:
384
- plot_path = f'runs/train/yolov8s_pdt/{plot_file}'
385
- if os.path.exists(plot_path):
386
- shutil.copy(plot_path, os.path.join(model_dir, plot_file))
387
-
388
- # Cell 4: Create model card (README.md)
389
- model_card = """---
390
- tags:
391
- - object-detection
392
- - yolov8
393
- - tree-disease-detection
394
- - pdt-dataset
395
- library_name: ultralytics
396
- datasets:
397
- - qwer0213/PDT_dataset
398
- metrics:
399
- - mAP50
400
- - mAP50-95
401
- ---
402
-
403
- # YOLOv8 Tree Disease Detection Model
404
-
405
- This model is trained on the PDT (Pests and Diseases Tree) dataset for detecting unhealthy trees using YOLOv8.
406
-
407
- ## Model Description
408
-
409
- - **Architecture**: YOLOv8s
410
- - **Task**: Object Detection (Tree Disease Detection)
411
- - **Classes**: 1 (unhealthy)
412
- - **Input Size**: 640x640
413
- - **Framework**: Ultralytics YOLOv8
414
-
415
- ## Training Details
416
-
417
- - **Dataset**: PDT (Pests and Diseases Tree) dataset
418
- - **Training Images**: 4,536
419
- - **Validation Images**: 567
420
- - **Test Images**: 567
421
- - **Epochs**: 50
422
- - **Batch Size**: 16
423
- - **Optimizer**: SGD
424
- - **Learning Rate**: 0.01
425
-
426
- ## Performance Metrics
427
-
428
- | Metric | Value |
429
- |--------|-------|
430
- | mAP50 | 0.xxx |
431
- | mAP50-95 | 0.xxx |
432
- | Precision | 0.xxx |
433
- | Recall | 0.xxx |
434
-
435
- ## Usage
436
-
437
- ```python
438
- from ultralytics import YOLO
439
-
440
- # Load model
441
- model = YOLO('tree_disease_detector.pt')
442
-
443
- # Run inference
444
- results = model('path/to/image.jpg')
445
-
446
- # Process results
447
- for result in results:
448
- boxes = result.boxes
449
- if boxes is not None:
450
- for box in boxes:
451
- confidence = box.conf[0]
452
- bbox = box.xyxy[0].tolist()
453
- print(f"Unhealthy tree detected with confidence: {confidence}")
454
- Dataset
455
- This model was trained on the PDT dataset, which contains high-resolution UAV images of trees with pest and disease annotations.
456
- Citation
457
- bibtex@dataset{pdt_dataset,
458
- title={PDT: UAV Pests and Diseases Tree Dataset},
459
- author={Zhou et al.},
460
- year={2024},
461
- publisher={HuggingFace}
462
- }
463
- License
464
- MIT License
465
- """
466
- Fill in the actual metrics
467
- if 'metrics' in globals() and metrics is not None:
468
- model_card = model_card.replace('0.xxx', f'{metrics.box.map50:.3f}')
469
- model_card = model_card.replace('0.xxx', f'{metrics.box.map:.3f}')
470
- model_card = model_card.replace('0.xxx', f'{metrics.box.p.mean():.3f}')
471
- model_card = model_card.replace('0.xxx', f'{metrics.box.r.mean():.3f}')
472
- Save model card
473
- with open(os.path.join(model_dir, "README.md"), "w") as f:
474
- f.write(model_card)
475
- Cell 5: Create config file
476
- config_content = """# YOLOv8 Tree Disease Detection Configuration
477
- model_type: yolov8s
478
- task: detect
479
- nc: 1 # number of classes
480
- names: ['unhealthy'] # class names
481
- Input
482
- imgsz: 640
483
- Inference settings
484
- conf: 0.25 # confidence threshold
485
- iou: 0.45 # IoU threshold for NMS
486
- """
487
- with open(os.path.join(model_dir, "config.yaml"), "w") as f:
488
- f.write(config_content)
489
- Cell 6: Push to Hugging Face Hub
490
- from huggingface_hub import HfApi
491
- Initialize API
492
- api = HfApi()
493
- Create repository (replace 'your-username' with your HuggingFace username)
494
- repo_id = "your-username/yolov8-tree-disease-detection" # Change this!
495
- Create the repository
496
- try:
497
- create_repo(
498
- repo_id=repo_id,
499
- repo_type="model",
500
- exist_ok=True
501
- )
502
- print(f"Repository created: https://huggingface.co/{repo_id}")
503
- except Exception as e:
504
- print(f"Repository might already exist or error: {e}")
505
- Upload all files in the model directory
506
- api.upload_folder(
507
- folder_path=model_dir,
508
- repo_id=repo_id,
509
- repo_type="model",
510
- )
511
- print(f"Model uploaded successfully to: https://huggingface.co/{repo_id}")
512
- Cell 7: Create a simple inference script for users
513
- inference_script = """# Tree Disease Detection Inference
514
- from ultralytics import YOLO
515
- import cv2
516
- import matplotlib.pyplot as plt
517
- Download and load model from Hugging Face
518
- model = YOLO('https://huggingface.co/{}/resolve/main/tree_disease_detector.pt')
519
- def detect_tree_disease(image_path):
520
- # Run inference
521
- results = model(image_path, conf=0.25)
522
- # Process results
523
- detections = []
524
- for result in results:
525
- boxes = result.boxes
526
- if boxes is not None:
527
- for box in boxes:
528
- detection = {
529
- 'confidence': float(box.conf[0]),
530
- 'bbox': box.xyxy[0].tolist(),
531
- 'class': 'unhealthy'
532
- }
533
- detections.append(detection)
534
-
535
- # Visualize
536
- annotated_img = results[0].plot()
537
- plt.figure(figsize=(12, 8))
538
- plt.imshow(cv2.cvtColor(annotated_img, cv2.COLOR_BGR2RGB))
539
- plt.axis('off')
540
- plt.title(f'Detected {len(detections)} unhealthy tree(s)')
541
- plt.show()
542
-
543
- return detections
544
- Example usage
545
- if name == "main":
546
- detections = detect_tree_disease('path/to/your/image.jpg')
547
- print(f"Found {len(detections)} unhealthy trees")
548
- """.format(repo_id)
549
- with open(os.path.join(model_dir, "inference.py"), "w") as f:
550
- f.write(inference_script)
551
- Upload the inference script
552
- api.upload_file(
553
- path_or_fileobj=os.path.join(model_dir, "inference.py"),
554
- path_in_repo="inference.py",
555
- repo_id=repo_id,
556
- repo_type="model",
557
- )
558
- Cell 8: Create requirements.txt
559
- requirements = """ultralytics>=8.0.0
560
- torch>=2.0.0
561
- opencv-python>=4.8.0
562
- matplotlib>=3.7.0
563
- pillow>=10.0.0
564
- """
565
- with open(os.path.join(model_dir, "requirements.txt"), "w") as f:
566
- f.write(requirements)
567
- Upload requirements
568
- api.upload_file(
569
- path_or_fileobj=os.path.join(model_dir, "requirements.txt"),
570
- path_in_repo="requirements.txt",
571
- repo_id=repo_id,
572
- repo_type="model",
573
- )
574
- print("\nModel successfully uploaded to Hugging Face!")
575
- print(f"View your model at: https://huggingface.co/{repo_id}")
576
- print("\nTo use your model:")
577
- print(f"model = YOLO('https://huggingface.co/{repo_id}/resolve/main/tree_disease_detector.pt')")
578
-
579
- ## Steps to upload your model:
580
-
581
- 1. **Get a Hugging Face token**:
582
- - Go to https://huggingface.co/settings/tokens
583
- - Create a new token with write permissions
584
- - Copy the token
585
-
586
- 2. **Replace placeholder values**:
587
- - Change `your-username` to your actual Hugging Face username
588
- - Update the metrics in the model card with actual values
589
-
590
- 3. **Run the cells** in order
591
-
592
- ## After uploading, others can use your model like this:
593
-
594
- ```python
595
- from ultralytics import YOLO
596
-
597
- # Load model directly from Hugging Face
598
- model = YOLO('https://huggingface.co/your-username/yolov8-tree-disease-detection/resolve/main/tree_disease_detector.pt')
599
-
600
- # Run inference
601
- results = model('image.jpg')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # Complete Pipeline for Tree Disease Detection with PDT Dataset
2
 
3
  # Cell 1: Install required packages
 
49
  # Extract the zip file
50
  extract_path = '/content/PDT_dataset_extracted'
51
  os.makedirs(extract_path, exist_ok=True)
52
+
53
  print(f"Extracting {zip_file_path} to {extract_path}")
54
  with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:
55
  zip_ref.extractall(extract_path)
 
67
  'val_path': None,
68
  'test_path': None
69
  }
70
+
71
  for root, dirs, files in os.walk(base_path):
72
  # Look for YOLO_txt directory
73
  if 'YOLO_txt' in root:
74
  dataset_info['yolo_txt_path'] = root
75
  print(f"Found YOLO_txt at: {root}")
76
+
77
  # Check for train/val/test
78
  for split in ['train', 'val', 'test']:
79
  split_path = os.path.join(root, split)
80
  if os.path.exists(split_path):
81
  dataset_info[f'{split}_path'] = split_path
82
  print(f"Found {split} at: {split_path}")
83
+
84
  # Look for VOC_xml directory
85
  if 'VOC_xml' in root:
86
  dataset_info['voc_xml_path'] = root
87
  print(f"Found VOC_xml at: {root}")
88
+
89
  return dataset_info
90
 
91
  dataset_info = explore_dataset_structure('/content/PDT_dataset_extracted')
 
94
  def setup_yolo_dataset(dataset_info, output_dir='/content/PDT_yolo'):
95
  """Setup YOLO dataset from the extracted PDT dataset"""
96
  print(f"\nSetting up YOLO dataset to {output_dir}")
97
+
98
  # Clean output directory
99
  if os.path.exists(output_dir):
100
  shutil.rmtree(output_dir)
101
  os.makedirs(output_dir, exist_ok=True)
102
+
103
  # Create directory structure
104
  for split in ['train', 'val', 'test']:
105
  os.makedirs(os.path.join(output_dir, 'images', split), exist_ok=True)
106
  os.makedirs(os.path.join(output_dir, 'labels', split), exist_ok=True)
107
+
108
  total_copied = 0
109
+
110
  # Process each split
111
  for split in ['train', 'val', 'test']:
112
  split_path = dataset_info[f'{split}_path']
113
+
114
  if not split_path or not os.path.exists(split_path):
115
  print(f"Warning: {split} split not found")
116
  continue
117
+
118
  print(f"\nProcessing {split} from: {split_path}")
119
+
120
  # Find images and labels directories
121
  img_dir = os.path.join(split_path, 'images')
122
  lbl_dir = os.path.join(split_path, 'labels')
123
+
124
  if not os.path.exists(img_dir) or not os.path.exists(lbl_dir):
125
  print(f"Warning: Could not find images or labels for {split}")
126
  continue
127
+
128
  # Copy images and labels
129
  img_files = [f for f in os.listdir(img_dir) if f.endswith(('.jpg', '.jpeg', '.png'))]
130
  print(f"Found {len(img_files)} images in {split}")
131
+
132
  for img_file in img_files:
133
  # Copy image
134
  src_img = os.path.join(img_dir, img_file)
135
  dst_img = os.path.join(output_dir, 'images', split, img_file)
136
  shutil.copy2(src_img, dst_img)
137
+
138
  # Copy corresponding label
139
  base_name = os.path.splitext(img_file)[0]
140
  txt_file = base_name + '.txt'
141
  src_txt = os.path.join(lbl_dir, txt_file)
142
  dst_txt = os.path.join(output_dir, 'labels', split, txt_file)
143
+
144
  if os.path.exists(src_txt):
145
  shutil.copy2(src_txt, dst_txt)
146
  total_copied += 1
147
+
148
  # Create data.yaml
149
  data_yaml_content = f"""# PDT dataset configuration
150
  path: {os.path.abspath(output_dir)}
 
157
  0: unhealthy
158
  nc: 1
159
  """
160
+
161
  yaml_path = os.path.join(output_dir, 'data.yaml')
162
  with open(yaml_path, 'w') as f:
163
  f.write(data_yaml_content)
164
+
165
  print(f"\nDataset setup completed!")
166
  print(f"Total images copied: {total_copied}")
167
+
168
  # Verify the dataset
169
  for split in ['train', 'val', 'test']:
170
  img_dir = os.path.join(output_dir, 'images', split)
 
173
  img_count = len([f for f in os.listdir(img_dir) if f.endswith(('.jpg', '.jpeg', '.png'))])
174
  lbl_count = len([f for f in os.listdir(lbl_dir) if f.endswith('.txt')])
175
  print(f"{split}: {img_count} images, {lbl_count} labels")
176
+
177
  return yaml_path
178
 
179
  # Setup the dataset
 
237
 
238
  for i, img_name in enumerate(val_images[:6]):
239
  img_path = os.path.join(val_img_dir, img_name)
240
+
241
  # Run inference
242
  results = model(img_path, conf=0.25)
243
+
244
  # Plot results
245
  img_with_boxes = results[0].plot()
246
  axes[i].imshow(cv2.cvtColor(img_with_boxes, cv2.COLOR_BGR2RGB))
 
258
  def detect_tree_disease(image_path, conf_threshold=0.25):
259
  """Detect unhealthy trees in an image"""
260
  results = model(image_path, conf=conf_threshold)
261
+
262
  detections = []
263
  for result in results:
264
  boxes = result.boxes
 
270
  'class': 'unhealthy'
271
  }
272
  detections.append(detection)
273
+
274
  # Visualize
275
  img_with_boxes = results[0].plot()
276
  plt.figure(figsize=(12, 8))
 
278
  plt.axis('off')
279
  plt.title(f'Detected {len(detections)} unhealthy tree(s)')
280
  plt.show()
281
+
282
  return detections
283
 
284
  # Cell 10: Save the model
 
292
 
293
  try:
294
  drive.mount('/content/drive')
295
+
296
  save_dir = '/content/drive/MyDrive/tree_disease_detection'
297
  os.makedirs(save_dir, exist_ok=True)
298
+
299
  # Copy files
300
  shutil.copy(best_model_path, os.path.join(save_dir, 'best_model.pt'))
301
  shutil.copy(final_model_path, os.path.join(save_dir, 'tree_disease_detector.pt'))
302
+
303
  # Copy training results
304
  results_png = 'runs/train/yolov8s_pdt/results.png'
305
  if os.path.exists(results_png):
306
  shutil.copy(results_png, os.path.join(save_dir, 'training_results.png'))
307
+
308
  print(f"Results saved to Google Drive: {save_dir}")
309
  except:
310
  print("Google Drive not mounted. Results saved locally.")
 
318
 
319
  # Test with your own image
320
  print("\nTo test with your own image:")
321
+ print("detections = detect_tree_disease('path/to/your/image.jpg')")