import gradio as gr
from ultralytics import YOLO
import cv2
import numpy as np
model = YOLO('model.pt')
colors = [
(255, 0, 0),
(0, 255, 0),
(0, 0, 255),
(255, 165, 0),
(128, 0, 128),
(255, 192, 203),
(255, 255, 0),
(255, 255, 255)
]
def predict_image(image):
result = model(image, conf=0.4)
# getting class names and correcting
classes = result[0].names
classes[6] = 'other'
# masks, bounding boxes, confidences, available classes
masks = result[0].masks
boxes = result[0].boxes
if len(boxes) == 0:
return [], [], [], [], classes
confs = list(map(lambda x: float(x.conf[0]), boxes))
avail_classes = list(map(lambda x: int(x.cls[0]), boxes))
masks_maps = list(
map(lambda x: x.data.numpy().transpose(1, 2, 0).reshape(-1, 512), masks))
masks_boundaries = list(map(lambda x: x.xy[0], masks))
return masks_maps, masks_boundaries, avail_classes, confs, classes
def apply_mask(image, mask, color, alpha):
colored_mask = np.zeros_like(image)
colored_mask[mask == 255] = color
return cv2.addWeighted(colored_mask, alpha, image, 1 - alpha, 0)
def generate_output(masks, avail_classes, image):
output = image.copy()
for i in range(len(masks)):
output = apply_mask(output, masks[i]*255, colors[avail_classes[i]], 0.2)
return output
def polygon_area(vertices):
n = len(vertices)
if n < 3:
return 0
area = 0
for i in range(n):
x1, y1 = vertices[i]
x2, y2 = vertices[(i + 1) % n]
area += x1 * y2 - y1 * x2
return abs(area) / 2
def compare(common_classes, masks_boundaries1, masks_boundaries2, avail_classes1, avail_classes2):
change_dict = {}
for common_class in common_classes:
index1 = avail_classes1.index(common_class)
index2 = avail_classes2.index(common_class)
area1 = polygon_area(masks_boundaries1[index1])
area2 = polygon_area(masks_boundaries2[index2])
change_dict[common_class] = (area2 - area1) / area1 * 100
return change_dict
def predict_habitat_with_comparison(img1, img2):
or_w1, or_h1, _ = img1.shape
or_w2, or_h2, _ = img2.shape
img1 = cv2.resize(img1, (512, 512), interpolation = cv2.INTER_LINEAR)
img2 = cv2.resize(img2, (512, 512), interpolation = cv2.INTER_LINEAR)
masks_maps1, masks_boundaries1, avail_classes1, confs1, classes1 = predict_image(img1)
masks_maps2, masks_boundaries2, avail_classes2, confs2, classes2 = predict_image(img2)
if len(masks_maps1) > 0:
output1 = generate_output(masks_maps1, avail_classes1, img1)
output1 = cv2.resize(output1, (or_h1, or_w1), interpolation = cv2.INTER_LINEAR)
data1 = {classes1[avail_classes1[i]]: confs1[i] for i in range(len(confs1))}
html_text1 = '
Detected Areas and Confidences
'
for index, (key, value) in enumerate(data1.items()):
html_text1 += f'- {key}: {round(value*100, 3)}%
'
html_text1 += '
'
if len(masks_maps2) > 0:
output2 = generate_output(masks_maps2, avail_classes2, img2)
output2 = cv2.resize(output2, (or_h2, or_w2), interpolation = cv2.INTER_LINEAR)
data2 = {classes2[avail_classes2[i]]: confs2[i] for i in range(len(confs2))}
html_text2 = 'Detected Areas and Confidences
'
for index, (key, value) in enumerate(data2.items()):
html_text2 += f'- {key}: {round(value*100, 3)}%
'
html_text2 += '
'
if len(masks_maps1) == 0 and len(masks_maps2) == 0:
return img1, "No areas detected!!
", img2, "No areas detected!!
", "Cannot perform comparisons!!
"
elif len(masks_maps1) == 0:
return img1, "No areas detected!!
", output2, html_text2, "Cannot perform comparisons!!
"
elif len(masks_maps2) == 0:
return output1, html_text1, img2, "No areas detected!!
", "Cannot perform comparisons!!
"
common_classes = list(set(avail_classes1).intersection(set(avail_classes2)))
changes = compare(common_classes, masks_boundaries1, masks_boundaries2, avail_classes1, avail_classes2)
common_data = {classes1[common_class]: changes[common_class] for common_class in common_classes}
html_text_common = 'Detected Area Comparisons (in image 2 compared to image 1)
'
for index, (key, value) in enumerate(common_data.items()):
html_text_common += f'- {key}: 0 else "red" if value<0 else "white"};">{round(value, 3)}%
'
html_text_common += '
'
return output1, html_text1, output2, html_text2, html_text_common
def predict_habitat(img):
or_w, or_h, _ = img.shape
img = cv2.resize(img, (512, 512), interpolation = cv2.INTER_LINEAR)
masks_maps, masks_boundaries, avail_classes, confs, classes = predict_image(
img)
if len(masks_maps) == 0:
return img, "No areas detected!!
"
output = generate_output(masks_maps, avail_classes, img)
output = cv2.resize(output, (or_h, or_w), interpolation = cv2.INTER_LINEAR)
data3 = {classes[avail_classes[i]]: confs[i] for i in range(len(confs))}
html_text3 = 'Detected Areas and Confidences
'
for index, (key, value) in enumerate(data3.items()):
html_text3 += f'- {key}: {round(value*100, 3)}%
'
html_text3 += '
'
return output, html_text3
with gr.Blocks() as app:
# Tab for "Habitat Mapping"
with gr.Tab(label="Habitat Mapping"):
gr.Markdown(
"""
## Habitat Segmentation using Ultralytics YOLOv8
* Add image and press submit to try
"""
)
with gr.Row():
img_input_habitat = gr.Image(type="numpy", label="Input Image")
img_output_habitat = gr.Image(type="numpy", label="Predicted Image")
html_output_habitat = gr.HTML(label="Areas and Confidences")
with gr.Row():
submit_btn_habitat = gr.Button("Submit", variant='primary')
gr.ClearButton(img_input_habitat)
submit_btn_habitat.click(
fn=predict_habitat,
inputs=img_input_habitat,
outputs=[img_output_habitat, html_output_habitat]
)
# Tab for "Habitat Mapping with Temporal Changes"
with gr.Tab(label="Habitat Mapping with Area Comparison"):
gr.Markdown(
"""
## Habitat Segmentation using Ultralytics YOLOv8 - Area Comparison
* Add images and press submit to try
* It will show the area difference of image 2 related to image 1 if area is detected by the model in both images
"""
)
with gr.Row():
img_input1 = gr.Image(type="numpy", label="Input Image 1")
img_input2 = gr.Image(type="numpy", label="Input Image 2")
with gr.Row():
with gr.Column():
img_output1 = gr.Image(type="numpy", label="Predicted Image 1")
html_output1 = gr.HTML(
label="Areas and Confidences for Image 1")
with gr.Column():
img_output2 = gr.Image(type="numpy", label="Predicted Image 2")
html_output2 = gr.HTML(
label="Areas and Confidences for Image 2")
with gr.Row():
html_output_common = gr.HTML(
label="Areas and Temporal Change (Common)")
with gr.Row():
submit_btn_mapping = gr.Button("Submit", variant='primary')
gr.ClearButton([img_input1, img_input2])
submit_btn_mapping.click(
fn=predict_habitat_with_comparison,
inputs=[img_input1, img_input2],
outputs=[img_output1, html_output1, img_output2,
html_output2, html_output_common]
)
app.launch()