Spaces:
Running
on
Zero
Running
on
Zero
File size: 14,252 Bytes
dae4d1c 335bcd6 dae4d1c 335bcd6 dae4d1c 335bcd6 dae4d1c 335bcd6 dae4d1c 335bcd6 dae4d1c 335bcd6 dae4d1c 335bcd6 dae4d1c 335bcd6 dae4d1c 335bcd6 dae4d1c 335bcd6 dae4d1c 335bcd6 dae4d1c 335bcd6 dae4d1c 335bcd6 dae4d1c 335bcd6 dae4d1c ff46b3e 915a67a af83bc0 915a67a af83bc0 d715937 335bcd6 dae4d1c 335bcd6 dae4d1c 335bcd6 dae4d1c 335bcd6 dae4d1c 335bcd6 dae4d1c 335bcd6 dae4d1c 335bcd6 dae4d1c ff46b3e dae4d1c 335bcd6 dae4d1c 335bcd6 dae4d1c 335bcd6 5ea22b8 d528373 335bcd6 d528373 335bcd6 d528373 335bcd6 dae4d1c 335bcd6 dae4d1c 335bcd6 dae4d1c 335bcd6 dae4d1c 335bcd6 dae4d1c 335bcd6 dae4d1c 335bcd6 dae4d1c 335bcd6 dae4d1c 335bcd6 dae4d1c 335bcd6 dae4d1c 335bcd6 dae4d1c 915a67a 335bcd6 dae4d1c 335bcd6 dae4d1c 335bcd6 dae4d1c 335bcd6 dae4d1c 335bcd6 dae4d1c 335bcd6 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 |
import os
import traceback
from typing import Literal, Optional
import cv2
import matplotlib.patches as patches
import matplotlib.pyplot as plt
import numpy as np
import torch
from sam2.sam2_image_predictor import SAM2ImagePredictor
from utils import *
# --- Utility Functions (kept outside the class) ---
def blur_image(img: np.ndarray):
"""Applies Gaussian blur to an image."""
return cv2.GaussianBlur(img, (35, 35), 50)
def plot_polygon_mask(image: np.ndarray, polygons: list[list[tuple[int, int]]]):
"""
Plots polygon-based segmentation masks on top of an image.
"""
plt.imshow(image)
for polygon in polygons:
if not polygon:
continue # Skip empty polygons
polygon_array = np.array(polygon).reshape(-1, 2)
x, y = zip(*polygon_array)
x = list(x) + [x[0]]
y = list(y) + [y[0]]
plt.plot(x, y, "-r", linewidth=2)
plt.axis("off")
plt.tight_layout()
plt.show()
def visualize_boxes(image, findings):
"""Visualizes bounding boxes on an image."""
fig, ax = plt.subplots(1)
ax.imshow(image)
colors = ["r", "g", "b", "c", "m", "y", "k"]
for i, finding in enumerate(findings):
[x_min, y_min, x_max, y_max] = finding.bounding_box
color = colors[i % len(colors)]
rect = patches.Rectangle(
(x_min, y_min),
x_max - x_min,
y_max - y_min,
linewidth=2,
edgecolor=color,
facecolor="none",
)
ax.add_patch(rect)
print(f"Finding {i + 1} (Color: {color}):")
if not findings:
print("No findings")
plt.xticks(np.arange(0, image.shape[1], 50))
plt.yticks(np.arange(0, image.shape[0], 50))
plt.show()
# --- SAM Visualization Helpers (kept outside the class) ---
def show_mask(mask, ax, random_color=False, borders=True):
"""Displays a single mask on a matplotlib axis."""
if random_color:
color = np.concatenate([np.random.random(3), np.array([0.6])], axis=0)
else:
color = np.array([30 / 255, 144 / 255, 255 / 255, 0.6])
h, w = mask.shape[-2:]
mask = mask.astype(np.uint8)
mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)
if borders:
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
# contours = [cv2.approxPolyDP(contour, epsilon=0.01, closed=True) for contour in contours] # Optional smoothing
mask_image = cv2.drawContours(
mask_image, contours, -1, (1, 1, 1, 0.5), thickness=2
)
ax.imshow(mask_image)
def show_points(coords, labels, ax, marker_size=375):
"""Displays points (positive/negative) on a matplotlib axis."""
pos_points = coords[labels == 1]
neg_points = coords[labels == 0]
ax.scatter(
pos_points[:, 0],
pos_points[:, 1],
color="green",
marker="*",
s=marker_size,
edgecolor="white",
linewidth=1.25,
)
ax.scatter(
neg_points[:, 0],
neg_points[:, 1],
color="red",
marker="*",
s=marker_size,
edgecolor="white",
linewidth=1.25,
)
def show_box(box, ax):
"""Displays a bounding box on a matplotlib axis."""
x0, y0 = box[0], box[1]
w, h = box[2] - box[0], box[3] - box[1]
ax.add_patch(
plt.Rectangle((x0, y0), w, h, edgecolor="green", facecolor=(0, 0, 0, 0), lw=2)
)
def show_masks(
image,
masks,
scores,
point_coords=None,
box_coords=None,
input_labels=None,
borders=True,
):
"""Displays multiple masks resulting from SAM prediction."""
for i, (mask, score) in enumerate(zip(masks, scores)):
plt.figure(figsize=(10, 10))
plt.imshow(image)
show_mask(mask, plt.gca(), borders=borders)
if point_coords is not None:
assert input_labels is not None
show_points(point_coords, input_labels, plt.gca())
if box_coords is not None:
show_box(box_coords, plt.gca())
if len(scores) > 1:
plt.title(f"Mask {i + 1}, Score: {score:.3f}", fontsize=18)
plt.axis("off")
plt.show()
# --- ImageBlurnonymizer Class ---
class ImageBlurnonymizer:
def __init__(self):
self.predictor = None
self.device = None
self.init_sam()
def init_sam(self, force=False):
# only initialize SAM if it hasn't been initialized yet
if self.predictor is not None and not force:
return
# self.device = "cuda" if torch.cuda.is_available() else "cpu"
# self.device = "cuda"
self.device = "cuda"
# Set the device for PyTorch
self.predictor = SAM2ImagePredictor.from_pretrained(
"facebook/sam2.1-hiera-small",
device=self.device,
)
@staticmethod
def _smoothen_mask(mask: np.ndarray):
"""Applies morphological closing to smoothen mask boundaries."""
kernel = np.ones((20, 20), np.uint8)
return cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
@staticmethod
def _mask_from_bbox(image_shape, bbox: tuple[int, int, int, int]):
"""Creates a simple rectangular mask from a bounding box."""
height, width, *_ = image_shape # Allow for 2D or 3D shape tuple
xmin, ymin, xmax, ymax = bbox
mask = np.zeros((height, width), dtype=np.uint8)
mask[ymin:ymax, xmin:xmax] = 1
return mask # No need for np.array() conversion
@staticmethod
def _apply_blur_mask(image: np.ndarray, mask: np.ndarray):
"""Applies a blur to an image based on a mask."""
if mask.ndim == 2: # Ensure mask is 3-channel for broadcasting
mask = np.stack((mask,) * image.shape[2], axis=-1)
blurred = blur_image(image) # Use the utility function
return np.where(mask, blurred, image)
@staticmethod
def _binary_mask_to_polygon(binary_mask: np.ndarray, epsilon=2.0):
"""Converts a binary segmentation mask to polygon contours."""
try:
converted = (binary_mask * 255).astype(np.uint8)
# Use RETR_TREE to get hierarchy, CHAIN_APPROX_SIMPLE for efficiency
contours, _ = cv2.findContours(
converted, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
)
polygons = []
for contour in contours:
approx_contour = cv2.approxPolyDP(contour, epsilon, True)
# Ensure points are converted correctly
polygon = [
(int(point[0][0]), int(point[0][1])) for point in approx_contour
]
polygons.append(polygon)
return polygons
except Exception as e:
print(f"An error occurred during polygon conversion: {e}")
print(traceback.format_exc())
return None # Return None on error
def get_segmentation_mask(self, image: np.ndarray, bbox: tuple[int, int, int, int]):
"""
Generates a segmentation mask for a region defined by a bounding box using SAM.
Adds points within the bounding box to guide SAM towards the intended object (e.g., face)
and away from surrounding elements (e.g., hair).
"""
if self.predictor is None:
raise Exception("[-] sam has not been initialized")
# if torch.cuda.is_available() and self.device == "cpu":
# # class instance was wrongly initialized to run on cpu, but gpu is avaiable
# self.init_sam(force=True)
x_min, y_min, x_max, y_max = bbox
x_width = x_max - x_min
y_height = y_max - y_min # Corrected variable name
# Handle cases where box dimensions are too small for third calculations
x_third = x_width // 3 if x_width >= 3 else 0
y_third = y_height // 3 if y_height >= 3 else 0
center_point = [(x_min + x_max) // 2, (y_min + y_max) // 2]
# Define points ensuring they stay within the image boundaries
points = [center_point]
if y_third > 0:
points.append([center_point[0], center_point[1] - y_third])
points.append([center_point[0], center_point[1] + y_third])
if x_third > 0:
points.append([center_point[0] + x_third, center_point[1]])
points.append([center_point[0] - x_third, center_point[1]])
# Ensure points are valid coordinates (e.g., non-negative)
points = [[max(0, p[0]), max(0, p[1])] for p in points]
with torch.inference_mode(), torch.autocast(self.device, dtype=torch.bfloat16):
self.predictor.set_image(image)
masks, scores, _ = self.predictor.predict(
box=np.array(bbox), # Predictor might expect numpy array
point_coords=np.array(points),
point_labels=np.ones(len(points)), # Label 1 for inclusion
multimask_output=True,
)
# Sort masks by score and select the best one
sorted_ind = np.argsort(scores)[::-1]
best_mask = masks[sorted_ind[0]]
best_score = scores[sorted_ind[0]]
return self._smoothen_mask(best_mask), best_score
def censor_image_blur(
self,
image: np.ndarray,
raw_out: str,
method: Optional[Literal["segmentation", "bbox"]] = "segmentation",
verbose=False,
):
"""
Censors an image by blurring regions identified in the raw_out string (LLM output).
"""
self.init_sam()
json_output = parse_json_response(raw_out)
# Ensure json_output is a list before passing to parse_into_models
if isinstance(json_output, dict):
findings_list = [json_output]
elif isinstance(json_output, list):
findings_list = json_output
else:
# Handle unexpected type or raise an error
print(
f"Warning: Unexpected output type from parse_json_response: {type(json_output)}"
)
findings_list = []
parsed = parse_into_models(findings_list) # type: ignore
# Filter findings based on severity
filtered = [entry for entry in parsed if entry.severity > 0]
if verbose:
visualize_boxes(image, filtered) # Use external visualization
masks = []
for finding in filtered:
bbox = (
finding.bounding_box
) # Assuming finding has a 'bounding_box' attribute
if method == "segmentation":
mask, _ = self.get_segmentation_mask(image, bbox) # Use instance method
if verbose:
polygons = self._binary_mask_to_polygon(mask)
if polygons: # Check if polygon conversion was successful
plot_polygon_mask(image, polygons) # Use external visualization
elif method == "bbox":
mask = self._mask_from_bbox(image.shape, bbox) # Use static method
else:
print(
f"Warning: Unknown method '{method}'. Defaulting to no mask for this finding."
)
continue # Skip if method is invalid
masks.append(mask)
if masks: # Check if any masks were generated
# Combine masks: logical OR ensures any pixel in any mask is included
combined_mask = np.zeros_like(masks[0], dtype=np.uint8)
for mask in masks:
# Ensure masks are boolean or uint8 for logical_or
combined_mask = np.logical_or(combined_mask, mask.astype(bool)).astype(
np.uint8
)
return self._apply_blur_mask(image, combined_mask) # Use static method
return image # Return original image if no masks
def censor_image_blur_easy(
self,
image: np.ndarray,
boxes: list[BoundingBox],
method: Optional[Literal["segmentation", "bbox"]] = "segmentation",
verbose=False,
):
"""
Censors an image by blurring regions defined by a list of BoundingBox objects.
"""
self.init_sam()
# method = "bbox"
masks = []
for box in boxes:
bbox_tuple = box.to_tuple() # Convert BoundingBox object to tuple
if method == "segmentation":
mask, _ = self.get_segmentation_mask(image, bbox_tuple)
if verbose:
polygons = self._binary_mask_to_polygon(mask)
if polygons:
plot_polygon_mask(image, polygons)
elif method == "bbox":
mask = self._mask_from_bbox(image.shape, bbox_tuple)
else:
print(
f"Warning: Unknown method '{method}'. Defaulting to no mask for this box."
)
continue
masks.append(mask)
if masks:
combined_mask = np.zeros_like(masks[0], dtype=np.uint8)
for mask in masks:
combined_mask = np.logical_or(combined_mask, mask.astype(bool)).astype(
np.uint8
)
return self._apply_blur_mask(image, combined_mask)
return image
# Example Usage (Optional - keep outside class):
# if __name__ == '__main__':
# # Load an image
# # img = cv2.imread('path/to/your/image.jpg')
# # img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # Convert to RGB for matplotlib
# # Create an instance of the blurnonymizer
# # blurnonymizer = ImageBlurnonymizer()
# # Define bounding boxes or get raw LLM output
# # example_boxes = [BoundingBox(xmin=100, ymin=100, xmax=200, ymax=200)] # Assuming BoundingBox class exists
# # llm_output = '...' # Your raw LLM output string
# # Censor the image
# # censored_img_easy = blurnonymizer.censor_image_blur_easy(img, example_boxes, method='segmentation', verbose=True)
# # censored_img_llm = blurnonymizer.censor_image_blur(img, llm_output, method='segmentation', verbose=True)
# # Display or save the result
# # plt.imshow(censored_img_easy)
# # plt.show()
|