Spaces:
Runtime error
Runtime error
yashzambre
commited on
Commit
•
ff071bd
1
Parent(s):
dd58c62
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import subprocess
|
3 |
+
from PIL import Image
|
4 |
+
import pandas as pd
|
5 |
+
import matplotlib.pyplot as plt
|
6 |
+
from itertools import product
|
7 |
+
import numpy as np
|
8 |
+
from sklearn.preprocessing import MinMaxScaler
|
9 |
+
import os
|
10 |
+
import time
|
11 |
+
import pdb
|
12 |
+
|
13 |
+
|
14 |
+
|
15 |
+
|
16 |
+
|
17 |
+
def preprocess_images(input_type):
|
18 |
+
k = 2
|
19 |
+
batch_size = 8
|
20 |
+
img_dir = 'Dataset'
|
21 |
+
data_folder = 'Agrilife_Dataset_Clean'
|
22 |
+
dataset_subfolder_paths = {}
|
23 |
+
dataset_img_files = {}
|
24 |
+
for (_, dirnames, _) in os.walk(img_dir):
|
25 |
+
for dirname in dirnames:
|
26 |
+
if 'Recording' in dirname:
|
27 |
+
dataset_name = os.path.basename(os.path.dirname(os.path.join(img_dir, dirname, 'TIFF'))) # Extract dataset name
|
28 |
+
|
29 |
+
subdir_path = os.path.join(img_dir, dirname, 'TIFF') # Path to the 'TIFF' subdirectory
|
30 |
+
|
31 |
+
master_folders = [folder for folder in os.listdir(subdir_path) if folder.startswith('MASTER')]
|
32 |
+
slave_folders = [folder for folder in os.listdir(subdir_path) if folder.startswith('SLAVE')]
|
33 |
+
|
34 |
+
use_master = bool(master_folders)
|
35 |
+
use_slave = bool(slave_folders)
|
36 |
+
|
37 |
+
# Create subfolders for the current dataset
|
38 |
+
subfolder_paths = create_dataset_folders(dataset_name, use_master or use_slave)
|
39 |
+
|
40 |
+
if subfolder_paths:
|
41 |
+
print("Folders created successfully for dataset:", dataset_name)
|
42 |
+
print("Subfolder paths:")
|
43 |
+
for path in subfolder_paths:
|
44 |
+
print(path)
|
45 |
+
|
46 |
+
# Store the subfolder paths for the current dataset
|
47 |
+
dataset_subfolder_paths[dataset_name] = subfolder_paths
|
48 |
+
|
49 |
+
# Determine the folder to read images from (MASTER or SLAVE)
|
50 |
+
read_folder = master_folders[0] if use_master else slave_folders[0]
|
51 |
+
subdir_path = os.path.join(subdir_path, read_folder)
|
52 |
+
|
53 |
+
# Read images and append to img_files for the current dataset
|
54 |
+
img_files_dataset = []
|
55 |
+
|
56 |
+
if os.path.exists(subdir_path):
|
57 |
+
for _, _, filenames in os.walk(subdir_path):
|
58 |
+
for file in filenames:
|
59 |
+
img_path = os.path.join(subdir_path, file)
|
60 |
+
img_files_dataset.append(img_path)
|
61 |
+
|
62 |
+
# Store the img_files for the current dataset
|
63 |
+
dataset_img_files[dataset_name] = img_files_dataset
|
64 |
+
|
65 |
+
print("Images appended and saved to subfolders successfully!")
|
66 |
+
|
67 |
+
# Process and save images for each dataset
|
68 |
+
for dataset_name, img_files_dataset in dataset_img_files.items():
|
69 |
+
subfolder_paths = dataset_subfolder_paths[dataset_name]
|
70 |
+
visual_subfolder, analysis_subfolder, preprocess_subfolder, segmented_subfolder, stitched_subfolder, dataframe = subfolder_paths
|
71 |
+
|
72 |
+
# Read CSV and filter out images of interest
|
73 |
+
img_indices = np.arange(len(img_files_dataset))
|
74 |
+
|
75 |
+
|
76 |
+
|
77 |
+
############################
|
78 |
+
if input_type == "Run Preprocessing":
|
79 |
+
channel_names = ['Red (660 nm)', 'Green (580 nm)','Red Edge (730 nm)', 'NIR (820 nm)']
|
80 |
+
for img_index in img_indices:
|
81 |
+
img_path = img_files_dataset[img_index]
|
82 |
+
title = os.path.splitext(os.path.basename(img_path))[0]
|
83 |
+
|
84 |
+
im = Image.open(img_path)
|
85 |
+
|
86 |
+
# Divide image into 4 equal parts (separate channels)
|
87 |
+
img_size = im.size[0] // 2
|
88 |
+
img_slices = tile(im, d=img_size)
|
89 |
+
|
90 |
+
# Visualize each slice (optional, remove if not needed)
|
91 |
+
fig, axs = plt.subplots(1, 4)
|
92 |
+
|
93 |
+
i = 0
|
94 |
+
scaler = MinMaxScaler(feature_range=(0, 1))
|
95 |
+
img_stack = np.zeros((img_size, img_size, len(img_slices)))
|
96 |
+
for box_coords in img_slices:
|
97 |
+
|
98 |
+
# Grab image based on box_coords
|
99 |
+
temp_img = np.array(im.crop(box_coords))
|
100 |
+
|
101 |
+
# Normalize and save to composite image
|
102 |
+
scaler.fit(temp_img)
|
103 |
+
temp_img = scaler.transform(temp_img)
|
104 |
+
img_stack[:, :, i] = temp_img
|
105 |
+
i += 1
|
106 |
+
|
107 |
+
# Grab each channel and stack to be R-G-NR-RE
|
108 |
+
red = np.expand_dims(img_stack[:, :, 1], axis=-1)
|
109 |
+
green = np.expand_dims(img_stack[:, :, 0], axis=-1)
|
110 |
+
red_edge = np.expand_dims(img_stack[:, :, 2], axis=-1)
|
111 |
+
NIR = np.expand_dims(img_stack[:, :, -1], axis=-1)
|
112 |
+
composite_img = np.concatenate((green, red_edge, red), axis=-1) * 255
|
113 |
+
|
114 |
+
gray_img, binary = CCA_Preprocess(composite_img, preprocess_subfolder,
|
115 |
+
title.replace('/', '_'), title, k=k)
|
116 |
+
|
117 |
+
preprocessed_img = np.repeat(np.expand_dims(binary, axis=-1), 3, axis=-1) * composite_img
|
118 |
+
# Perform Min-Max normalization
|
119 |
+
# normalized_img = (composite_img - composite_img.min()) / (composite_img.max() - composite_img.min())
|
120 |
+
# normalized_img *= 255
|
121 |
+
# normalized_img = normalized_img.astype(np.uint8)
|
122 |
+
|
123 |
+
# Save image for processing with all channels (for algorithms)
|
124 |
+
save_img = Image.fromarray(np.uint8(preprocessed_img))
|
125 |
+
save_img.save(os.path.join(analysis_subfolder, '{}.png'.format(title.replace('/', '_'))))
|
126 |
+
|
127 |
+
# Redo visualization with mask (find more efficient way for this)
|
128 |
+
for channel in range(0, composite_img.shape[-1]):
|
129 |
+
# Visualize (optional, remove if not needed)
|
130 |
+
axs[channel].imshow(composite_img[:, :, channel] * binary, cmap='BuGn')
|
131 |
+
axs[channel].axis('off')
|
132 |
+
axs[channel].set_title(channel_names[channel], fontsize=10)
|
133 |
+
|
134 |
+
# Save Visual (optional, remove if not needed)
|
135 |
+
plt.suptitle(title)
|
136 |
+
plt.tight_layout()
|
137 |
+
fig.savefig(os.path.join(visual_subfolder, '{}.png'.format(title.replace('/', '_'))))
|
138 |
+
|
139 |
+
# Close figures (optional, remove if not needed)
|
140 |
+
plt.close('all')
|
141 |
+
|
142 |
+
print('Finished processing Image {} of {}'.format(img_index + 1, len(img_indices)))
|
143 |
+
|
144 |
+
|
145 |
+
|
146 |
+
# Define the input and output interfaces using Gradio
|
147 |
+
iface = gr.Interface(
|
148 |
+
fn=image_processing,
|
149 |
+
inputs=[gr.components.Dropdown(["Run Preprocessing", "Run Image Stitching", "Run Image Segmentation", "Run Image Stats"], label="Choose the operation to be performed")],
|
150 |
+
title = "Agrilife Automated Phenotyping",
|
151 |
+
description = "Select processing steps and run the script.")
|
152 |
+
iface.launch()
|