Reference for ultralytics/engine/predictor.py
Note
This file is available at https://github.com/ultralytics/ultralytics/blob/main/ultralytics/engine/predictor.py. If you spot a problem please help fix it by contributing a Pull Request 🛠️. Thank you 🙏!
ultralytics.engine.predictor.BasePredictor
BasePredictor(
cfg=DEFAULT_CFG,
overrides: Optional[Dict[str, Any]] = None,
_callbacks: Optional[Dict[str, List[callable]]] = None,
)
A base class for creating predictors.
This class provides the foundation for prediction functionality, handling model setup, inference, and result processing across various input sources.
Attributes:
Name | Type | Description |
---|---|---|
args |
SimpleNamespace
|
Configuration for the predictor. |
save_dir |
Path
|
Directory to save results. |
done_warmup |
bool
|
Whether the predictor has finished setup. |
model |
Module
|
Model used for prediction. |
data |
dict
|
Data configuration. |
device |
device
|
Device used for prediction. |
dataset |
Dataset
|
Dataset used for prediction. |
vid_writer |
Dict[str, VideoWriter]
|
Dictionary of {save_path: video_writer} for saving video output. |
plotted_img |
ndarray
|
Last plotted image. |
source_type |
SimpleNamespace
|
Type of input source. |
seen |
int
|
Number of images processed. |
windows |
List[str]
|
List of window names for visualization. |
batch |
tuple
|
Current batch data. |
results |
List[Any]
|
Current batch results. |
transforms |
callable
|
Image transforms for classification. |
callbacks |
Dict[str, List[callable]]
|
Callback functions for different events. |
txt_path |
Path
|
Path to save text results. |
_lock |
Lock
|
Lock for thread-safe inference. |
Methods:
Name | Description |
---|---|
preprocess |
Prepare input image before inference. |
inference |
Run inference on a given image. |
postprocess |
Process raw predictions into structured results. |
predict_cli |
Run prediction for command line interface. |
setup_source |
Set up input source and inference mode. |
stream_inference |
Stream inference on input source. |
setup_model |
Initialize and configure the model. |
write_results |
Write inference results to files. |
save_predicted_images |
Save prediction visualizations. |
show |
Display results in a window. |
run_callbacks |
Execute registered callbacks for an event. |
add_callback |
Register a new callback function. |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cfg
|
str | dict
|
Path to a configuration file or a configuration dictionary. |
DEFAULT_CFG
|
overrides
|
dict
|
Configuration overrides. |
None
|
_callbacks
|
dict
|
Dictionary of callback functions. |
None
|
Source code in ultralytics/engine/predictor.py
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 |
|
__call__
__call__(source=None, model=None, stream: bool = False, *args, **kwargs)
Perform inference on an image or stream.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
source
|
str | Path | List[str] | List[Path] | List[ndarray] | ndarray | Tensor
|
Source for inference. |
None
|
model
|
str | Path | Module
|
Model for inference. |
None
|
stream
|
bool
|
Whether to stream the inference results. If True, returns a generator. |
False
|
*args
|
Any
|
Additional arguments for the inference method. |
()
|
**kwargs
|
Any
|
Additional keyword arguments for the inference method. |
{}
|
Returns:
Type | Description |
---|---|
List[Results] | generator
|
Results objects or generator of Results objects. |
Source code in ultralytics/engine/predictor.py
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 |
|
add_callback
add_callback(event: str, func: callable)
Add a callback function for a specific event.
Source code in ultralytics/engine/predictor.py
502 503 504 |
|
inference
inference(im: Tensor, *args, **kwargs)
Run inference on a given image using the specified model and arguments.
Source code in ultralytics/engine/predictor.py
175 176 177 178 179 180 181 182 |
|
postprocess
postprocess(preds, img, orig_imgs)
Post-process predictions for an image and return them.
Source code in ultralytics/engine/predictor.py
204 205 206 |
|
pre_transform
pre_transform(im: List[ndarray]) -> List[np.ndarray]
Pre-transform input image before inference.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
im
|
List[ndarray]
|
List of images with shape [(H, W, 3) x N]. |
required |
Returns:
Type | Description |
---|---|
List[ndarray]
|
List of transformed images. |
Source code in ultralytics/engine/predictor.py
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 |
|
predict_cli
predict_cli(source=None, model=None)
Method used for Command Line Interface (CLI) prediction.
This function is designed to run predictions using the CLI. It sets up the source and model, then processes the inputs in a streaming manner. This method ensures that no outputs accumulate in memory by consuming the generator without storing results.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
source
|
str | Path | List[str] | List[Path] | List[ndarray] | ndarray | Tensor
|
Source for inference. |
None
|
model
|
str | Path | Module
|
Model for inference. |
None
|
Note
Do not modify this function or remove the generator. The generator ensures that no outputs are accumulated in memory, which is critical for preventing memory issues during long-running predictions.
Source code in ultralytics/engine/predictor.py
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 |
|
preprocess
preprocess(im: Union[Tensor, List[ndarray]]) -> torch.Tensor
Prepare input image before inference.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
im
|
Tensor | List[ndarray]
|
Images of shape (N, 3, H, W) for tensor, [(H, W, 3) x N] for list. |
required |
Returns:
Type | Description |
---|---|
Tensor
|
Preprocessed image tensor of shape (N, 3, H, W). |
Source code in ultralytics/engine/predictor.py
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 |
|
run_callbacks
run_callbacks(event: str)
Run all registered callbacks for a specific event.
Source code in ultralytics/engine/predictor.py
497 498 499 500 |
|
save_predicted_images
save_predicted_images(save_path: str = '', frame: int = 0)
Save video predictions as mp4 or images as jpg at specified path.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
save_path
|
str
|
Path to save the results. |
''
|
frame
|
int
|
Frame number for video mode. |
0
|
Source code in ultralytics/engine/predictor.py
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 |
|
setup_model
setup_model(model, verbose: bool = True)
Initialize YOLO model with given parameters and set it to evaluation mode.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
str | Path | Module
|
Model to load or use. |
required |
verbose
|
bool
|
Whether to print verbose output. |
True
|
Source code in ultralytics/engine/predictor.py
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 |
|
setup_source
setup_source(source)
Set up source and inference mode.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
source
|
str | Path | List[str] | List[Path] | List[ndarray] | ndarray | Tensor
|
Source for inference. |
required |
Source code in ultralytics/engine/predictor.py
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 |
|
show
show(p: str = '')
Display an image in a window.
Source code in ultralytics/engine/predictor.py
487 488 489 490 491 492 493 494 495 |
|
stream_inference
stream_inference(source=None, model=None, *args, **kwargs)
Stream real-time inference on camera feed and save results to file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
source
|
str | Path | List[str] | List[Path] | List[ndarray] | ndarray | Tensor
|
Source for inference. |
None
|
model
|
str | Path | Module
|
Model for inference. |
None
|
*args
|
Any
|
Additional arguments for the inference method. |
()
|
**kwargs
|
Any
|
Additional keyword arguments for the inference method. |
{}
|
Yields:
Type | Description |
---|---|
Results
|
Results objects. |
Source code in ultralytics/engine/predictor.py
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 |
|
write_results
write_results(i: int, p: Path, im: Tensor, s: List[str]) -> str
Write inference results to a file or directory.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
i
|
int
|
Index of the current image in the batch. |
required |
p
|
Path
|
Path to the current image. |
required |
im
|
Tensor
|
Preprocessed image tensor. |
required |
s
|
List[str]
|
List of result strings. |
required |
Returns:
Type | Description |
---|---|
str
|
String with result information. |
Source code in ultralytics/engine/predictor.py
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 |
|