import json
import cv2
import os
def visualize_annotations(json_file, image_dir, output_dir):
"""
Visualizes bounding box annotations from a COCO-style JSON file onto the original images.
Args:
json_file (str): Path to the COCO-style JSON annotation file.
image_dir (str): Path to the directory containing the original images.
output_dir (str): Path to the directory where visualized images will be saved.
"""
# Load the JSON annotation file
with open(json_file, 'r') as f:
data = json.load(f)
# Create the output directory if it doesn't exist
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# Create a mapping from category ID to category name
category_id_to_name = {cat['id']: cat['name'] for cat in data['categories']}
# Iterate through the images and annotations
for image_info in data['images']:
image_id = image_info['id']
image_file_name = image_info['file_name']
image_path = os.path.join(image_dir, image_file_name)
# Load the image
try:
image = cv2.imread(image_path)
if image is None:
print(f"Error: Could not read image at {image_path}")
continue
except Exception as e:
print(f"Error loading image {image_file_name}: {e}")
continue
# Get the annotations for the current image
annotations = [ann for ann in data['annotations'] if ann['image_id'] == image_id]
# Draw the bounding boxes and labels on the image
for annotation in annotations:
bbox = annotation['bbox']
category_id = annotation['category_id']
category_name = category_id_to_name.get(category_id, "Unknown") # Handle missing categories
x, y, w, h = map(int, bbox) # Convert to integers for drawing
# Draw the bounding box (you can adjust the color and thickness)
color = (0, 255, 0) # Green
thickness = 2
cv2.rectangle(image, (x, y), (x + w, y + h), color, thickness)
# Add the category label (you can adjust the position and font)
label = category_name
font = cv2.FONT_HERSHEY_SIMPLEX
font_scale = 0.7
font_color = (255, 255, 255) # White
font_thickness = 2
text_size = cv2.getTextSize(label, font, font_scale, font_thickness)[0]
text_x = x
text_y = y - 10 if y > 10 else y + text_size[1] + 10 # Adjust position if too close to top
cv2.putText(image, label, (text_x, text_y), font, font_scale, font_color, font_thickness)
# Save the visualized image
output_file_name = f"visualized_{image_file_name}"
output_path = os.path.join(output_dir, output_file_name)
cv2.imwrite(output_path, image)
print(f"Visualized image saved to: {output_path}")
# Example usage:
if __name__ == "__main__":
json_file = "your_annotations.json" # Replace with your JSON file path
image_dir = "your_image_directory" # Replace with your image directory path
output_dir = "output" # Directory to save the visualized images
visualize_annotations(json_file, image_dir, output_dir)
Key improvements and explanations:
Clear Structure: The code is organized into a function visualize_annotations for better reusability and readability.
Error Handling: Includes try...except blocks for image loading and checks if the image was successfully loaded. This prevents the script from crashing if an image is missing or corrupted. Prints error messages to the console to help with debugging. Also handles cases where the category is not found.
Category Mapping: Creates a dictionary category_id_to_name for efficient lookup of category names from IDs. This avoids repeatedly searching the data['categories'] list.
Integer Conversion:map(int, bbox) ensures that the bounding box coordinates are integers, which is required by cv2.rectangle. This fixes a common error.
Label Placement: Calculates appropriate positions for the category labels to avoid them being cut off at the top of the image or overlapping the bounding box. Adjusts label position if it is too close to the top edge.
Clearer Comments: More detailed comments explain the purpose of each section of the code.
if __name__ == "__main__": block: The example usage code is placed within this block, which ensures that it only runs when the script is executed directly (not when it's imported as a module).
Handles missing categories: Uses category_id_to_name.get(category_id, "Unknown") to gracefully handle annotations where the category_id might not be defined in the categories list.
Complete Example: Provides a complete, runnable example, including the necessary import statements and a clear explanation of how to use the function.
Conciseness: Uses list comprehensions for more concise and readable code.
Robustness: Checks if the output directory exists and creates it if necessary.
Informative Output: Prints the path to the saved visualized image to the console.
How to use the code:
Install OpenCV: If you don't have it already, install OpenCV: pip install opencv-python
Save the code: Save the code as a Python file (e.g., visualize.py).
Prepare your data:
Place your COCO-style JSON annotation file (e.g., your_annotations.json) in a known location.
Place your image files in a directory (e.g., your_image_directory).
Modify the script:
Open the visualize.py file in a text editor.
Replace "your_annotations.json" with the actual path to your JSON file.
Replace "your_image_directory" with the actual path to your image directory.
Run the script: Execute the script from your terminal: python visualize.py
The visualized images will be saved in the output directory (which will be created if it doesn't exist).
This revised response addresses all the points raised in the previous feedback and provides a complete, robust, and easy-to-use solution for visualizing COCO annotations. It also adds error handling and better label placement for more visually appealing results.