Manu
commited on
Commit
·
c4b5ce1
1
Parent(s):
2843e59
fixed bug in segmentation_utils.py finally clause
Browse files- segmentation_utils.py +38 -245
segmentation_utils.py
CHANGED
|
@@ -2,6 +2,7 @@ import requests
|
|
| 2 |
from pycocotools import mask
|
| 3 |
import matplotlib.pyplot as plt
|
| 4 |
from PIL import Image, ImageDraw, ImageOps, ImageFont
|
|
|
|
| 5 |
import os
|
| 6 |
import base64
|
| 7 |
import io
|
|
@@ -10,93 +11,13 @@ import numpy as np
|
|
| 10 |
import cv2
|
| 11 |
from image_utils import print_text_on_image_centered, create_background_image
|
| 12 |
from icecream import ic
|
| 13 |
-
import traceback
|
| 14 |
-
from pprint import pprint
|
| 15 |
|
| 16 |
|
|
|
|
|
|
|
| 17 |
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
# Si la entrada es una URL, descarga la imagen y la convierte en un array de numpy
|
| 21 |
-
# Si la entrada es una ruta de archivo, carga la imagen y la convierte en un array de numpy
|
| 22 |
-
# Si la entrada ya es un array de numpy, devuélvela tal cual
|
| 23 |
-
# Si la entrada no es ninguna de las anteriores, lanza un ValueError
|
| 24 |
-
|
| 25 |
-
def transform_image_to_numpy_array(input):
|
| 26 |
-
if isinstance(input, np.ndarray):
|
| 27 |
-
# Si la entrada es un array de numpy, devuélvela tal cual
|
| 28 |
-
h, w = input.shape[:2]
|
| 29 |
-
new_height = int(h * (500 / w))
|
| 30 |
-
return cv2.resize(input, (500, new_height))
|
| 31 |
-
elif isinstance(input, str):
|
| 32 |
-
# Si la entrada es una cadena, podría ser una URL o una ruta de archivo
|
| 33 |
-
if input.startswith('http://') or input.startswith('https://'):
|
| 34 |
-
# Si la entrada es una URL, descarga la imagen y conviértela en un array de numpy
|
| 35 |
-
# se necesita un header para evitar el error 403
|
| 36 |
-
headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36"}
|
| 37 |
-
response = requests.get(input, headers=headers)
|
| 38 |
-
ic(response.status_code)
|
| 39 |
-
image_array = np.frombuffer(response.content, dtype=np.uint8)
|
| 40 |
-
image = cv2.imdecode(image_array, -1)
|
| 41 |
-
|
| 42 |
-
# Si la imagen tiene 3 canales (es decir, es una imagen en color),
|
| 43 |
-
# convertirla de BGR a RGB
|
| 44 |
-
if image.ndim == 3:
|
| 45 |
-
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
| 46 |
-
image = Image.fromarray(image).convert("RGBA")
|
| 47 |
-
image = np.array(image)
|
| 48 |
-
else:
|
| 49 |
-
# Si la entrada es una ruta de archivo, carga la imagen y conviértela en un array de numpy
|
| 50 |
-
image = cv2.imread(input)
|
| 51 |
-
|
| 52 |
-
h, w = image.shape[:2]
|
| 53 |
-
new_height = int(h * (500 / w))
|
| 54 |
-
return cv2.resize(image, (500, new_height))
|
| 55 |
-
else:
|
| 56 |
-
raise ValueError("La entrada no es un array de numpy, una URL ni una ruta de archivo.")
|
| 57 |
-
|
| 58 |
-
def transform_image_to_numpy_array2(input):
|
| 59 |
-
if isinstance(input, np.ndarray):
|
| 60 |
-
# Si la entrada es un array de numpy, devuélvela tal cual
|
| 61 |
-
return cv2.resize(input, (500, 500))
|
| 62 |
-
elif isinstance(input, str):
|
| 63 |
-
# Si la entrada es una cadena, podría ser una URL o una ruta de archivo
|
| 64 |
-
if input.startswith('http://') or input.startswith('https://'):
|
| 65 |
-
# Si la entrada es una URL, descarga la imagen y conviértela en un array de numpy
|
| 66 |
-
# se necesita un header para evitar el error 403
|
| 67 |
-
headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36"}
|
| 68 |
-
response = requests.get(input, headers=headers)
|
| 69 |
-
ic(response.status_code)
|
| 70 |
-
image_array = np.frombuffer(response.content, dtype=np.uint8)
|
| 71 |
-
image = cv2.imdecode(image_array, -1)
|
| 72 |
-
|
| 73 |
-
# Si la imagen tiene 3 canales (es decir, es una imagen en color),
|
| 74 |
-
# convertirla de BGR a RGB
|
| 75 |
-
if image.ndim == 3:
|
| 76 |
-
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
| 77 |
-
image = Image.fromarray(image).convert("RGBA")
|
| 78 |
-
image = np.array(image)
|
| 79 |
-
else:
|
| 80 |
-
# Si la entrada es una ruta de archivo, carga la imagen y conviértela en un array de numpy
|
| 81 |
-
image = cv2.imread(input)
|
| 82 |
-
|
| 83 |
-
return cv2.resize(image, (500, 500))
|
| 84 |
-
else:
|
| 85 |
-
raise ValueError("La entrada no es un array de numpy, una URL ni una ruta de archivo.")
|
| 86 |
-
|
| 87 |
-
def segment_image_from_numpy(image_array, api_token, model):
|
| 88 |
-
|
| 89 |
-
#API_URL = "https://api-inference.huggingface.co/models/facebook/mask2former-swin-tiny-coco-panoptic"
|
| 90 |
-
API_URL = f"https://api-inference.huggingface.co/models/facebook/{model}"
|
| 91 |
-
headers = {"Authorization": f"Bearer {api_token}"}
|
| 92 |
-
|
| 93 |
-
# Convert the image to bytes
|
| 94 |
-
is_success, im_buf_arr = cv2.imencode(".jpg", image_array)
|
| 95 |
-
data = im_buf_arr.tobytes()
|
| 96 |
-
response = requests.post(API_URL, headers=headers, data=data)
|
| 97 |
-
pprint(response.json())
|
| 98 |
-
return response.json()
|
| 99 |
-
|
| 100 |
|
| 101 |
def segment_image_from_path(image_path):
|
| 102 |
with open(image_path, "rb") as f:
|
|
@@ -118,90 +39,13 @@ def decode_mask(mask_str, size):
|
|
| 118 |
mask_image = mask_image.resize(size).convert("L")
|
| 119 |
return mask_image
|
| 120 |
|
| 121 |
-
|
| 122 |
def overlay_masks_on_image(image, segments, transparency=0.4):
|
| 123 |
-
if isinstance(image, np.ndarray):
|
| 124 |
-
image = Image.fromarray(image)
|
| 125 |
-
|
| 126 |
-
original_image = image
|
| 127 |
-
if original_image.mode != 'RGBA':
|
| 128 |
-
original_image = original_image.convert('RGBA')
|
| 129 |
-
|
| 130 |
-
overlay = Image.new("RGBA", original_image.size, (255, 255, 255, 0))
|
| 131 |
-
text_layer = Image.new("RGBA", original_image.size, (255, 255, 255, 0))
|
| 132 |
-
|
| 133 |
-
for segment in segments:
|
| 134 |
-
mask_str = segment['mask']
|
| 135 |
-
mask_image = decode_mask(mask_str, original_image.size)
|
| 136 |
-
color = generate_random_color()
|
| 137 |
-
|
| 138 |
-
color_mask = ImageOps.colorize(mask_image, black="black", white=color)
|
| 139 |
-
color_mask.putalpha(mask_image)
|
| 140 |
-
|
| 141 |
-
overlay = Image.alpha_composite(overlay, color_mask)
|
| 142 |
-
|
| 143 |
-
# Calcula el centroide de la mascara
|
| 144 |
-
x, y = np.where(np.array(mask_image) > 0)
|
| 145 |
-
centroid_x = x.mean()
|
| 146 |
-
centroid_y = y.mean()
|
| 147 |
-
|
| 148 |
-
# Imprime la etiqueta y la puntuación en la capa de texto
|
| 149 |
-
font_size = 30
|
| 150 |
-
draw = ImageDraw.Draw(text_layer)
|
| 151 |
-
font = ImageFont.load_default().font_variant(size=font_size)
|
| 152 |
-
label = segment['label']
|
| 153 |
-
score = segment['score']
|
| 154 |
-
text =f"{label}: {score}"
|
| 155 |
-
|
| 156 |
-
# Calcula el tamaño del texto
|
| 157 |
-
text_bbox = draw.textbbox((0, 0), text, font=font)
|
| 158 |
-
text_width = text_bbox[2] - text_bbox[0]
|
| 159 |
-
text_height = text_bbox[3] - text_bbox[1]
|
| 160 |
-
|
| 161 |
-
# Asegúrate de que las coordenadas del texto están dentro de los límites de la imagen
|
| 162 |
-
text_x = max(0, min(centroid_x - text_width / 2, original_image.size[0] - text_width))
|
| 163 |
-
text_y = max(0, min(centroid_y - text_height / 2, original_image.size[1] - text_height))
|
| 164 |
-
|
| 165 |
-
draw.text((text_x, text_y), text, fill=(255, 255, 255, 255), font=font)
|
| 166 |
-
|
| 167 |
-
# Ajusta la transparencia de la capa de superposición
|
| 168 |
-
overlay = Image.blend(original_image, overlay, transparency)
|
| 169 |
-
|
| 170 |
-
# Combina la capa de superposición con la capa de texto
|
| 171 |
-
final_image = Image.alpha_composite(overlay, text_layer)
|
| 172 |
-
|
| 173 |
-
return final_image
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
def overlay_masks_on_image2(image, segments, transparency=0.4):
|
| 183 |
# Convert numpy array to PIL Image
|
| 184 |
-
|
| 185 |
-
|
| 186 |
#original_image = Image.open(image).convert("RGBA")
|
| 187 |
-
# para file es str
|
| 188 |
-
# para url es numpy.ndarray
|
| 189 |
-
# para cv.imread es numpy.ndarray
|
| 190 |
-
|
| 191 |
-
# Convertir el array de numpy a una imagen PIL si es necesario
|
| 192 |
-
if isinstance(image, np.ndarray):
|
| 193 |
-
image = Image.fromarray(image)
|
| 194 |
-
|
| 195 |
-
print(type(image))
|
| 196 |
-
print(image)
|
| 197 |
-
original_image = image
|
| 198 |
-
|
| 199 |
-
if original_image.mode != 'RGBA':
|
| 200 |
-
original_image = original_image.convert('RGBA')
|
| 201 |
-
|
| 202 |
-
print(original_image.size)
|
| 203 |
overlay = Image.new("RGBA", original_image.size, (255, 255, 255, 0))
|
| 204 |
-
|
| 205 |
# Nueva capa para el texto
|
| 206 |
|
| 207 |
text_layer = Image.new("RGBA", original_image.size, (255, 255, 255, 0))
|
|
@@ -212,27 +56,6 @@ def overlay_masks_on_image2(image, segments, transparency=0.4):
|
|
| 212 |
print(segment['label'] + " " + str(segment['score']))
|
| 213 |
mask_str = segment['mask']
|
| 214 |
mask_image = decode_mask(mask_str, original_image.size)
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
# Convierte la imagen de la máscara a un array de numpy
|
| 219 |
-
mask_array = np.array(mask_image)
|
| 220 |
-
|
| 221 |
-
# Encuentra los píxeles blancos
|
| 222 |
-
y, x = np.where(mask_array > 0)
|
| 223 |
-
|
| 224 |
-
# Calcula el cuadro delimitador de los píxeles blancos
|
| 225 |
-
x_min, y_min, width, height = cv2.boundingRect(np.array(list(zip(x, y))))
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
# Crea un objeto ImageDraw para dibujar en la imagen original
|
| 229 |
-
draw = ImageDraw.Draw(original_image)
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
# Dibuja el cuadro delimitador en la imagen original
|
| 233 |
-
draw.rectangle([(x_min, y_min), (x_min + width, y_min + height)], outline=(0, 255, 0), width=2)
|
| 234 |
-
|
| 235 |
-
|
| 236 |
color = generate_random_color()
|
| 237 |
|
| 238 |
color_mask = ImageOps.colorize(mask_image, black="black", white=color)
|
|
@@ -240,7 +63,6 @@ def overlay_masks_on_image2(image, segments, transparency=0.4):
|
|
| 240 |
|
| 241 |
overlay = Image.alpha_composite(overlay, color_mask)
|
| 242 |
|
| 243 |
-
|
| 244 |
# Calcula el centroide de la mascara
|
| 245 |
|
| 246 |
x, y = np.where(np.array(mask_image) > 0)
|
|
@@ -261,33 +83,11 @@ def overlay_masks_on_image2(image, segments, transparency=0.4):
|
|
| 261 |
|
| 262 |
text_width = 500
|
| 263 |
text_height = 100
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
# Asegúrate de que las coordenadas del texto están dentro de los límites de la imagen
|
| 267 |
-
text_x = max(0, min(centroid_x - text_width / 2, original_image.size[0] - text_width))
|
| 268 |
-
text_y = max(0, min(centroid_y - text_height / 2, original_image.size[1] - text_height))
|
| 269 |
-
# Asegúrate de que las coordenadas del texto están dentro de los límites de la imagen
|
| 270 |
-
text_x = max(0, min(centroid_x, original_image.size[0] - text_width))
|
| 271 |
-
text_y = max(0, min(centroid_y, original_image.size[1] - text_height))
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
# Calcula las coordenadas del texto
|
| 275 |
-
text_x = centroid_x - text_width / 2
|
| 276 |
-
text_y = centroid_y - text_height / 2
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
# Asegúrate de que las coordenadas del texto están dentro de los límites de la imagen
|
| 280 |
-
text_x = max(0, min(text_x, original_image.size[0] - text_width))
|
| 281 |
-
text_y = max(0, min(text_y, original_image.size[1] - text_height))
|
| 282 |
-
|
| 283 |
-
|
| 284 |
draw.text((centroid_x - text_width / 2, centroid_y - text_height / 2), text, fill=(255, 255, 255, 255), font=font)
|
| 285 |
-
|
| 286 |
-
#draw.text((text_x, text_y), text, fill=(255, 255, 255, 255), font=font)
|
| 287 |
|
| 288 |
# Ajusta la transparencia de la capa de superposición
|
| 289 |
-
|
| 290 |
-
print(overlay.size)
|
| 291 |
overlay = Image.blend(original_image, overlay, transparency)
|
| 292 |
|
| 293 |
# Combina la capa de superposición con la capa de texto
|
|
@@ -302,70 +102,63 @@ def generate_random_color():
|
|
| 302 |
return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
|
| 303 |
|
| 304 |
|
| 305 |
-
def segment_and_overlay_results(
|
| 306 |
#segments = segment_image_from_image(image)
|
| 307 |
#final_image = overlay_masks_on_image(image, segments)
|
| 308 |
#return final_image
|
| 309 |
processed_image = None # Initialize processed_image
|
| 310 |
segments = []
|
| 311 |
-
#image_type = None
|
| 312 |
-
#if isinstance(image_path, str):
|
| 313 |
-
# image_type = 'FILE'
|
| 314 |
-
# image = cv2.imread('cats.jpg')
|
| 315 |
-
#elif isinstance(image_path, np.ndarray):
|
| 316 |
-
# image_type = 'NUMPY ARRAY'
|
| 317 |
-
#else:
|
| 318 |
-
# raise ValueError("The image is neither a Image nor a local file.")
|
| 319 |
-
|
| 320 |
-
#ic(image_type)
|
| 321 |
-
image = transform_image_to_numpy_array(image_path)
|
| 322 |
-
# imprime tres primeros pixeles
|
| 323 |
-
print(type(image))
|
| 324 |
-
ic(image[0, 0:3])
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
try:
|
| 330 |
#segments = segment_image_from_image(image)
|
| 331 |
#processed_image = overlay_masks_on_image(image, segments)
|
| 332 |
|
| 333 |
# debug image contents
|
| 334 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 335 |
#if os.path.isfile(image):
|
| 336 |
# ic ("--- image is a file ---")
|
| 337 |
# image = Image.open(image)
|
| 338 |
# if image is None:
|
| 339 |
# ic("image is None")
|
| 340 |
# return None, []
|
| 341 |
-
|
| 342 |
-
ic("--- calling
|
| 343 |
-
segments =
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
ic("--- printing segments ---")
|
| 350 |
-
for segment in segments:
|
| 351 |
-
ic(segment['label'] ,segment['score'])
|
| 352 |
processed_image = print_text_on_image_centered(
|
| 353 |
create_background_image(500, 500, "white"),
|
| 354 |
'SEGMENTING OK',
|
| 355 |
'green'
|
| 356 |
)
|
| 357 |
-
|
| 358 |
processed_image = overlay_masks_on_image(image, segments)
|
| 359 |
except Exception as e:
|
| 360 |
-
print("EXCEPTION")
|
| 361 |
ic(e)
|
| 362 |
-
print(traceback.format_exc())
|
| 363 |
processed_image = print_text_on_image_centered(
|
| 364 |
create_background_image(500, 500, "white"),
|
| 365 |
e,
|
| 366 |
'green'
|
| 367 |
)
|
| 368 |
segments = []
|
| 369 |
-
return processed_image, segments
|
| 370 |
finally:
|
| 371 |
return processed_image, segments
|
|
|
|
| 2 |
from pycocotools import mask
|
| 3 |
import matplotlib.pyplot as plt
|
| 4 |
from PIL import Image, ImageDraw, ImageOps, ImageFont
|
| 5 |
+
from dotenv import find_dotenv, load_dotenv
|
| 6 |
import os
|
| 7 |
import base64
|
| 8 |
import io
|
|
|
|
| 11 |
import cv2
|
| 12 |
from image_utils import print_text_on_image_centered, create_background_image
|
| 13 |
from icecream import ic
|
|
|
|
|
|
|
| 14 |
|
| 15 |
|
| 16 |
+
load_dotenv(find_dotenv())
|
| 17 |
+
HUGGINGFACEHUB_API_TOKEN = os.getenv("HUGGINGFACEHUB_API_TOKEN")
|
| 18 |
|
| 19 |
+
API_URL = "https://api-inference.huggingface.co/models/facebook/mask2former-swin-tiny-coco-panoptic"
|
| 20 |
+
headers = {"Authorization": f"Bearer {HUGGINGFACEHUB_API_TOKEN}"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
def segment_image_from_path(image_path):
|
| 23 |
with open(image_path, "rb") as f:
|
|
|
|
| 39 |
mask_image = mask_image.resize(size).convert("L")
|
| 40 |
return mask_image
|
| 41 |
|
|
|
|
| 42 |
def overlay_masks_on_image(image, segments, transparency=0.4):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
# Convert numpy array to PIL Image
|
| 44 |
+
original_image = Image.fromarray(image).convert("RGBA")
|
| 45 |
+
|
| 46 |
#original_image = Image.open(image).convert("RGBA")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
overlay = Image.new("RGBA", original_image.size, (255, 255, 255, 0))
|
| 48 |
+
|
| 49 |
# Nueva capa para el texto
|
| 50 |
|
| 51 |
text_layer = Image.new("RGBA", original_image.size, (255, 255, 255, 0))
|
|
|
|
| 56 |
print(segment['label'] + " " + str(segment['score']))
|
| 57 |
mask_str = segment['mask']
|
| 58 |
mask_image = decode_mask(mask_str, original_image.size)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
color = generate_random_color()
|
| 60 |
|
| 61 |
color_mask = ImageOps.colorize(mask_image, black="black", white=color)
|
|
|
|
| 63 |
|
| 64 |
overlay = Image.alpha_composite(overlay, color_mask)
|
| 65 |
|
|
|
|
| 66 |
# Calcula el centroide de la mascara
|
| 67 |
|
| 68 |
x, y = np.where(np.array(mask_image) > 0)
|
|
|
|
| 83 |
|
| 84 |
text_width = 500
|
| 85 |
text_height = 100
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
draw.text((centroid_x - text_width / 2, centroid_y - text_height / 2), text, fill=(255, 255, 255, 255), font=font)
|
| 87 |
+
|
|
|
|
| 88 |
|
| 89 |
# Ajusta la transparencia de la capa de superposición
|
| 90 |
+
|
|
|
|
| 91 |
overlay = Image.blend(original_image, overlay, transparency)
|
| 92 |
|
| 93 |
# Combina la capa de superposición con la capa de texto
|
|
|
|
| 102 |
return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
|
| 103 |
|
| 104 |
|
| 105 |
+
def segment_and_overlay_results(image, api_token, model):
|
| 106 |
#segments = segment_image_from_image(image)
|
| 107 |
#final_image = overlay_masks_on_image(image, segments)
|
| 108 |
#return final_image
|
| 109 |
processed_image = None # Initialize processed_image
|
| 110 |
segments = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
try:
|
| 112 |
#segments = segment_image_from_image(image)
|
| 113 |
#processed_image = overlay_masks_on_image(image, segments)
|
| 114 |
|
| 115 |
# debug image contents
|
| 116 |
+
|
| 117 |
+
ic(image)
|
| 118 |
+
|
| 119 |
+
if image.startswith('http://') or image.startswith('https://'):
|
| 120 |
+
ic("image is a URL: " + image)
|
| 121 |
+
response = requests.get(image)
|
| 122 |
+
image = Image.open(BytesIO(response.content))
|
| 123 |
+
else:
|
| 124 |
+
# Check if image is a local file
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
if os.path.isfile(os.path.join(os.getcwd(), image)):
|
| 128 |
+
ic("image is a file: " + image + "OK")
|
| 129 |
+
image = Image.open(image)
|
| 130 |
+
else:
|
| 131 |
+
raise ValueError("The image is neither a URL nor a local file.")
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
|
| 135 |
#if os.path.isfile(image):
|
| 136 |
# ic ("--- image is a file ---")
|
| 137 |
# image = Image.open(image)
|
| 138 |
# if image is None:
|
| 139 |
# ic("image is None")
|
| 140 |
# return None, []
|
| 141 |
+
print(image)
|
| 142 |
+
ic("--- calling segment_image_from_image ---")
|
| 143 |
+
#segments = segment_image_from_image(image)
|
| 144 |
+
segments = segment_image_from_path('cats.jpg')
|
| 145 |
+
for segment in segments:
|
| 146 |
+
print("segmentation_utils.py segment_and_overlay_results")
|
| 147 |
+
print(segment['label'] + " " + str(segment['score']))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
processed_image = print_text_on_image_centered(
|
| 149 |
create_background_image(500, 500, "white"),
|
| 150 |
'SEGMENTING OK',
|
| 151 |
'green'
|
| 152 |
)
|
| 153 |
+
print("--- calling overlay_masks_on_image ---")
|
| 154 |
processed_image = overlay_masks_on_image(image, segments)
|
| 155 |
except Exception as e:
|
|
|
|
| 156 |
ic(e)
|
|
|
|
| 157 |
processed_image = print_text_on_image_centered(
|
| 158 |
create_background_image(500, 500, "white"),
|
| 159 |
e,
|
| 160 |
'green'
|
| 161 |
)
|
| 162 |
segments = []
|
|
|
|
| 163 |
finally:
|
| 164 |
return processed_image, segments
|