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 default color palette https://ultralytics.com/.
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. |
Source code in ultralytics/utils/plotting.py
__call__(i, bgr=False)
__init__()
Initialize colors as hex = matplotlib.colors.TABLEAU_COLORS.values().
Source code in ultralytics/utils/plotting.py
hex2rgb(h)
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
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 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 |
|
__init__(im, line_width=None, font_size=None, font='Arial.ttf', pil=False, example='abc')
Initialize the Annotator class with image and line width along with color palette for keypoints and limbs.
Source code in ultralytics/utils/plotting.py
box_label(box, label='', color=(128, 128, 128), txt_color=(255, 255, 255), rotated=False)
Add one xyxy box to image with label.
Source code in ultralytics/utils/plotting.py
display_analytics(im0, text, txt_color, bg_color, margin)
Display the overall statistics for parking lots Args: im0 (ndarray): inference image text (dict): labels dictionary txt_color (bgr color): display color for text foreground bg_color (bgr color): display color for text background margin (int): gap between text and rectangle for better display
Source code in ultralytics/utils/plotting.py
display_objects_labels(im0, text, txt_color, bg_color, x_center, y_center, margin)
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 |
bgr color
|
display color for text foreground |
required |
bg_color |
bgr color
|
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(track, color=(255, 0, 255), track_thickness=2)
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(reg_pts=None, color=(0, 255, 0), thickness=5)
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(keypoints, indices=[2, 5, 7], shape=(640, 640), radius=2, conf_thres=0.25)
Draw specific keypoints for gym steps counting.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
keypoints |
list
|
list of keypoints data to be plotted |
required |
indices |
list
|
keypoints ids list to be plotted |
[2, 5, 7]
|
shape |
tuple
|
imgsz for model inference |
(640, 640)
|
radius |
int
|
Keypoint radius value |
2
|
Source code in ultralytics/utils/plotting.py
estimate_pose_angle(a, b, c)
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(im)
get_bbox_dimension(bbox=None)
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
kpts(kpts, shape=(640, 640), radius=5, kpt_line=True, conf_thres=0.25)
Plot keypoints on the image.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
kpts |
tensor
|
Predicted keypoints with shape [17, 3]. Each keypoint has (x, y, confidence). |
required |
shape |
tuple
|
Image shape as a tuple (h, w), where h is the height and w is the width. |
(640, 640)
|
radius |
int
|
Radius of the drawn keypoints. Default is 5. |
5
|
kpt_line |
bool
|
If True, the function will draw lines connecting keypoints for human pose. Default is True. |
True
|
Note
kpt_line=True
currently only supports human pose plotting.
Source code in ultralytics/utils/plotting.py
masks(masks, colors, im_gpu, alpha=0.5, retina_masks=False)
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(angle_text, count_text, stage_text, center_kpt, line_thickness=2)
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 |
int
|
centroid pose index for workout monitoring |
required |
line_thickness |
int
|
thickness for text display |
2
|
Source code in ultralytics/utils/plotting.py
plot_distance_and_line(distance_m, distance_mm, centroids, line_color, centroid_color)
Plot the distance and line on frame.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
distance_m |
float
|
Distance between two bbox centroids in meters. |
required |
distance_mm |
float
|
Distance between two bbox centroids in millimeters. |
required |
centroids |
list
|
Bounding box centroids data. |
required |
line_color |
RGB
|
Distance line color. |
required |
centroid_color |
RGB
|
Bounding box centroid color. |
required |
Source code in ultralytics/utils/plotting.py
queue_counts_display(label, points=None, region_color=(255, 255, 255), txt_color=(0, 0, 0), fontsize=0.7)
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 |
RGB
|
queue region color |
(255, 255, 255)
|
txt_color |
RGB
|
text display color |
(0, 0, 0)
|
fontsize |
float
|
text fontsize |
0.7
|
Source code in ultralytics/utils/plotting.py
rectangle(xy, fill=None, outline=None, width=1)
result()
save(filename='image.jpg')
seg_bbox(mask, mask_color=(255, 0, 255), det_label=None, track_label=None)
Function for drawing segmented object in bounding box shape.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
mask |
list
|
masks data list for instance segmentation area plotting |
required |
mask_color |
tuple
|
mask foreground color |
(255, 0, 255)
|
det_label |
str
|
Detection label text |
None
|
track_label |
str
|
Tracking label text |
None
|
Source code in ultralytics/utils/plotting.py
show(title=None)
text(xy, text, txt_color=(255, 255, 255), anchor='top', box_style=False)
Adds text to an image using PIL or cv2.
Source code in ultralytics/utils/plotting.py
visioneye(box, center_point, color=(235, 219, 11), pin_color=(255, 0, 255), thickness=2, pins_radius=10)
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)
|
thickness |
int
|
int value for line thickness |
2
|
pins_radius |
int
|
visioneye point radius value |
10
|
Source code in ultralytics/utils/plotting.py
ultralytics.utils.plotting.plot_labels(boxes, cls, names=(), save_dir=Path(''), on_plot=None)
Plot training labels including class histograms and box statistics.
Source code in ultralytics/utils/plotting.py
ultralytics.utils.plotting.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(images, batch_idx, cls, bboxes=np.zeros(0, dtype=np.float32), confs=None, masks=np.zeros(0, dtype=np.uint8), kpts=np.zeros((0, 51), dtype=np.float32), paths=None, fname='images.jpg', names=None, on_plot=None, max_subplots=16, save=True, conf_thres=0.25)
Plot image grid with labels.
Source code in ultralytics/utils/plotting.py
781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 |
|
ultralytics.utils.plotting.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
ultralytics.utils.plotting.plt_color_scatter(v, f, bins=20, cmap='viridis', alpha=0.8, edgecolors='none')
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(csv_file='tune_results.csv')
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(output, max_det=300)
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(output, max_det=300)
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(x, module_type, stage, n=32, save_dir=Path('runs/detect/exp'))
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')
|