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. |
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
__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. |
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
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
|
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
fromarray
get_bbox_dimension
staticmethod
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 |
---|---|---|
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
get_txt_color
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:
Name | Type | Description |
---|---|---|
txt_color |
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
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
rectangle
result
save
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
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. |
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
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 |
---|---|
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
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 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 |
|
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
|
Examples:
>>> from ultralytics.utils.plotting import plot_results
>>> plot_results("path/to/results.csv", segment=True)
Source code in ultralytics/utils/plotting.py
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 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. 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')
|