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
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[Tuple]
|
List of RGB color values. |
n |
int
|
The number of colors in the palette. |
pose_palette |
ndarray
|
A specific color palette array for pose estimation with dtype np.uint8. |
Examples:
>>> from ultralytics.utils.plotting import Colors
>>> colors = Colors()
>>> colors(5, True) # ff6fdd or (255, 111, 221)
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
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 |
|
__call__
__call__(i, bgr=False)
Convert hex color codes to RGB values.
Source code in ultralytics/utils/plotting.py
143 144 145 146 |
|
hex2rgb
staticmethod
hex2rgb(h)
Convert hex color codes to RGB values (i.e. default PIL order).
Source code in ultralytics/utils/plotting.py
148 149 150 151 |
|
ultralytics.utils.plotting.Annotator
Annotator(
im,
line_width=None,
font_size=None,
font="Arial.ttf",
pil=False,
example="abc",
)
Ultralytics Annotator for train/val mosaics and JPGs and predictions annotations.
Attributes:
Name | Type | Description |
---|---|---|
im |
Image or ndarray
|
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. |
dark_colors |
set
|
Set of colors considered dark for text contrast. |
light_colors |
set
|
Set of colors considered light for text contrast. |
Examples:
>>> from ultralytics.utils.plotting import Annotator
>>> im0 = cv2.imread("test.png")
>>> annotator = Annotator(im0, line_width=10)
Source code in ultralytics/utils/plotting.py
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 |
|
box_label
box_label(
box,
label="",
color=(128, 128, 128),
txt_color=(255, 255, 255),
rotated=False,
)
Draw a bounding box on an image with a given 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
|
Whether the task is oriented bounding box detection. |
False
|
Examples:
>>> from ultralytics.utils.plotting import Annotator
>>> im0 = cv2.imread("test.png")
>>> annotator = Annotator(im0, line_width=10)
>>> annotator.box_label(box=[10, 20, 30, 40], label="person")
Source code in ultralytics/utils/plotting.py
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 |
|
fromarray
fromarray(im)
Update self.im from a numpy array.
Source code in ultralytics/utils/plotting.py
476 477 478 479 |
|
get_bbox_dimension
staticmethod
get_bbox_dimension(bbox=None)
Calculate the dimensions and 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 |
---|---|---|
width |
float
|
Width of the bounding box. |
height |
float
|
Height of the bounding box. |
area |
float
|
Area enclosed by the bounding box. |
Examples:
>>> from ultralytics.utils.plotting import Annotator
>>> im0 = cv2.imread("test.png")
>>> annotator = Annotator(im0, line_width=10)
>>> annotator.get_bbox_dimension(bbox=[10, 20, 30, 40])
Source code in ultralytics/utils/plotting.py
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 |
|
get_txt_color
get_txt_color(color=(128, 128, 128), txt_color=(255, 255, 255))
Assign text color based on background color.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
color
|
tuple
|
The background color of the rectangle for text (B, G, R). |
(128, 128, 128)
|
txt_color
|
tuple
|
The color of the text (R, G, B). |
(255, 255, 255)
|
Returns:
Type | Description |
---|---|
tuple
|
Text color for label. |
Examples:
>>> from ultralytics.utils.plotting import Annotator
>>> im0 = cv2.imread("test.png")
>>> annotator = Annotator(im0, line_width=10)
>>> annotator.get_txt_color(color=(104, 31, 17)) # return (255, 255, 255)
Source code in ultralytics/utils/plotting.py
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 |
|
kpts
kpts(
kpts,
shape=(640, 640),
radius=None,
kpt_line=True,
conf_thres=0.25,
kpt_color=None,
)
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). |
(640, 640)
|
radius
|
int
|
Keypoint radius. |
None
|
kpt_line
|
bool
|
Draw lines between keypoints. |
True
|
conf_thres
|
float
|
Confidence threshold. |
0.25
|
kpt_color
|
tuple
|
Keypoint color (B, G, R). |
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
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 |
|
masks
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. |
False
|
Source code in ultralytics/utils/plotting.py
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 |
|
rectangle
rectangle(xy, fill=None, outline=None, width=1)
Add rectangle to image (PIL-only).
Source code in ultralytics/utils/plotting.py
441 442 443 |
|
result
result()
Return annotated image as array.
Source code in ultralytics/utils/plotting.py
481 482 483 |
|
save
save(filename='image.jpg')
Save the annotated image to 'filename'.
Source code in ultralytics/utils/plotting.py
496 497 498 |
|
show
show(title=None)
Show the annotated image.
Source code in ultralytics/utils/plotting.py
485 486 487 488 489 490 491 492 493 494 |
|
text
text(xy, text, txt_color=(255, 255, 255), anchor='top', box_color=())
Add text to an image using PIL or cv2.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
xy
|
List[int]
|
Top-left coordinates for text placement. |
required |
text
|
str
|
Text to be drawn. |
required |
txt_color
|
tuple
|
Text color (R, G, B). |
(255, 255, 255)
|
anchor
|
str
|
Text anchor position ('top' or 'bottom'). |
'top'
|
box_color
|
tuple
|
Box color (R, G, B, A) with optional alpha. |
()
|
Source code in ultralytics/utils/plotting.py
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 |
|
ultralytics.utils.plotting.plot_labels
plot_labels(boxes, cls, names=(), save_dir=Path(''), on_plot=None)
Plot training labels including class histograms and box statistics.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
boxes
|
ndarray
|
Bounding box coordinates in format [x, y, width, height]. |
required |
cls
|
ndarray
|
Class indices. |
required |
names
|
dict
|
Dictionary mapping class indices to class names. |
()
|
save_dir
|
Path
|
Directory to save the plot. |
Path('')
|
on_plot
|
Callable
|
Function to call after plot is saved. |
None
|
Source code in ultralytics/utils/plotting.py
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 |
|
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 | 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. |
Path('im.jpg')
|
gain
|
float
|
A multiplicative factor to increase the size of the bounding box. |
1.02
|
pad
|
int
|
The number of pixels to add to the width and height of the bounding box. |
10
|
square
|
bool
|
If True, the bounding box will be transformed into a square. |
False
|
BGR
|
bool
|
If True, the image will be saved in BGR format, otherwise in RGB. |
False
|
save
|
bool
|
If True, the cropped image will be saved to disk. |
True
|
Returns:
Type | Description |
---|---|
ndarray
|
The cropped image. |
Examples:
>>> from ultralytics.utils.plotting import save_one_box
>>> xyxy = [50, 50, 150, 150]
>>> im = cv2.imread("image.jpg")
>>> cropped_im = save_one_box(xyxy, im, file="cropped.jpg", square=True)
Source code in ultralytics/utils/plotting.py
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 |
|
ultralytics.utils.plotting.plot_images
plot_images(
images: Union[Tensor, ndarray],
batch_idx: Union[Tensor, ndarray],
cls: Union[Tensor, ndarray],
bboxes: Union[Tensor, ndarray] = np.zeros(0, dtype=np.float32),
confs: Optional[Union[Tensor, ndarray]] = None,
masks: Union[Tensor, ndarray] = np.zeros(0, dtype=np.uint8),
kpts: Union[Tensor, 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 |
---|---|
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
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 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 |
|
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. |
'path/to/results.csv'
|
dir
|
str
|
Directory where the CSV file is located if 'file' is not provided. |
''
|
segment
|
bool
|
Flag to indicate if the data is for segmentation. |
False
|
pose
|
bool
|
Flag to indicate if the data is for pose estimation. |
False
|
classify
|
bool
|
Flag to indicate if the data is for classification. |
False
|
on_plot
|
callable
|
Callback function to be executed after plotting. Takes filename as an argument. |
None
|
Examples:
>>> from ultralytics.utils.plotting import plot_results
>>> plot_results("path/to/results.csv", segment=True)
Source code in ultralytics/utils/plotting.py
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 |
|
ultralytics.utils.plotting.plt_color_scatter
plt_color_scatter(v, f, bins=20, cmap='viridis', alpha=0.8, edgecolors='none')
Plot 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. |
20
|
cmap
|
str
|
Colormap for the scatter plot. |
'viridis'
|
alpha
|
float
|
Alpha for the scatter plot. |
0.8
|
edgecolors
|
str
|
Edge colors for the scatter plot. |
'none'
|
Examples:
>>> v = np.random.rand(100)
>>> f = np.random.rand(100)
>>> plt_color_scatter(v, f)
Source code in ultralytics/utils/plotting.py
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 |
|
ultralytics.utils.plotting.plot_tune_results
plot_tune_results(csv_file='tune_results.csv')
Plot the evolution results stored in a '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. |
'tune_results.csv'
|
Examples:
>>> plot_tune_results("path/to/tune_results.csv")
Source code in ultralytics/utils/plotting.py
900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 |
|
ultralytics.utils.plotting.output_to_target
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
956 957 958 959 960 961 962 963 964 |
|
ultralytics.utils.plotting.output_to_rotated_target
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
967 968 969 970 971 972 973 974 975 |
|
ultralytics.utils.plotting.feature_visualization
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. |
32
|
save_dir
|
Path
|
Directory to save results. |
Path('runs/detect/exp')
|
Source code in ultralytics/utils/plotting.py
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 |
|