Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -17,11 +17,10 @@ from model.CBAM.reunet_cbam import reunet_cbam
|
|
17 |
from model.transform import transforms
|
18 |
from model.unet import UNET
|
19 |
from Utils.area import pixel_to_sqft, process_and_overlay_image
|
20 |
-
from split_merge import split, merge
|
21 |
from Utils.convert import read_pansharpened_rgb
|
22 |
|
23 |
# Define base directory for Hugging Face Spaces
|
24 |
-
BASE_DIR = "/
|
25 |
|
26 |
# Define subdirectories
|
27 |
UPLOAD_DIR = os.path.join(BASE_DIR, "uploaded_images")
|
@@ -49,6 +48,76 @@ def predict(image):
|
|
49 |
output = model(image.unsqueeze(0))
|
50 |
return output.squeeze().cpu().numpy()
|
51 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
52 |
def log_image_details(image_id, image_filename, mask_filename):
|
53 |
file_exists = os.path.exists(CSV_LOG_PATH)
|
54 |
|
@@ -122,55 +191,30 @@ def upload_page():
|
|
122 |
# Store the full path of the converted image
|
123 |
st.session_state.filename = converted_filename
|
124 |
|
125 |
-
#
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
patch_tr_img = transforms(patch_img)
|
141 |
-
prediction = predict(patch_tr_img)
|
142 |
-
mask = (prediction > 0.5).astype(np.uint8) * 255
|
143 |
-
mask_filename = f"mask_{patch_filename}"
|
144 |
-
mask_filepath = os.path.join(PRED_PATCHES_DIR, mask_filename)
|
145 |
-
Image.fromarray(mask).save(mask_filepath)
|
146 |
-
|
147 |
-
# Merge predicted patches
|
148 |
-
merged_mask_filename = f"mask_{timestamp}.png"
|
149 |
-
merged_mask_path = os.path.join(MASK_DIR, merged_mask_filename)
|
150 |
-
merge(PRED_PATCHES_DIR, merged_mask_path, img_array.shape)
|
151 |
-
|
152 |
-
# Save merged mask
|
153 |
-
st.session_state.mask_filename = merged_mask_filename
|
154 |
-
|
155 |
-
# Clean up temporary patch files
|
156 |
-
st.info('Cleaning up temporary files...')
|
157 |
-
shutil.rmtree(PATCHES_DIR)
|
158 |
-
shutil.rmtree(PRED_PATCHES_DIR)
|
159 |
-
os.makedirs(PATCHES_DIR) # Recreate empty folders
|
160 |
-
os.makedirs(PRED_PATCHES_DIR)
|
161 |
-
st.success('Temporary files cleaned up')
|
162 |
-
else:
|
163 |
-
# Predict on whole image
|
164 |
-
st.session_state.tr_img = transforms(img)
|
165 |
-
prediction = predict(st.session_state.tr_img)
|
166 |
-
mask = (prediction > 0.5).astype(np.uint8) * 255
|
167 |
-
mask_filename = f"mask_{timestamp}.png"
|
168 |
-
mask_filepath = os.path.join(MASK_DIR, mask_filename)
|
169 |
-
Image.fromarray(mask).save(mask_filepath)
|
170 |
-
st.session_state.mask_filename = mask_filename
|
171 |
|
172 |
st.session_state.file_uploaded = True
|
173 |
|
|
|
|
|
|
|
|
|
|
|
|
|
174 |
except Exception as e:
|
175 |
st.error(f"An error occurred: {str(e)}")
|
176 |
st.error("Please check the logs for more details.")
|
@@ -237,8 +281,6 @@ def result_page():
|
|
237 |
st.error("Image or mask file not found for overlay.")
|
238 |
|
239 |
if st.button('Back to Upload'):
|
240 |
-
shutil.rmtree(PATCHES_DIR)
|
241 |
-
shutil.rmtree(PRED_PATCHES_DIR)
|
242 |
st.session_state.page = 'upload'
|
243 |
st.session_state.file_uploaded = False
|
244 |
st.session_state.filename = None
|
|
|
17 |
from model.transform import transforms
|
18 |
from model.unet import UNET
|
19 |
from Utils.area import pixel_to_sqft, process_and_overlay_image
|
|
|
20 |
from Utils.convert import read_pansharpened_rgb
|
21 |
|
22 |
# Define base directory for Hugging Face Spaces
|
23 |
+
BASE_DIR = "/Data"
|
24 |
|
25 |
# Define subdirectories
|
26 |
UPLOAD_DIR = os.path.join(BASE_DIR, "uploaded_images")
|
|
|
48 |
output = model(image.unsqueeze(0))
|
49 |
return output.squeeze().cpu().numpy()
|
50 |
|
51 |
+
def split_image(image, patch_size=512):
|
52 |
+
h, w, _ = image.shape
|
53 |
+
patches = []
|
54 |
+
for y in range(0, h, patch_size):
|
55 |
+
for x in range(0, w, patch_size):
|
56 |
+
patch = image[y:min(y+patch_size, h), x:min(x+patch_size, w)]
|
57 |
+
patches.append((f"patch_{y}_{x}.png", patch))
|
58 |
+
return patches
|
59 |
+
|
60 |
+
def merge(patch_folder, dest_image='out.png', image_shape=None):
|
61 |
+
merged = np.zeros(image_shape[:-1] + (3,), dtype=np.uint8)
|
62 |
+
for filename in os.listdir(patch_folder):
|
63 |
+
if filename.endswith(".png"):
|
64 |
+
patch_path = os.path.join(patch_folder, filename)
|
65 |
+
patch = cv2.imread(patch_path)
|
66 |
+
patch_height, patch_width, _ = patch.shape
|
67 |
+
|
68 |
+
# Extract patch coordinates from filename
|
69 |
+
parts = filename.split("_")
|
70 |
+
x, y = None, None
|
71 |
+
for part in parts:
|
72 |
+
if part.endswith(".png"):
|
73 |
+
x = int(part.split(".")[0])
|
74 |
+
elif part.isdigit():
|
75 |
+
y = int(part)
|
76 |
+
if x is None or y is None:
|
77 |
+
raise ValueError(f"Invalid filename: {filename}")
|
78 |
+
|
79 |
+
# Check if patch fits within image boundaries
|
80 |
+
if x + patch_width > image_shape[1] or y + patch_height > image_shape[0]:
|
81 |
+
# Adjust patch position to fit within image boundaries
|
82 |
+
if x + patch_width > image_shape[1]:
|
83 |
+
x = image_shape[1] - patch_width
|
84 |
+
if y + patch_height > image_shape[0]:
|
85 |
+
y = image_shape[0] - patch_height
|
86 |
+
|
87 |
+
# Merge patch into the main image
|
88 |
+
merged[y:y+patch_height, x:x+patch_width, :] = patch
|
89 |
+
|
90 |
+
cv2.imwrite(dest_image, merged)
|
91 |
+
return merged
|
92 |
+
|
93 |
+
def process_large_image(model, image_path, patch_size=512):
|
94 |
+
# Read the image
|
95 |
+
img = cv2.imread(image_path)
|
96 |
+
if img is None:
|
97 |
+
raise ValueError(f"Failed to read image from {image_path}")
|
98 |
+
|
99 |
+
h, w, _ = img.shape
|
100 |
+
st.write(f"Processing image of size {w}x{h}")
|
101 |
+
|
102 |
+
# Split the image into patches
|
103 |
+
patches = split_image(img, patch_size)
|
104 |
+
|
105 |
+
# Process each patch
|
106 |
+
for filename, patch in patches:
|
107 |
+
patch_pil = Image.fromarray(cv2.cvtColor(patch, cv2.COLOR_BGR2RGB))
|
108 |
+
patch_transformed = transforms(patch_pil)
|
109 |
+
prediction = predict(patch_transformed)
|
110 |
+
mask = (prediction > 0.5).astype(np.uint8) * 255
|
111 |
+
|
112 |
+
# Save the mask patch
|
113 |
+
mask_filepath = os.path.join(PRED_PATCHES_DIR, filename)
|
114 |
+
cv2.imwrite(mask_filepath, mask)
|
115 |
+
|
116 |
+
# Merge the predicted patches
|
117 |
+
merged_mask = merge(PRED_PATCHES_DIR, dest_image='merged_mask.png', image_shape=img.shape)
|
118 |
+
|
119 |
+
return merged_mask
|
120 |
+
|
121 |
def log_image_details(image_id, image_filename, mask_filename):
|
122 |
file_exists = os.path.exists(CSV_LOG_PATH)
|
123 |
|
|
|
191 |
# Store the full path of the converted image
|
192 |
st.session_state.filename = converted_filename
|
193 |
|
194 |
+
# Process the image
|
195 |
+
st.write("Processing image...")
|
196 |
+
with st.spinner('Analyzing...'):
|
197 |
+
full_mask = process_large_image(model, converted_filepath)
|
198 |
+
|
199 |
+
# Save the full mask
|
200 |
+
mask_filename = f"mask_{timestamp}.png"
|
201 |
+
mask_filepath = os.path.join(MASK_DIR, mask_filename)
|
202 |
+
cv2.imwrite(mask_filepath, full_mask)
|
203 |
+
st.session_state.mask_filename = mask_filename
|
204 |
+
|
205 |
+
st.success("Image processed successfully")
|
206 |
+
|
207 |
+
# Log image details
|
208 |
+
log_image_details(timestamp, converted_filename, mask_filename)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
209 |
|
210 |
st.session_state.file_uploaded = True
|
211 |
|
212 |
+
# Clean up temporary patch files
|
213 |
+
st.info('Cleaning up temporary files...')
|
214 |
+
for file in os.listdir(PRED_PATCHES_DIR):
|
215 |
+
os.remove(os.path.join(PRED_PATCHES_DIR, file))
|
216 |
+
st.success('Temporary files cleaned up')
|
217 |
+
|
218 |
except Exception as e:
|
219 |
st.error(f"An error occurred: {str(e)}")
|
220 |
st.error("Please check the logs for more details.")
|
|
|
281 |
st.error("Image or mask file not found for overlay.")
|
282 |
|
283 |
if st.button('Back to Upload'):
|
|
|
|
|
284 |
st.session_state.page = 'upload'
|
285 |
st.session_state.file_uploaded = False
|
286 |
st.session_state.filename = None
|