Reference for ultralytics/utils/plotting.py
Note
This file is available at https://github.com/ultralytics/ultralytics/blob/main/ultralytics/utils/plotting.py. If you spot a problem please help fix it by contributing a Pull Request 🛠️. Thank you 🙏!
ultralytics.utils.plotting.Colors
Ultralytics color palette https://docs.ultralytics.com/reference/utils/plotting/#ultralytics.utils.plotting.Colors.
This class provides methods to work with the Ultralytics color palette, including converting hex color codes to RGB values.
Attributes:
Name | Type | Description |
---|---|---|
palette |
list of tuple
|
List of RGB color values. |
n |
int
|
The number of colors in the palette. |
pose_palette |
ndarray
|
A specific color palette array with dtype np.uint8. |
Ultralytics Color Palette
Index | Color | HEX | RGB |
---|---|---|---|
0 | #042aff |
(4, 42, 255) | |
1 | #0bdbeb |
(11, 219, 235) | |
2 | #f3f3f3 |
(243, 243, 243) | |
3 | #00dfb7 |
(0, 223, 183) | |
4 | #111f68 |
(17, 31, 104) | |
5 | #ff6fdd |
(255, 111, 221) | |
6 | #ff444f |
(255, 68, 79) | |
7 | #cced00 |
(204, 237, 0) | |
8 | #00f344 |
(0, 243, 68) | |
9 | #bd00ff |
(189, 0, 255) | |
10 | #00b4ff |
(0, 180, 255) | |
11 | #dd00ba |
(221, 0, 186) | |
12 | #00ffff |
(0, 255, 255) | |
13 | #26c000 |
(38, 192, 0) | |
14 | #01ffb3 |
(1, 255, 179) | |
15 | #7d24ff |
(125, 36, 255) | |
16 | #7b0068 |
(123, 0, 104) | |
17 | #ff1b6c |
(255, 27, 108) | |
18 | #fc6d2f |
(252, 109, 47) | |
19 | #a2ff0b |
(162, 255, 11) |
Pose Color Palette
Index | Color | HEX | RGB |
---|---|---|---|
0 | #ff8000 |
(255, 128, 0) | |
1 | #ff9933 |
(255, 153, 51) | |
2 | #ffb266 |
(255, 178, 102) | |
3 | #e6e600 |
(230, 230, 0) | |
4 | #ff99ff |
(255, 153, 255) | |
5 | #99ccff |
(153, 204, 255) | |
6 | #ff66ff |
(255, 102, 255) | |
7 | #ff33ff |
(255, 51, 255) | |
8 | #66b2ff |
(102, 178, 255) | |
9 | #3399ff |
(51, 153, 255) | |
10 | #ff9999 |
(255, 153, 153) | |
11 | #ff6666 |
(255, 102, 102) | |
12 | #ff3333 |
(255, 51, 51) | |
13 | #99ff99 |
(153, 255, 153) | |
14 | #66ff66 |
(102, 255, 102) | |
15 | #33ff33 |
(51, 255, 51) | |
16 | #00ff00 |
(0, 255, 0) | |
17 | #0000ff |
(0, 0, 255) | |
18 | #ff0000 |
(255, 0, 0) | |
19 | #ffffff |
(255, 255, 255) |
Ultralytics Brand Colors
For Ultralytics brand colors see https://www.ultralytics.com/brand. Please use the official Ultralytics colors for all marketing materials.
Source code in ultralytics/utils/plotting.py
__call__
hex2rgb
staticmethod
ultralytics.utils.plotting.Annotator
Ultralytics Annotator for train/val mosaics and JPGs and predictions annotations.
Attributes:
Name | Type | Description |
---|---|---|
im |
Image.Image or numpy array
|
The image to annotate. |
pil |
bool
|
Whether to use PIL or cv2 for drawing annotations. |
font |
truetype or load_default
|
Font used for text annotations. |
lw |
float
|
Line width for drawing. |
skeleton |
List[List[int]]
|
Skeleton structure for keypoints. |
limb_color |
List[int]
|
Color palette for limbs. |
kpt_color |
List[int]
|
Color palette for keypoints. |
Source code in ultralytics/utils/plotting.py
box_label
Draws a bounding box to image with label.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
box
|
tuple
|
The bounding box coordinates (x1, y1, x2, y2). |
required |
label
|
str
|
The text label to be displayed. |
''
|
color
|
tuple
|
The background color of the rectangle (B, G, R). |
(128, 128, 128)
|
txt_color
|
tuple
|
The color of the text (R, G, B). |
(255, 255, 255)
|
rotated
|
bool
|
Variable used to check if task is OBB |
False
|
Source code in ultralytics/utils/plotting.py
circle_label
Draws a label with a background circle centered within a given bounding box.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
box
|
tuple
|
The bounding box coordinates (x1, y1, x2, y2). |
required |
label
|
str
|
The text label to be displayed. |
''
|
color
|
tuple
|
The background color of the rectangle (B, G, R). |
(128, 128, 128)
|
txt_color
|
tuple
|
The color of the text (R, G, B). |
(255, 255, 255)
|
margin
|
int
|
The margin between the text and the rectangle border. |
2
|
Source code in ultralytics/utils/plotting.py
display_analytics
Display the overall statistics for parking lots.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
im0
|
ndarray
|
inference image |
required |
text
|
dict
|
labels dictionary |
required |
txt_color
|
tuple
|
display color for text foreground |
required |
bg_color
|
tuple
|
display color for text background |
required |
margin
|
int
|
gap between text and rectangle for better display |
required |
Source code in ultralytics/utils/plotting.py
display_objects_labels
Display the bounding boxes labels in parking management app.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
im0
|
ndarray
|
inference image |
required |
text
|
str
|
object/class name |
required |
txt_color
|
tuple
|
display color for text foreground |
required |
bg_color
|
tuple
|
display color for text background |
required |
x_center
|
float
|
x position center point for bounding box |
required |
y_center
|
float
|
y position center point for bounding box |
required |
margin
|
int
|
gap between text and rectangle for better display |
required |
Source code in ultralytics/utils/plotting.py
draw_centroid_and_tracks
Draw centroid point and track trails.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
track
|
list
|
object tracking points for trails display |
required |
color
|
tuple
|
tracks line color |
(255, 0, 255)
|
track_thickness
|
int
|
track line thickness value |
2
|
Source code in ultralytics/utils/plotting.py
draw_region
Draw region line.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
reg_pts
|
list
|
Region Points (for line 2 points, for region 4 points) |
None
|
color
|
tuple
|
Region Color value |
(0, 255, 0)
|
thickness
|
int
|
Region area thickness value |
5
|
Source code in ultralytics/utils/plotting.py
draw_specific_points
Draw specific keypoints for gym steps counting.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
keypoints
|
list
|
Keypoints data to be plotted. |
required |
indices
|
list
|
Keypoint indices to be plotted. Defaults to [2, 5, 7]. |
None
|
radius
|
int
|
Keypoint radius. Defaults to 2. |
2
|
conf_thres
|
float
|
Confidence threshold for keypoints. Defaults to 0.25. |
0.25
|
Returns:
Type | Description |
---|---|
ndarray
|
Image with drawn keypoints. |
Note
Keypoint format: [x, y] or [x, y, confidence]. Modifies self.im in-place.
Source code in ultralytics/utils/plotting.py
estimate_pose_angle
staticmethod
Calculate the pose angle for object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
a
|
float)
|
The value of pose point a |
required |
b
|
float
|
The value of pose point b |
required |
c
|
float
|
The value o pose point c |
required |
Returns:
Name | Type | Description |
---|---|---|
angle |
degree
|
Degree value of angle between three points |
Source code in ultralytics/utils/plotting.py
fromarray
get_bbox_dimension
Calculate the area of a bounding box.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
bbox
|
tuple
|
Bounding box coordinates in the format (x_min, y_min, x_max, y_max). |
None
|
Returns:
Name | Type | Description |
---|---|---|
angle |
degree
|
Degree value of angle between three points |
Source code in ultralytics/utils/plotting.py
get_txt_color
Assign text color based on background color.
Source code in ultralytics/utils/plotting.py
kpts
Plot keypoints on the image.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
kpts
|
Tensor
|
Keypoints, shape [17, 3] (x, y, confidence). |
required |
shape
|
tuple
|
Image shape (h, w). Defaults to (640, 640). |
(640, 640)
|
radius
|
int
|
Keypoint radius. Defaults to 5. |
None
|
kpt_line
|
bool
|
Draw lines between keypoints. Defaults to True. |
True
|
conf_thres
|
float
|
Confidence threshold. Defaults to 0.25. |
0.25
|
kpt_color
|
tuple
|
Keypoint color (B, G, R). Defaults to None. |
None
|
Note
kpt_line=True
currently only supports human pose plotting.- Modifies self.im in-place.
- If self.pil is True, converts image to numpy array and back to PIL.
Source code in ultralytics/utils/plotting.py
masks
Plot masks on image.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
masks
|
tensor
|
Predicted masks on cuda, shape: [n, h, w] |
required |
colors
|
List[List[Int]]
|
Colors for predicted masks, [[r, g, b] * n] |
required |
im_gpu
|
tensor
|
Image is in cuda, shape: [3, h, w], range: [0, 1] |
required |
alpha
|
float
|
Mask transparency: 0.0 fully transparent, 1.0 opaque |
0.5
|
retina_masks
|
bool
|
Whether to use high resolution masks or not. Defaults to False. |
False
|
Source code in ultralytics/utils/plotting.py
plot_angle_and_count_and_stage
plot_angle_and_count_and_stage(
angle_text,
count_text,
stage_text,
center_kpt,
color=(104, 31, 17),
txt_color=(255, 255, 255),
)
Plot the pose angle, count value, and step stage.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
angle_text
|
str
|
Angle value for workout monitoring |
required |
count_text
|
str
|
Counts value for workout monitoring |
required |
stage_text
|
str
|
Stage decision for workout monitoring |
required |
center_kpt
|
list
|
Centroid pose index for workout monitoring |
required |
color
|
tuple
|
Text background color |
(104, 31, 17)
|
txt_color
|
tuple
|
Text foreground color |
(255, 255, 255)
|
Source code in ultralytics/utils/plotting.py
plot_distance_and_line
plot_distance_and_line(
pixels_distance,
centroids,
line_color=(104, 31, 17),
centroid_color=(255, 0, 255),
)
Plot the distance and line on frame.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
pixels_distance
|
float
|
Pixels distance between two bbox centroids. |
required |
centroids
|
list
|
Bounding box centroids data. |
required |
line_color
|
tuple
|
Distance line color. |
(104, 31, 17)
|
centroid_color
|
tuple
|
Bounding box centroid color. |
(255, 0, 255)
|
Source code in ultralytics/utils/plotting.py
plot_workout_information
Draw text with a background on the image.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
display_text
|
str
|
The text to be displayed. |
required |
position
|
tuple
|
Coordinates (x, y) on the image where the text will be placed. |
required |
color
|
tuple
|
Text background color |
(104, 31, 17)
|
txt_color
|
tuple
|
Text foreground color |
(255, 255, 255)
|
Source code in ultralytics/utils/plotting.py
queue_counts_display
Displays queue counts on an image centered at the points with customizable font size and colors.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
label
|
str
|
queue counts label |
required |
points
|
tuple
|
region points for center point calculation to display text |
None
|
region_color
|
tuple
|
RGB queue region color. |
(255, 255, 255)
|
txt_color
|
tuple
|
RGB text display color. |
(0, 0, 0)
|
Source code in ultralytics/utils/plotting.py
rectangle
result
save
seg_bbox
Function for drawing segmented object in bounding box shape.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
mask
|
ndarray
|
A 2D array of shape (N, 2) containing the contour points of the segmented object. |
required |
mask_color
|
tuple
|
RGB color for the contour and label background. |
(255, 0, 255)
|
label
|
str
|
Text label for the object. If None, no label is drawn. |
None
|
txt_color
|
tuple
|
RGB color for the label text. |
(255, 255, 255)
|
Source code in ultralytics/utils/plotting.py
show
Show the annotated image.
Source code in ultralytics/utils/plotting.py
text
Adds text to an image using PIL or cv2.
Source code in ultralytics/utils/plotting.py
text_label
Draws a label with a background rectangle centered within a given bounding box.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
box
|
tuple
|
The bounding box coordinates (x1, y1, x2, y2). |
required |
label
|
str
|
The text label to be displayed. |
''
|
color
|
tuple
|
The background color of the rectangle (B, G, R). |
(128, 128, 128)
|
txt_color
|
tuple
|
The color of the text (R, G, B). |
(255, 255, 255)
|
margin
|
int
|
The margin between the text and the rectangle border. |
5
|
Source code in ultralytics/utils/plotting.py
visioneye
Function for pinpoint human-vision eye mapping and plotting.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
box
|
list
|
Bounding box coordinates |
required |
center_point
|
tuple
|
center point for vision eye view |
required |
color
|
tuple
|
object centroid and line color value |
(235, 219, 11)
|
pin_color
|
tuple
|
visioneye point color value |
(255, 0, 255)
|
Source code in ultralytics/utils/plotting.py
ultralytics.utils.plotting.plot_labels
Plot training labels including class histograms and box statistics.
Source code in ultralytics/utils/plotting.py
ultralytics.utils.plotting.save_one_box
save_one_box(
xyxy,
im,
file=Path("im.jpg"),
gain=1.02,
pad=10,
square=False,
BGR=False,
save=True,
)
Save image crop as {file} with crop size multiple {gain} and {pad} pixels. Save and/or return crop.
This function takes a bounding box and an image, and then saves a cropped portion of the image according to the bounding box. Optionally, the crop can be squared, and the function allows for gain and padding adjustments to the bounding box.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
xyxy
|
Tensor or list
|
A tensor or list representing the bounding box in xyxy format. |
required |
im
|
ndarray
|
The input image. |
required |
file
|
Path
|
The path where the cropped image will be saved. Defaults to 'im.jpg'. |
Path('im.jpg')
|
gain
|
float
|
A multiplicative factor to increase the size of the bounding box. Defaults to 1.02. |
1.02
|
pad
|
int
|
The number of pixels to add to the width and height of the bounding box. Defaults to 10. |
10
|
square
|
bool
|
If True, the bounding box will be transformed into a square. Defaults to False. |
False
|
BGR
|
bool
|
If True, the image will be saved in BGR format, otherwise in RGB. Defaults to False. |
False
|
save
|
bool
|
If True, the cropped image will be saved to disk. Defaults to True. |
True
|
Returns:
Type | Description |
---|---|
ndarray
|
The cropped image. |
Example
Source code in ultralytics/utils/plotting.py
ultralytics.utils.plotting.plot_images
plot_images(
images: Union[torch.Tensor, np.ndarray],
batch_idx: Union[torch.Tensor, np.ndarray],
cls: Union[torch.Tensor, np.ndarray],
bboxes: Union[torch.Tensor, np.ndarray] = np.zeros(0, dtype=np.float32),
confs: Optional[Union[torch.Tensor, np.ndarray]] = None,
masks: Union[torch.Tensor, np.ndarray] = np.zeros(0, dtype=np.uint8),
kpts: Union[torch.Tensor, np.ndarray] = np.zeros((0, 51), dtype=np.float32),
paths: Optional[List[str]] = None,
fname: str = "images.jpg",
names: Optional[Dict[int, str]] = None,
on_plot: Optional[Callable] = None,
max_size: int = 1920,
max_subplots: int = 16,
save: bool = True,
conf_thres: float = 0.25,
) -> Optional[np.ndarray]
Plot image grid with labels, bounding boxes, masks, and keypoints.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
images
|
Union[Tensor, ndarray]
|
Batch of images to plot. Shape: (batch_size, channels, height, width). |
required |
batch_idx
|
Union[Tensor, ndarray]
|
Batch indices for each detection. Shape: (num_detections,). |
required |
cls
|
Union[Tensor, ndarray]
|
Class labels for each detection. Shape: (num_detections,). |
required |
bboxes
|
Union[Tensor, ndarray]
|
Bounding boxes for each detection. Shape: (num_detections, 4) or (num_detections, 5) for rotated boxes. |
zeros(0, dtype=float32)
|
confs
|
Optional[Union[Tensor, ndarray]]
|
Confidence scores for each detection. Shape: (num_detections,). |
None
|
masks
|
Union[Tensor, ndarray]
|
Instance segmentation masks. Shape: (num_detections, height, width) or (1, height, width). |
zeros(0, dtype=uint8)
|
kpts
|
Union[Tensor, ndarray]
|
Keypoints for each detection. Shape: (num_detections, 51). |
zeros((0, 51), dtype=float32)
|
paths
|
Optional[List[str]]
|
List of file paths for each image in the batch. |
None
|
fname
|
str
|
Output filename for the plotted image grid. |
'images.jpg'
|
names
|
Optional[Dict[int, str]]
|
Dictionary mapping class indices to class names. |
None
|
on_plot
|
Optional[Callable]
|
Optional callback function to be called after saving the plot. |
None
|
max_size
|
int
|
Maximum size of the output image grid. |
1920
|
max_subplots
|
int
|
Maximum number of subplots in the image grid. |
16
|
save
|
bool
|
Whether to save the plotted image grid to a file. |
True
|
conf_thres
|
float
|
Confidence threshold for displaying detections. |
0.25
|
Returns:
Type | Description |
---|---|
Optional[ndarray]
|
np.ndarray: Plotted image grid as a numpy array if save is False, None otherwise. |
Note
This function supports both tensor and numpy array inputs. It will automatically convert tensor inputs to numpy arrays for processing.
Source code in ultralytics/utils/plotting.py
962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 |
|
ultralytics.utils.plotting.plot_results
plot_results(
file="path/to/results.csv",
dir="",
segment=False,
pose=False,
classify=False,
on_plot=None,
)
Plot training results from a results CSV file. The function supports various types of data including segmentation, pose estimation, and classification. Plots are saved as 'results.png' in the directory where the CSV is located.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
file
|
str
|
Path to the CSV file containing the training results. Defaults to 'path/to/results.csv'. |
'path/to/results.csv'
|
dir
|
str
|
Directory where the CSV file is located if 'file' is not provided. Defaults to ''. |
''
|
segment
|
bool
|
Flag to indicate if the data is for segmentation. Defaults to False. |
False
|
pose
|
bool
|
Flag to indicate if the data is for pose estimation. Defaults to False. |
False
|
classify
|
bool
|
Flag to indicate if the data is for classification. Defaults to False. |
False
|
on_plot
|
callable
|
Callback function to be executed after plotting. Takes filename as an argument. Defaults to None. |
None
|
Example
Source code in ultralytics/utils/plotting.py
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 |
|
ultralytics.utils.plotting.plt_color_scatter
Plots a scatter plot with points colored based on a 2D histogram.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
v
|
array - like
|
Values for the x-axis. |
required |
f
|
array - like
|
Values for the y-axis. |
required |
bins
|
int
|
Number of bins for the histogram. Defaults to 20. |
20
|
cmap
|
str
|
Colormap for the scatter plot. Defaults to 'viridis'. |
'viridis'
|
alpha
|
float
|
Alpha for the scatter plot. Defaults to 0.8. |
0.8
|
edgecolors
|
str
|
Edge colors for the scatter plot. Defaults to 'none'. |
'none'
|
Examples:
Source code in ultralytics/utils/plotting.py
ultralytics.utils.plotting.plot_tune_results
Plot the evolution results stored in an 'tune_results.csv' file. The function generates a scatter plot for each key in the CSV, color-coded based on fitness scores. The best-performing configurations are highlighted on the plots.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
csv_file
|
str
|
Path to the CSV file containing the tuning results. Defaults to 'tune_results.csv'. |
'tune_results.csv'
|
Examples:
Source code in ultralytics/utils/plotting.py
ultralytics.utils.plotting.output_to_target
Convert model output to target format [batch_id, class_id, x, y, w, h, conf] for plotting.
Source code in ultralytics/utils/plotting.py
ultralytics.utils.plotting.output_to_rotated_target
Convert model output to target format [batch_id, class_id, x, y, w, h, conf] for plotting.
Source code in ultralytics/utils/plotting.py
ultralytics.utils.plotting.feature_visualization
Visualize feature maps of a given model module during inference.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Tensor
|
Features to be visualized. |
required |
module_type
|
str
|
Module type. |
required |
stage
|
int
|
Module stage within the model. |
required |
n
|
int
|
Maximum number of feature maps to plot. Defaults to 32. |
32
|
save_dir
|
Path
|
Directory to save results. Defaults to Path('runs/detect/exp'). |
Path('runs/detect/exp')
|