mefet commited on
Commit
293ead4
·
verified ·
1 Parent(s): 85c1180

Create cal.py

Browse files
Files changed (1) hide show
  1. cal.py +86 -0
cal.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # cal.py
2
+
3
+ import torch
4
+ from ultralytics import YOLO
5
+ import cv2
6
+ import numpy as np
7
+ import matplotlib.pyplot as plt
8
+ import streamlit as st
9
+ # Configuration class
10
+ class Config:
11
+
12
+ CLASSES = ['asparagus', 'avocados', 'broccoli', 'cabbage',
13
+ 'celery', 'cucumber', 'green_apples',
14
+ 'green_beans', 'green_capsicum', 'green_grapes', 'kiwifruit',
15
+ 'lettuce', 'limes', 'peas', 'spinach']
16
+
17
+ CALORIES_DICT = {
18
+ 'asparagus': 20,
19
+ 'avocados': 160,
20
+ 'broccoli': 55,
21
+ 'cabbage': 25,
22
+ 'celery': 16,
23
+ 'cucumber': 16,
24
+ 'green_apples': 52,
25
+ 'green_beans': 31,
26
+ 'green_capsicum': 20,
27
+ 'green_grapes': 69,
28
+ 'kiwifruit': 61,
29
+ 'lettuce': 15,
30
+ 'limes': 30,
31
+ 'peas': 81,
32
+ 'spinach': 23
33
+ }
34
+
35
+ # Load the model
36
+ @st.cache_resource
37
+ def load_model():
38
+ model = YOLO('./best.pt')
39
+ return model
40
+
41
+ # Function to make predictions on a single image
42
+ def predict_image(image_path, model, conf_threshold=0.03):
43
+ # Perform inference on the image
44
+ results = model.predict(
45
+ source=image_path,
46
+ imgsz=640,
47
+ conf=conf_threshold
48
+ )
49
+
50
+ # Load the image for visualization
51
+ image = cv2.imread(image_path)
52
+ image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
53
+
54
+ # To store detailed information about detections
55
+ detection_details = []
56
+
57
+ # Iterate over detections
58
+ for result in results[0].boxes.data:
59
+ # Extract bounding box coordinates, confidence score, and class ID
60
+ x1, y1, x2, y2, confidence, class_id = result.cpu().numpy()
61
+
62
+ # Draw the bounding box with top confidence score
63
+ cv2.rectangle(image, (int(x1), int(y1)), (int(x2), int(y2)), color=(0, 255, 0), thickness=2)
64
+ label = f"{Config.CLASSES[int(class_id)]}: {confidence:.2f}"
65
+ cv2.putText(image, label, (int(x1), int(y1) - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), thickness=1)
66
+
67
+ # Save details for printing below
68
+ detection_details.append({
69
+ "class": Config.CLASSES[int(class_id)],
70
+ "top_confidence": confidence,
71
+ "bbox": (x1, y1, x2, y2)
72
+ })
73
+
74
+ return image, detection_details
75
+
76
+ # Function to calculate detected items and their calories
77
+ def calculate_calories(detection_details):
78
+ detected_items = []
79
+
80
+ for det in detection_details:
81
+ item = det["class"]
82
+ calories = Config.CALORIES_DICT[item]
83
+ confidence = det["top_confidence"]
84
+ detected_items.append((item, calories, confidence))
85
+
86
+ return detected_items