File size: 5,657 Bytes
d2693ac | 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 | #!/usr/bin/env python3
"""
Script to test the Marine Species API and save annotated images for viewing.
"""
import requests
import base64
import json
import time
from pathlib import Path
import sys
from PIL import Image
import io
def encode_image_to_base64(image_path: str) -> str:
"""Encode an image file to base64 string."""
try:
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode('utf-8')
except Exception as e:
print(f"Error encoding image {image_path}: {e}")
return None
def save_base64_image(base64_string: str, output_path: str) -> bool:
"""Save a base64 encoded image to a file."""
try:
# Decode base64 to bytes
image_bytes = base64.b64decode(base64_string)
# Open with PIL and save
image = Image.open(io.BytesIO(image_bytes))
image.save(output_path)
print(f"β
Saved annotated image: {output_path}")
return True
except Exception as e:
print(f"β Failed to save image: {e}")
return False
def test_and_save_annotated_image(api_url: str, image_path: str, output_dir: str):
"""Test API with an image and save the annotated result."""
image_name = Path(image_path).stem
print(f"\nπ Processing {Path(image_path).name}")
print("-" * 50)
# Encode input image
print("π· Encoding image...")
image_b64 = encode_image_to_base64(image_path)
if not image_b64:
return False
# Prepare API request
detection_request = {
"image": image_b64,
"confidence_threshold": 0.25,
"iou_threshold": 0.45,
"image_size": 640,
"return_annotated_image": True
}
try:
print("π Sending detection request...")
start_time = time.time()
response = requests.post(
f"{api_url}/api/v1/detect",
json=detection_request,
timeout=60
)
request_time = time.time() - start_time
print(f"β±οΈ Request completed in {request_time:.2f}s")
if response.status_code == 200:
result = response.json()
detections = result.get('detections', [])
processing_time = result.get('processing_time', 0)
annotated_image_b64 = result.get('annotated_image')
print(f"β
SUCCESS!")
print(f" Processing Time: {processing_time:.3f}s")
print(f" Detections Found: {len(detections)}")
# Show top detections
if detections:
print(f" π― Top Detections:")
for i, detection in enumerate(detections[:3]):
species = detection.get('class_name', 'Unknown')
confidence = detection.get('confidence', 0)
print(f" {i+1}. {species} (confidence: {confidence:.3f})")
# Save annotated image
if annotated_image_b64:
output_path = Path(output_dir) / f"{image_name}_annotated.jpg"
success = save_base64_image(annotated_image_b64, str(output_path))
if success:
print(f" πΌοΈ View annotated image: {output_path}")
return str(output_path)
else:
print(" β No annotated image returned")
else:
print(f"β Request failed with status {response.status_code}")
print(f" Response: {response.text}")
except Exception as e:
print(f"β Request failed: {e}")
return None
def main():
"""Main function."""
# API URL
api_url = sys.argv[1] if len(sys.argv) > 1 else "https://seamo-ai-fishapi.hf.space"
print("π Marine Species API - Annotated Image Viewer")
print("=" * 60)
print(f"API URL: {api_url}")
# Create output directory
output_dir = Path("annotated_results")
output_dir.mkdir(exist_ok=True)
print(f"Output directory: {output_dir.absolute()}")
# Find test images
image_dir = Path("docs/gradio/images")
if not image_dir.exists():
print(f"\nβ Image directory not found: {image_dir}")
return
# Get image files
image_files = []
for ext in ['*.png', '*.jpg', '*.jpeg']:
image_files.extend(image_dir.glob(ext))
if not image_files:
print(f"\nβ No image files found in {image_dir}")
return
print(f"\nπ Found {len(image_files)} test images")
# Process each image
saved_images = []
for image_path in sorted(image_files):
result_path = test_and_save_annotated_image(api_url, str(image_path), str(output_dir))
if result_path:
saved_images.append(result_path)
time.sleep(1) # Small delay between requests
# Summary
print("\n" + "=" * 60)
print(f"π― Summary:")
print(f" Processed: {len(image_files)} images")
print(f" Saved: {len(saved_images)} annotated images")
if saved_images:
print(f"\nπΌοΈ Annotated images saved to:")
for img_path in saved_images:
print(f" - {img_path}")
print(f"\nπ‘ To view the images:")
print(f" - Open the files in any image viewer")
print(f" - Or run: open {output_dir}") # macOS
print(f" - Or run: xdg-open {output_dir}") # Linux
print(f" - Or navigate to: {output_dir.absolute()}")
if __name__ == "__main__":
main()
|