API Reference¶
Auto-generated documentation from Python docstrings using mkdocstrings.
Note
Some modules may have limited docstring coverage. This reference will improve over time.
Project Management¶
castle.utils.project_manager
¶
Project management utilities for Castle AI.
create_project(storage_path, project_name)
¶
Create a new project with config file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
storage_path
|
Path to the storage directory |
required | |
project_name
|
Name of the new project |
required |
Raises:
| Type | Description |
|---|---|
FileExistsError
|
If project already exists |
Source code in castle/utils/project_manager.py
delete_project(storage_path, project_name)
¶
Delete a project directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
storage_path
|
Path to the storage directory |
required | |
project_name
|
Name of the project to delete |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
True if deletion was successful, False otherwise |
Source code in castle/utils/project_manager.py
generate_default_project_name(custom_name='')
¶
Generate a default project name with timestamp.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
custom_name
|
Optional custom name to use |
''
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
Project name |
Source code in castle/utils/project_manager.py
initialize_storage(root_path)
¶
Initialize storage directory if it doesn't exist.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
root_path
|
Path to the root storage directory |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
Normalized storage path with trailing separator |
Source code in castle/utils/project_manager.py
list_projects(storage_path)
¶
List all project directories in the storage path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
storage_path
|
Path to the storage directory |
required |
Returns:
| Type | Description |
|---|---|
|
List of project directory names, sorted if more than one exists |
Source code in castle/utils/project_manager.py
Video I/O¶
castle.utils.video_io
¶
影片輸入/輸出工具模組
該模組提供了影片讀取、寫入和字幕生成的功能。 相較於使用 OpenCV,新版本使用 av 庫提供更高效的影片處理能力。
主要功能: - 高效的影片讀取和隨機存取 - 影片編碼和寫入 - 字幕檔案生成 (SRT, WebVTT) - 自動資源管理和錯誤處理
SubtitleGenerator
¶
字幕生成器
提供字幕檔案的建立和儲存功能,支援多種字幕格式。 可用於為影片自動生成時間同步的字幕檔案。
支援格式: - SRT (SubRip Text) - WebVTT (Web Video Text Tracks)
範例用法: generator = SubtitleGenerator() generator.add_subtitle(0.0, 5.0, "第一段字幕") generator.add_subtitle(5.0, 10.0, "第二段字幕") generator.save("output.srt", format="srt")
Source code in castle/utils/video_io.py
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 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 | |
__init__()
¶
add_subtitle(start_time, end_time, text)
¶
添加字幕項目
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start_time
|
float
|
開始時間(秒) |
required |
end_time
|
float
|
結束時間(秒) |
required |
text
|
str
|
字幕文字內容 |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
當時間參數無效時 |
Source code in castle/utils/video_io.py
clear()
¶
get_subtitle_count()
¶
get_total_duration()
¶
獲取字幕總時長
Returns:
| Type | Description |
|---|---|
float
|
總時長(秒),如果沒有字幕則返回 0 |
save(output_path, format='srt')
¶
儲存字幕檔案
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_path
|
Union[str, Path]
|
輸出檔案路徑 |
required |
format
|
str
|
字幕格式 ('srt', 'vtt') |
'srt'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
當格式不支援時 |
IOError
|
當檔案寫入失敗時 |
Source code in castle/utils/video_io.py
VideoIO
¶
影片輸入/輸出處理器
提供靜態方法來處理影片的讀取、寫入和基本操作。 使用 av 庫實現高效的影片處理功能。
Source code in castle/utils/video_io.py
get_frame(video, frame_idx)
staticmethod
¶
從 VideoReader 獲取指定影格
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
video
|
VideoReader
|
VideoReader 實例 |
required |
frame_idx
|
int
|
影格索引 |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
影格陣列 (RGB) |
load_video(video_path)
staticmethod
¶
載入影片檔案
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
video_path
|
Union[str, Path]
|
影片檔案路徑 |
required |
Returns:
| Type | Description |
|---|---|
VideoReader
|
VideoReader 物件 |
Raises:
| Type | Description |
|---|---|
VideoIOError
|
當影片載入失敗時 |
Source code in castle/utils/video_io.py
save_video(frames, output_path, fps=30.0, crf=15, codec='libx264')
staticmethod
¶
儲存影片
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frames
|
List[ndarray]
|
影格陣列列表 |
required |
output_path
|
Union[str, Path]
|
輸出檔案路徑 |
required |
fps
|
float
|
幀率 |
30.0
|
crf
|
int
|
壓縮品質 (0-51, 數值越小品質越好) |
15
|
codec
|
str
|
編碼器名稱 |
'libx264'
|
Raises:
| Type | Description |
|---|---|
VideoIOError
|
當影片儲存失敗時 |
ValueError
|
當輸入資料無效時 |
Source code in castle/utils/video_io.py
VideoIOError
¶
VideoInfo
dataclass
¶
影片資訊資料類別
用於儲存影片的基本屬性資訊,包括路徑、幀率、影格數量、尺寸和時長等。
Source code in castle/utils/video_io.py
VideoReader
¶
影片讀取器
使用 av 庫實現高效的影片讀取功能,支援隨機存取和批次讀取。 相較於傳統的 OpenCV 方法,提供更好的效能和準確性。
主要功能: - 高效的隨機影格存取 - 自動資源管理 - 影格快取機制 - 批次讀取支援
範例用法: # 基本使用 reader = VideoReader("video.mp4") frame = reader.get_frame(100) # 獲取第 100 幀
# 作為 context manager 使用
with VideoReader("video.mp4") as reader:
for i, frame in reader.iterate_frames(0, 100, 5):
process_frame(frame)
Source code in castle/utils/video_io.py
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 | |
__del__()
¶
__enter__()
¶
__exit__(exc_type, exc_val, exc_tb)
¶
__getitem__(frame_idx)
¶
__init__(video_path)
¶
初始化影片讀取器
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
video_path
|
Union[str, Path]
|
影片檔案路徑 |
required |
Raises:
| Type | Description |
|---|---|
VideoIOError
|
當影片初始化失敗時 |
FileNotFoundError
|
當影片檔案不存在時 |
Source code in castle/utils/video_io.py
__len__()
¶
clear_cache()
¶
close()
¶
關閉影片讀取器並釋放資源
Source code in castle/utils/video_io.py
get_batch_frames(indices)
¶
批次獲取影格
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
indices
|
List[int]
|
影格索引列表 |
required |
Returns:
| Type | Description |
|---|---|
List[ndarray]
|
影格陣列列表 |
Raises:
| Type | Description |
|---|---|
ValueError
|
當索引列表為空時 |
Source code in castle/utils/video_io.py
get_frame(frame_idx)
¶
獲取指定影格
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame_idx
|
int
|
影格索引 |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
影格陣列 (RGB 格式) |
Raises:
| Type | Description |
|---|---|
IndexError
|
當影格索引超出範圍時 |
RuntimeError
|
當讀取失敗時 |
Source code in castle/utils/video_io.py
get_info()
¶
獲取影片資訊
Returns:
| Type | Description |
|---|---|
VideoInfo
|
VideoInfo 實例,包含影片的基本資訊 |
Source code in castle/utils/video_io.py
iterate_frames(start=0, end=None, step=1)
¶
迭代影片影格
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start
|
int
|
起始影格索引 |
0
|
end
|
Optional[int]
|
結束影格索引(不包含),None 表示到影片結尾 |
None
|
step
|
int
|
步長 |
1
|
Yields:
| Type | Description |
|---|---|
Tuple[int, ndarray]
|
(影格索引, 影格陣列) 元組 |
Raises:
| Type | Description |
|---|---|
ValueError
|
當參數無效時 |
Source code in castle/utils/video_io.py
VideoWriter
¶
影片寫入器
使用 av 庫實現高效的影片編碼和寫入功能。 基於提供的 WriteArray 範例實現,支援多種編碼器和品質設定。
範例用法: # 基本使用 writer = VideoWriter("output.mp4", fps=30.0) for frame in frames: writer.write_frame(frame) writer.close()
# 作為 context manager 使用
with VideoWriter("output.mp4", fps=30.0, crf=20) as writer:
for frame in frames:
writer.write_frame(frame)
Source code in castle/utils/video_io.py
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 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 | |
__del__()
¶
__enter__()
¶
__exit__(exc_type, exc_val, exc_tb)
¶
__init__(output_path, fps=30.0, crf=15, codec='libx264')
¶
初始化影片寫入器
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_path
|
Union[str, Path]
|
輸出檔案路徑 |
required |
fps
|
float
|
幀率 |
30.0
|
crf
|
int
|
壓縮品質 (0-51, 數值越小品質越好,檔案越大) |
15
|
codec
|
str
|
編碼器名稱 |
'libx264'
|
Raises:
| Type | Description |
|---|---|
VideoIOError
|
當初始化失敗時 |
Source code in castle/utils/video_io.py
append(frame)
¶
追加影格(向後相容性方法)
這是為了與舊版本 WriteArray 相容而提供的方法。 內部調用 write_frame 方法。
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame
|
ndarray
|
影格陣列,形狀為 (H, W, 3),RGB 格式 |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
當影格格式無效時 |
VideoIOError
|
當寫入失敗時 |
Source code in castle/utils/video_io.py
close()
¶
關閉影片寫入器並完成編碼
Source code in castle/utils/video_io.py
write_frame(frame)
¶
寫入一個影格
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame
|
ndarray
|
影格陣列,形狀為 (H, W, 3),RGB 格式 |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
當影格格式無效時 |
VideoIOError
|
當寫入失敗時 |
Source code in castle/utils/video_io.py
Video Management¶
castle.utils.video_manager
¶
Video management utilities for Castle AI.
add_video_to_project(storage_path, project_name, video_source_path, video_name)
¶
Add a video file to the project.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
storage_path
|
Path to the storage directory |
required | |
project_name
|
Name of the project |
required | |
video_source_path
|
Source path of the video file |
required | |
video_name
|
Name of the video file |
required |
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
(success: bool, message: str) |
Source code in castle/utils/video_manager.py
add_videos_batch(storage_path, project_name, video_directory, video_list)
¶
Add multiple videos to a project in batch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
storage_path
|
Path to the storage directory |
required | |
project_name
|
Name of the project |
required | |
video_directory
|
Source directory containing videos |
required | |
video_list
|
List of video file names to add |
required |
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
(success_count, fail_count, messages) |
Source code in castle/utils/video_manager.py
get_project_videos(storage_path, project_name)
¶
Get list of videos in a project.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
storage_path
|
Path to the storage directory |
required | |
project_name
|
Name of the project |
required |
Returns:
| Name | Type | Description |
|---|---|---|
list |
List of video file names in the project, sorted |
Source code in castle/utils/video_manager.py
is_video_file(file_path)
¶
Check if a file is a video based on its extension.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
Path to the file |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
True if the file is a video, False otherwise |
Source code in castle/utils/video_manager.py
list_videos_in_directory(directory_path)
¶
List all video files in a directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directory_path
|
Path to the directory |
required |
Returns:
| Name | Type | Description |
|---|---|---|
list |
Sorted list of video file names |
Source code in castle/utils/video_manager.py
load_video_metadata(storage_path, project_name, video_name)
¶
Load video file and return metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
storage_path
|
Path to the storage directory |
required | |
project_name
|
Name of the project |
required | |
video_name
|
Name of the video file |
required |
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
(video_path, frame_count) or (None, 0) if error |
Source code in castle/utils/video_manager.py
scan_video_directory(directory_path)
¶
Scan a directory and return video statistics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directory_path
|
Path to the directory to scan |
required |
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
(video_list, summary_text) where video_list is the list of all videos and summary_text is a formatted string showing statistics |
Source code in castle/utils/video_manager.py
Image Segmentation (SAM)¶
castle.utils.image_segment
¶
Segmentor
¶
Source code in castle/utils/image_segment.py
__init__(sam_args)
¶
sam_args
sam_checkpoint: path of SAM checkpoint generator_args: args for everything_generator device: device
Source code in castle/utils/image_segment.py
segment_with_click(origin_frame, coords, modes, multimask=True)
¶
return
mask: one-hot
Source code in castle/utils/image_segment.py
ROI Tracking¶
castle.utils.tracking_manager
¶
ROI tracking management utilities for Castle AI.
ROITracker
¶
ROI tracker for performing video object tracking using reference frames and masks.
Source code in castle/utils/tracking_manager.py
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 | |
__init__(storage_path, project_name, video_source, start_frame, stop_frame, model_type='r50_deaotl')
¶
Initialize the ROI tracker.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
storage_path
|
str
|
Base storage directory |
required |
project_name
|
str
|
Name of the project |
required |
video_source
|
Any
|
Video source object |
required |
start_frame
|
int
|
Starting frame index |
required |
stop_frame
|
int
|
Stopping frame index |
required |
model_type
|
str
|
Tracking model type (e.g., 'r50_deaotl', 'swinb_deaotl') |
'r50_deaotl'
|
Source code in castle/utils/tracking_manager.py
cancel_tracking()
¶
get_current_result()
¶
Get current frame and mask.
Returns:
| Type | Description |
|---|---|
Tuple[Optional[Any], Optional[Any]]
|
Tuple of (current_frame, current_mask) |
toggle_display_mode()
¶
track(progress=None, skip_existing=False)
¶
Execute ROI tracking over specified frames using a parallelized DataLoader and batch inference.
Source code in castle/utils/tracking_manager.py
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 | |
TrackingDataset
¶
Bases: Dataset
Dataset for lazy loading of video frames for tracking.
Source code in castle/utils/tracking_manager.py
__init__(video_source, frame_indices, transform)
¶
Initialize the dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
video_source
|
Any
|
Video source object (e.g., ReadArray) |
required |
frame_indices
|
List[int]
|
List of frame indices to process |
required |
transform
|
Any
|
Preprocessing transform to apply to each frame |
required |
Source code in castle/utils/tracking_manager.py
read_roi_labels(storage_path, project_name, video_name=None)
¶
Read all ROI label files for the given project.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
storage_path
|
str
|
Base storage directory |
required |
project_name
|
str
|
Name of the project |
required |
video_name
|
Optional[str]
|
Optional specific video name to filter labels |
None
|
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
List of dictionaries containing label information with keys: - index: String identifier combining file index and video basename - frame: Frame data - mask: Corresponding mask |
Source code in castle/utils/tracking_manager.py
Feature Extraction¶
castle.utils.visual_latent_extract
¶
castle/utils/visual_latent_extract.py Wrapper module for backward compatibility. Delegates to castle.core.models.
download_dinov3_ckpt(model_name)
¶
Downloads DINOv3 checkpoint if not exists.
Source code in castle/utils/visual_latent_extract.py
generate_dinov2(model_type='dinov2_vitb14', **kwargs)
¶
generate_dinov3(model_type='dinov3_vitb16', notify_func=None, **kwargs)
¶
Wrapper to get DINOv3 encoder from core.
Source code in castle/utils/visual_latent_extract.py
Latent Explorer¶
castle.utils.latent_explorer
¶
generate_distinct_color(index, saturation=0.7, value=0.9)
¶
Generate a distinct color using golden ratio for even distribution in HSV space.
This ensures an unlimited number of visually distinct colors can be generated, preventing clusters from becoming grey when the fixed palette is exhausted.
Source code in castle/utils/latent_explorer.py
Video Alignment¶
castle.utils.video_align
¶
get_roi_closest_point_safe(mask, roi_color)
¶
安全地獲取 ROI 的最接近中心點 如果 ROI 不存在或發生錯誤,返回 None
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mask
|
遮罩影像 |
required | |
roi_color
|
ROI 顏色識別碼 |
required |
Returns:
| Type | Description |
|---|---|
|
tuple (x, y) 或 None |
Source code in castle/utils/video_align.py
rotate_based_on_point(frame, closest_point)
¶
根據預先計算的最接近點旋轉影像
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame
|
要旋轉的影像 |
required | |
closest_point
|
(x, y) 座標元組 |
required |
Returns:
| Type | Description |
|---|---|
|
旋轉後的影像 |
Source code in castle/utils/video_align.py
HDF5 I/O¶
castle.utils.h5_io
¶
Visualization¶
castle.utils.plot
¶
Core — Extractor¶
Build Note
Auto-documentation for castle.core.extractor is unavailable due to import dependencies that are not installed in the docs build environment. See source code directly: castle/core/extractor.py
Core — Data¶
Build Note
Auto-documentation for castle.core.data is unavailable due to import dependencies. See source: castle/core/data.py
Core — Models¶
Build Note
Auto-documentation for castle.core.models is unavailable due to import dependencies. See source: castle/core/models.py