Update part3.py
Browse files
part3.py
CHANGED
@@ -2,7 +2,6 @@ import numpy as np
|
|
2 |
import cv2
|
3 |
from segment_anything import sam_model_registry, SamPredictor
|
4 |
import matplotlib.pyplot as plt
|
5 |
-
import io
|
6 |
from PIL import Image
|
7 |
|
8 |
class SAMAnalyzer:
|
@@ -33,6 +32,9 @@ class SAMAnalyzer:
|
|
33 |
image = np.stack((image,)*3, axis=-1)
|
34 |
elif len(image.shape) == 3 and image.shape[2] == 4: # RGBA
|
35 |
image = image[:,:,:3]
|
|
|
|
|
|
|
36 |
else:
|
37 |
raise ValueError("Invalid image format")
|
38 |
|
@@ -46,9 +48,9 @@ class SAMAnalyzer:
|
|
46 |
health_analysis = self.analyze_crop_health(veg_index, farmland_mask)
|
47 |
|
48 |
print("Creating visualization...")
|
49 |
-
|
50 |
|
51 |
-
return veg_index, health_analysis,
|
52 |
|
53 |
except Exception as e:
|
54 |
print(f"Error in image processing: {e}")
|
@@ -71,8 +73,11 @@ class SAMAnalyzer:
|
|
71 |
)
|
72 |
|
73 |
# Select best mask
|
74 |
-
|
75 |
-
|
|
|
|
|
|
|
76 |
|
77 |
except Exception as e:
|
78 |
print(f"Error in farmland segmentation: {e}")
|
@@ -141,6 +146,10 @@ class SAMAnalyzer:
|
|
141 |
def create_visualization(self, image, mask, veg_index):
|
142 |
"""Create visualization of results"""
|
143 |
try:
|
|
|
|
|
|
|
|
|
144 |
fig = plt.figure(figsize=(15, 5))
|
145 |
|
146 |
# Original image with mask overlay
|
@@ -152,8 +161,8 @@ class SAMAnalyzer:
|
|
152 |
|
153 |
# Vegetation index heatmap
|
154 |
plt.subplot(132)
|
155 |
-
plt.imshow(veg_index, cmap='RdYlGn')
|
156 |
-
plt.colorbar(label='Vegetation Index')
|
157 |
plt.title('Vegetation Index')
|
158 |
plt.axis('off')
|
159 |
|
@@ -164,47 +173,19 @@ class SAMAnalyzer:
|
|
164 |
health_mask[(veg_index > 0.3) & (veg_index <= 0.6)] = 2 # Moderate
|
165 |
health_mask[veg_index > 0.6] = 3 # High
|
166 |
health_mask = health_mask * mask
|
167 |
-
|
168 |
-
plt.
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
values=[1, 2, 3]
|
173 |
-
)
|
174 |
plt.title('Vegetation Levels')
|
175 |
plt.axis('off')
|
176 |
|
|
|
177 |
plt.tight_layout()
|
178 |
|
179 |
-
|
180 |
-
buf = io.BytesIO()
|
181 |
-
plt.savefig(buf, format='png', bbox_inches='tight', dpi=300)
|
182 |
-
buf.seek(0)
|
183 |
-
plt.close()
|
184 |
-
|
185 |
-
return buf
|
186 |
|
187 |
except Exception as e:
|
188 |
print(f"Error creating visualization: {e}")
|
189 |
-
raise
|
190 |
-
|
191 |
-
def format_analysis_text(self, health_analysis):
|
192 |
-
"""Format health analysis results as text"""
|
193 |
-
try:
|
194 |
-
return f"""
|
195 |
-
🌿 Vegetation Analysis Results:
|
196 |
-
|
197 |
-
📊 Average Vegetation Index: {health_analysis['average_index']:.2f}
|
198 |
-
|
199 |
-
🌱 Vegetation Distribution:
|
200 |
-
• Low Vegetation: {health_analysis['health_distribution']['low_vegetation']*100:.1f}%
|
201 |
-
• Moderate Vegetation: {health_analysis['health_distribution']['moderate_vegetation']*100:.1f}%
|
202 |
-
• High Vegetation: {health_analysis['health_distribution']['high_vegetation']*100:.1f}%
|
203 |
-
|
204 |
-
📋 Overall Health Status: {health_analysis['overall_health']}
|
205 |
-
|
206 |
-
Note: Analysis uses SAM2 for farmland segmentation
|
207 |
-
"""
|
208 |
-
except Exception as e:
|
209 |
-
print(f"Error formatting analysis text: {e}")
|
210 |
-
return "Error generating analysis report"
|
|
|
2 |
import cv2
|
3 |
from segment_anything import sam_model_registry, SamPredictor
|
4 |
import matplotlib.pyplot as plt
|
|
|
5 |
from PIL import Image
|
6 |
|
7 |
class SAMAnalyzer:
|
|
|
32 |
image = np.stack((image,)*3, axis=-1)
|
33 |
elif len(image.shape) == 3 and image.shape[2] == 4: # RGBA
|
34 |
image = image[:,:,:3]
|
35 |
+
# Ensure image is in RGB format
|
36 |
+
if image.shape[2] == 3:
|
37 |
+
image = cv2.cvtColor(cv2.cvtColor(image, cv2.COLOR_RGB2BGR), cv2.COLOR_BGR2RGB)
|
38 |
else:
|
39 |
raise ValueError("Invalid image format")
|
40 |
|
|
|
48 |
health_analysis = self.analyze_crop_health(veg_index, farmland_mask)
|
49 |
|
50 |
print("Creating visualization...")
|
51 |
+
fig = self.create_visualization(image, farmland_mask, veg_index)
|
52 |
|
53 |
+
return veg_index, health_analysis, fig
|
54 |
|
55 |
except Exception as e:
|
56 |
print(f"Error in image processing: {e}")
|
|
|
73 |
)
|
74 |
|
75 |
# Select best mask
|
76 |
+
if len(masks) > 0:
|
77 |
+
best_mask = masks[scores.argmax()]
|
78 |
+
return best_mask
|
79 |
+
else:
|
80 |
+
raise ValueError("No valid masks generated")
|
81 |
|
82 |
except Exception as e:
|
83 |
print(f"Error in farmland segmentation: {e}")
|
|
|
146 |
def create_visualization(self, image, mask, veg_index):
|
147 |
"""Create visualization of results"""
|
148 |
try:
|
149 |
+
# Clear any existing plots
|
150 |
+
plt.close('all')
|
151 |
+
|
152 |
+
# Create figure
|
153 |
fig = plt.figure(figsize=(15, 5))
|
154 |
|
155 |
# Original image with mask overlay
|
|
|
161 |
|
162 |
# Vegetation index heatmap
|
163 |
plt.subplot(132)
|
164 |
+
im = plt.imshow(veg_index, cmap='RdYlGn', vmin=0, vmax=1)
|
165 |
+
plt.colorbar(im, label='Vegetation Index')
|
166 |
plt.title('Vegetation Index')
|
167 |
plt.axis('off')
|
168 |
|
|
|
173 |
health_mask[(veg_index > 0.3) & (veg_index <= 0.6)] = 2 # Moderate
|
174 |
health_mask[veg_index > 0.6] = 3 # High
|
175 |
health_mask = health_mask * mask
|
176 |
+
|
177 |
+
im = plt.imshow(health_mask, cmap='viridis', vmin=1, vmax=3)
|
178 |
+
cbar = plt.colorbar(im, ticks=[1, 2, 3])
|
179 |
+
cbar.set_label('Vegetation Levels')
|
180 |
+
cbar.set_ticklabels(['Low', 'Moderate', 'High'])
|
|
|
|
|
181 |
plt.title('Vegetation Levels')
|
182 |
plt.axis('off')
|
183 |
|
184 |
+
# Adjust layout
|
185 |
plt.tight_layout()
|
186 |
|
187 |
+
return fig
|
|
|
|
|
|
|
|
|
|
|
|
|
188 |
|
189 |
except Exception as e:
|
190 |
print(f"Error creating visualization: {e}")
|
191 |
+
raise
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|