Coding-图像处理-在图片上显示矩形框

显示矩形框

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

import cv2

def draw_boxes_on_image(image_path, label_path, class_dict, output_path=None):
"""
Reads an image and its corresponding YOLO format label file, then draws the boxes on the image.

:param image_path: Path to the image file.
:param label_path: Path to the YOLO format label file.
:param class_dict: Dictionary mapping class names to their ids.
:param output_path: Optional path to save the annotated image.
:return: Annotated image as numpy array.
"""
# Load the image
image = cv2.imread(image_path)
height, width, _ = image.shape

# Read the label file
with open(label_path, 'r') as f:
lines = f.readlines()

# Draw boxes for each object in the label file
for line in lines:
parts = line.strip().split()
class_id = int(parts[0])
x_center, y_center, box_width, box_height = map(float, parts[1:])

# Convert normalized coordinates back to pixel values
x_min = int((x_center - box_width / 2) * width)
y_min = int((y_center - box_height / 2) * height)
x_max = int((x_center + box_width / 2) * width)
y_max = int((y_center + box_height / 2) * height)

# Get the class name
class_name = next(key for key, value in class_dict.items() if value == class_id)

# Draw the bounding box
cv2.rectangle(image, (x_min, y_min), (x_max, y_max), (0, 255, 0), 2)

# Add the class name on top of the box
cv2.putText(image, class_name, (x_min, y_min - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)

# Optionally save the image
if output_path is not None:
cv2.imwrite(output_path, image)

return image

# Example usage:
class_dict = {'dog': 0, 'cat': 1}
image_path = 'jpg\\1.jpg'
label_path = 'txt\\1.txt'
output_path = 'annotated_image.jpg'
annotated_image = draw_boxes_on_image(image_path, label_path, class_dict, output_path)