Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import roboflow
|
| 3 |
+
import os
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import numpy as np
|
| 6 |
+
import matplotlib.pyplot as plt
|
| 7 |
+
import re
|
| 8 |
+
import io
|
| 9 |
+
from shapely.geometry import Polygon
|
| 10 |
+
from PIL import Image
|
| 11 |
+
|
| 12 |
+
# 🔥 Inicializar o modelo do Roboflow
|
| 13 |
+
API_KEY = "SUA_API_KEY_AQUI" # ⚠️ Substitua pela sua API Key do Roboflow
|
| 14 |
+
rf = roboflow.Roboflow(api_key=API_KEY)
|
| 15 |
+
project = rf.workspace().project("pre-eclampsia-vhaot")
|
| 16 |
+
model = project.version("4").model
|
| 17 |
+
|
| 18 |
+
# Configurar confiança e sobreposição
|
| 19 |
+
model.confidence = 80
|
| 20 |
+
model.overlap = 25
|
| 21 |
+
|
| 22 |
+
# 📌 Função para calcular a área do polígono segmentado
|
| 23 |
+
def calculate_polygon_area(points):
|
| 24 |
+
polygon = Polygon([(p['x'], p['y']) for p in points])
|
| 25 |
+
return polygon.area
|
| 26 |
+
|
| 27 |
+
# 📌 Função para processar uma única imagem
|
| 28 |
+
def process_image(image, image_name):
|
| 29 |
+
# Converter imagem para RGB (caso seja TIFF ou outro formato especial)
|
| 30 |
+
if image.mode != "RGB":
|
| 31 |
+
image = image.convert("RGB")
|
| 32 |
+
|
| 33 |
+
# Salvar temporariamente a imagem para passar ao Roboflow
|
| 34 |
+
temp_path = "temp_image.png"
|
| 35 |
+
image.save(temp_path)
|
| 36 |
+
|
| 37 |
+
# Fazer a predição
|
| 38 |
+
prediction = model.predict(temp_path)
|
| 39 |
+
prediction_data = prediction.json()
|
| 40 |
+
|
| 41 |
+
# Verificar se há segmentação
|
| 42 |
+
if "predictions" not in prediction_data or len(prediction_data["predictions"]) == 0:
|
| 43 |
+
return None, None, None
|
| 44 |
+
|
| 45 |
+
# Obter os pontos da segmentação e calcular a área
|
| 46 |
+
points = prediction_data['predictions'][0]['points']
|
| 47 |
+
area = calculate_polygon_area(points)
|
| 48 |
+
|
| 49 |
+
# Criar contorno da segmentação
|
| 50 |
+
x_coords = [p['x'] for p in points] + [points[0]['x']]
|
| 51 |
+
y_coords = [p['y'] for p in points] + [points[0]['y']]
|
| 52 |
+
|
| 53 |
+
# Criar figura
|
| 54 |
+
fig, ax = plt.subplots(figsize=(6, 6))
|
| 55 |
+
ax.imshow(image)
|
| 56 |
+
ax.plot(x_coords, y_coords, color='red', linewidth=2)
|
| 57 |
+
ax.set_title(f"Segmentação: {image_name}")
|
| 58 |
+
|
| 59 |
+
# Salvar a imagem segmentada em buffer
|
| 60 |
+
img_buffer = io.BytesIO()
|
| 61 |
+
plt.savefig(img_buffer, format="png", bbox_inches='tight')
|
| 62 |
+
img_buffer.seek(0)
|
| 63 |
+
plt.close()
|
| 64 |
+
|
| 65 |
+
return area, img_buffer, fig
|
| 66 |
+
|
| 67 |
+
# 📌 Função para extrair a hora do nome do arquivo (se aplicável)
|
| 68 |
+
def extract_hour_from_filename(filename):
|
| 69 |
+
match = re.search(r"(\d{1,2})h", filename.lower())
|
| 70 |
+
return int(match.group(1)) if match else None
|
| 71 |
+
|
| 72 |
+
# 📌 Interface Streamlit
|
| 73 |
+
st.title("Segmentação de Imagens - Roboflow")
|
| 74 |
+
st.write("Envie uma ou mais imagens para segmentação usando o modelo do Roboflow.")
|
| 75 |
+
|
| 76 |
+
# Opção de carregar uma única imagem ou múltiplas imagens
|
| 77 |
+
upload_option = st.radio("Escolha o tipo de upload:", ["Imagem única", "Pasta de imagens"])
|
| 78 |
+
|
| 79 |
+
# Lista para armazenar resultados
|
| 80 |
+
results = []
|
| 81 |
+
|
| 82 |
+
if upload_option == "Imagem única":
|
| 83 |
+
uploaded_file = st.file_uploader("Escolha uma imagem", type=["png", "jpg", "jpeg", "tiff"])
|
| 84 |
+
|
| 85 |
+
if uploaded_file:
|
| 86 |
+
image = Image.open(uploaded_file)
|
| 87 |
+
st.image(image, caption="Imagem Original", use_column_width=True)
|
| 88 |
+
|
| 89 |
+
st.write("Processando a segmentação...")
|
| 90 |
+
area, segmented_buffer, fig = process_image(image, uploaded_file.name)
|
| 91 |
+
|
| 92 |
+
if area is not None:
|
| 93 |
+
st.image(segmented_buffer, caption="Imagem Segmentada", use_column_width=True)
|
| 94 |
+
st.write(f"📏 **Área segmentada:** {area:.2f} pixels²")
|
| 95 |
+
st.download_button("Baixar Imagem Segmentada", segmented_buffer, file_name="segmentada.png", mime="image/png")
|
| 96 |
+
else:
|
| 97 |
+
st.warning("Nenhuma segmentação encontrada.")
|
| 98 |
+
|
| 99 |
+
elif upload_option == "Pasta de imagens":
|
| 100 |
+
uploaded_files = st.file_uploader("Envie várias imagens", type=["png", "jpg", "jpeg", "tiff"], accept_multiple_files=True)
|
| 101 |
+
|
| 102 |
+
if uploaded_files:
|
| 103 |
+
for uploaded_file in uploaded_files:
|
| 104 |
+
image = Image.open(uploaded_file)
|
| 105 |
+
st.write(f"**Processando:** {uploaded_file.name}")
|
| 106 |
+
st.image(image, caption="Imagem Original", use_column_width=True)
|
| 107 |
+
|
| 108 |
+
area, segmented_buffer, fig = process_image(image, uploaded_file.name)
|
| 109 |
+
|
| 110 |
+
if area is not None:
|
| 111 |
+
st.image(segmented_buffer, caption="Imagem Segmentada", use_column_width=True)
|
| 112 |
+
st.write(f"📏 **Área segmentada:** {area:.2f} pixels²")
|
| 113 |
+
|
| 114 |
+
results.append({
|
| 115 |
+
"Imagem": uploaded_file.name,
|
| 116 |
+
"Hora": extract_hour_from_filename(uploaded_file.name),
|
| 117 |
+
"Área Segmentada (px²)": area
|
| 118 |
+
})
|
| 119 |
+
|
| 120 |
+
# Criar DataFrame e exibir os resultados
|
| 121 |
+
if results:
|
| 122 |
+
results_df = pd.DataFrame(results).sort_values(by="Hora", na_position='last')
|
| 123 |
+
st.write("📊 **Tabela de Resultados**")
|
| 124 |
+
st.dataframe(results_df)
|
| 125 |
+
|
| 126 |
+
# Salvar em Excel para download
|
| 127 |
+
excel_buffer = io.BytesIO()
|
| 128 |
+
results_df.to_excel(excel_buffer, index=False)
|
| 129 |
+
excel_buffer.seek(0)
|
| 130 |
+
|
| 131 |
+
st.download_button(
|
| 132 |
+
label="📥 Baixar Resultados em Excel",
|
| 133 |
+
data=excel_buffer,
|
| 134 |
+
file_name="resultados_segmentacao.xlsx",
|
| 135 |
+
mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
| 136 |
+
)
|