Spaces:
Paused

CK1 / utils /image_processing.py
Kesherat's picture
Clean YOLO API deployment without any tokens
2bc0576
Raw History Blame Contribute Delete
4.62 kB
import base64
import cv2
import numpy as np
from typing import Tuple, Optional, Union
def decode_base64_image(base64_string: str) -> np.ndarray:
"""
Decode a base64 string to a numpy image array
Args:
base64_string: Base64 encoded image string
Returns:
numpy.ndarray: Decoded image in BGR format (OpenCV default)
"""
# Remove data URL prefix if present
if base64_string.startswith('data:image'):
base64_string = base64_string.split(',')[1]
# Decode base64 string
image_data = base64.b64decode(base64_string)
# Convert to numpy array
nparr = np.frombuffer(image_data, np.uint8)
# Decode image
image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
if image is None:
raise ValueError("Failed to decode base64 image")
return image
def encode_image_to_base64(image: np.ndarray, format: str = '.jpg', quality: int = 90) -> str:
"""
Encode a numpy image array to base64 string
Args:
image: Image as numpy array (BGR format)
format: Image format ('.jpg', '.png', etc.)
quality: JPEG quality (0-100) if format is '.jpg'
Returns:
str: Base64 encoded image string
"""
# Set encoding parameters
if format.lower() == '.jpg' or format.lower() == '.jpeg':
params = [cv2.IMWRITE_JPEG_QUALITY, quality]
elif format.lower() == '.png':
params = [cv2.IMWRITE_PNG_COMPRESSION, min(9, quality // 10)]
else:
params = []
# Encode image
_, buffer = cv2.imencode(format, image, params)
# Convert to base64
base64_string = base64.b64encode(buffer).decode('utf-8')
return base64_string
def resize_image(image: np.ndarray, target_size: Tuple[int, int],
keep_aspect_ratio: bool = True) -> np.ndarray:
"""
Resize image to target size
Args:
image: Input image
target_size: Target size as (width, height)
keep_aspect_ratio: Whether to maintain aspect ratio
Returns:
numpy.ndarray: Resized image
"""
if keep_aspect_ratio:
h, w = image.shape[:2]
target_w, target_h = target_size
# Calculate scaling factor
scale = min(target_w / w, target_h / h)
# Calculate new dimensions
new_w, new_h = int(w * scale), int(h * scale)
# Resize image
resized = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_AREA)
# Create canvas of target size
canvas = np.zeros((target_h, target_w, 3), dtype=np.uint8)
# Calculate position to paste resized image
x_offset = (target_w - new_w) // 2
y_offset = (target_h - new_h) // 2
# Paste resized image onto canvas
canvas[y_offset:y_offset+new_h, x_offset:x_offset+new_w] = resized
return canvas
else:
# Simple resize without preserving aspect ratio
return cv2.resize(image, target_size, interpolation=cv2.INTER_AREA)
def draw_detections(image: np.ndarray, detections: list) -> np.ndarray:
"""
Draw detection bounding boxes on image
Args:
image: Input image
detections: List of detection results with bbox, class_name, confidence, color
Returns:
numpy.ndarray: Image with bounding boxes drawn
"""
output = image.copy()
for det in detections:
x1, y1, x2, y2 = det["bbox"]
class_name = det["class_name"]
confidence = det["confidence"]
color = tuple(det["color"]) # Convert to tuple for OpenCV
# Draw bounding box
cv2.rectangle(output, (x1, y1), (x2, y2), color, 2)
# Draw label background
text = f"{class_name}: {confidence:.2f}"
text_size, _ = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 2)
cv2.rectangle(output, (x1, y1 - text_size[1] - 5), (x1 + text_size[0], y1), color, -1)
# Draw text
cv2.putText(output, text, (x1, y1 - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
return output
def preprocess_image_for_detection(image: np.ndarray, target_size: Tuple[int, int] = (640, 640)) -> np.ndarray:
"""
Preprocess image for YOLO detection
Args:
image: Input image
target_size: Target size for the model
Returns:
numpy.ndarray: Preprocessed image
"""
# Resize image
resized = resize_image(image, target_size, keep_aspect_ratio=True)
return resized