File size: 4,617 Bytes
2bc0576 | 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 | 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 |