Documentation
¶
Overview ¶
Package norfairgo provides real-time multi-object tracking.
- norfairgo is a golang port of python's norfair https://github.com/tryolabs/norfair - This project is in **no** way associated with the original
Track objects across video frames using distance metrics and Kalman filtering.
Basic Usage ¶
tracker := norfairgo.NewTracker(
norfairgo.WithDistanceFunction(
norfairgo.GetDistanceFunctionByName("iou", nil),
),
norfairgo.WithDistanceThreshold(0.7),
)
for frame := range videoFrames {
detections := getDetections(frame)
trackedObjects := tracker.Update(detections)
for _, obj := range trackedObjects {
fmt.Printf("ID: %d, Position: %v\n", obj.ID, obj.LastDetection.Points)
}
}
Core Types ¶
Detection represents detected objects with keypoints or bounding boxes.
TrackedObject maintains state across frames:
- ID: Unique identifier
- LastDetection: Most recent matching detection
- Age: Frames since first detection
- HitCounter: Consecutive frames with detections
Tracker manages object lifecycle, association, and filtering.
Distance Functions ¶
Built-in: iou, euclidean, frobenius, manhattan Custom: Implement Distance interface
Filtering ¶
- OptimizedKalmanFilter: Fast, simplified covariance (default)
- FilterPyKalmanFilter: Full Kalman, filterpy-compatible
- NoFilter: No prediction
Index ¶
- func AnyTrue(values []bool) bool
- func CreateKeypointsVotingDistance(keypointDistanceThreshold, detectionThreshold float64) func(*Detection, *TrackedObject) float64
- func CreateNormalizedMeanEuclideanDistance(height, width int) func(*Detection, *TrackedObject) float64
- func Frobenius(detection *Detection, trackedObject *TrackedObject) float64
- func GetCutout(points *mat.Dense, img gocv.Mat) gocv.Mat
- func GetTerminalSize(defaultCols, defaultLines int) (cols, lines int)
- func GlobalCount() int
- func IoU(candidates, objects *mat.Dense) *mat.Dense
- func MatchDetectionsAndObjects(distanceMatrix *mat.Dense, distanceThreshold float64) (matchedCandIndices, matchedObjIndices []int)
- func MeanEuclidean(detection *Detection, trackedObject *TrackedObject) float64
- func MeanManhattan(detection *Detection, trackedObject *TrackedObject) float64
- func ResetGlobalCount()
- func StringPtr(s string) *string
- func ValidateDistanceMatrix(m *mat.Dense) error
- func ValidatePoints(points *mat.Dense) (*mat.Dense, error)
- func WarnOnce(message string)
- type Accumulators
- func (a *Accumulators) ComputeMetrics() (*Metrics, error)
- func (a *Accumulators) CreateAccumulator(videoName string) error
- func (a *Accumulators) PrintMetrics() error
- func (a *Accumulators) Reset()
- func (a *Accumulators) SaveMetrics(filePath string) error
- func (a *Accumulators) Update(gtBBoxes [][]float64, gtIDs []int, predBBoxes [][]float64, predIDs []int, ...) error
- type CoordinateTransformation
- type Detection
- type DetectionConfig
- type DetectionFileParser
- type Distance
- type Filter
- type FilterFactory
- type FilterPyKalmanFilter
- type FilterPyKalmanFilterFactory
- type HomographyTransformation
- type HomographyTransformationGetter
- type InformationFile
- type MOTChallengeData
- type MOTChallengeFrame
- type Metrics
- type MetricsDataFrame
- type MetricsRow
- type MotionEstimator
- type NilCoordinateTransformation
- type NoFilter
- type NoFilterFactory
- type OptimizedKalmanFilter
- func (okf *OptimizedKalmanFilter) GetDimZ() int
- func (okf *OptimizedKalmanFilter) GetState() *mat.Dense
- func (okf *OptimizedKalmanFilter) GetStateVector() *mat.Dense
- func (okf *OptimizedKalmanFilter) Predict()
- func (okf *OptimizedKalmanFilter) SetStateVector(x *mat.Dense)
- func (okf *OptimizedKalmanFilter) Update(detectionPointsFlatten *mat.Dense, R, H *mat.Dense)
- type OptimizedKalmanFilterFactory
- type PredictionsTextFile
- type ScalarDistance
- type ScipyDistance
- type TrackedObject
- func (to *TrackedObject) EstimateVelocity() *mat.Dense
- func (to *TrackedObject) GetEstimate(absolute bool) (*mat.Dense, error)
- func (to *TrackedObject) GetID() *int
- func (to *TrackedObject) GetLabel() *string
- func (to *TrackedObject) GetLivePoints() []bool
- func (to *TrackedObject) Hit(detection *Detection, period int) error
- func (to *TrackedObject) HitCounterIsPositive() bool
- func (to *TrackedObject) LivePoints() []bool
- func (to *TrackedObject) Merge(trackedObject *TrackedObject)
- func (to *TrackedObject) ReidHitCounterIsPositive() bool
- func (to *TrackedObject) TrackerStep()
- func (to *TrackedObject) UpdateCoordinateTransformation(coordTransform CoordinateTransformation)
- type TrackedObjectFactory
- type Tracker
- type TrackerConfig
- type TransformationGetter
- type TranslationTransformation
- type TranslationTransformationGetter
- type VectorizedDistance
- type Video
- type VideoFromFrames
- type VideoOptions
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AnyTrue ¶
AnyTrue returns true if any element in the slice is true. Returns false for empty slices.
func CreateKeypointsVotingDistance ¶
func CreateKeypointsVotingDistance(keypointDistanceThreshold, detectionThreshold float64) func(*Detection, *TrackedObject) float64
CreateKeypointsVotingDistance constructs a keypoint voting distance function configured with the thresholds.
Count how many points in a detection match with a tracked_object. A match is considered when distance between the points is < keypointDistanceThreshold and the score of the last_detection of the tracked_object is > detectionThreshold. Notice that if multiple points are tracked, the ith point in detection can only match the ith point in the tracked object.
Distance is 1 if no point matches and approximates 0 as more points are matched.
func CreateNormalizedMeanEuclideanDistance ¶
func CreateNormalizedMeanEuclideanDistance(height, width int) func(*Detection, *TrackedObject) float64
CreateNormalizedMeanEuclideanDistance constructs a normalized mean euclidean distance function configured with the max height and width.
The result distance is bound to [0, 1] where 1 indicates opposite corners of the image.
func Frobenius ¶
func Frobenius(detection *Detection, trackedObject *TrackedObject) float64
Frobenius computes the Frobenius norm distance
func GetCutout ¶
GetCutout extracts a rectangular region from an image based on the bounding box of points. The cutout is defined by the minimum and maximum x and y coordinates in the points array.
func GetTerminalSize ¶
GetTerminalSize returns the terminal dimensions (columns, lines). If terminal size cannot be detected, returns the provided defaults.
func GlobalCount ¶
func GlobalCount() int
GlobalCount returns the current global counter value. This represents the total number of objects that have been fully initialized across ALL factory instances.
func IoU ¶
IoU computes the IoU distance (1 - IoU) for bounding boxes Input format: [x_min, y_min, x_max, y_max]
func MatchDetectionsAndObjects ¶
func MatchDetectionsAndObjects( distanceMatrix *mat.Dense, distanceThreshold float64, ) (matchedCandIndices, matchedObjIndices []int)
MatchDetectionsAndObjects performs greedy minimum-distance matching between candidates (detections or tracked objects) and existing tracked objects.
This implements a greedy matching algorithm that repeatedly finds the global minimum distance and creates a match, then invalidates that row and column to prevent re-matching. This ensures one-to-one correspondence.
Note: This is NOT the optimal assignment algorithm (Hungarian). It's a simpler greedy approach that works well in practice for object tracking.
Parameters:
- distanceMatrix: NxM matrix of distances where N=candidates, M=objects
- distanceThreshold: Maximum distance to consider a valid match
Returns:
- matchedCandIndices: Indices of matched candidates (detections)
- matchedObjIndices: Indices of matched objects (tracked objects)
The returned slices have the same length and matchedCandIndices[i] corresponds to matchedObjIndices[i].
func MeanEuclidean ¶
func MeanEuclidean(detection *Detection, trackedObject *TrackedObject) float64
MeanEuclidean computes the mean Euclidean distance between corresponding points
func MeanManhattan ¶
func MeanManhattan(detection *Detection, trackedObject *TrackedObject) float64
MeanManhattan computes the mean Manhattan distance between corresponding points
func ResetGlobalCount ¶
func ResetGlobalCount()
ResetGlobalCount resets the global counter to zero. This should typically only be used in tests.
func StringPtr ¶
StringPtr returns a pointer to a string. Helper for DetectionConfig.Label.
Example:
det, err := NewDetection(points, &DetectionConfig{
Label: StringPtr("person"),
})
func ValidateDistanceMatrix ¶
ValidateDistanceMatrix checks a distance matrix for NaN values and returns an error if any are found. This should be called after computing distances and before performing matching.
func ValidatePoints ¶
ValidatePoints ensures points have shape (n_points, n_dims) where n_dims is 2 or 3. If points is a 1D array (single point), it reshapes to (1, n_dims).
Types ¶
type Accumulators ¶
type Accumulators struct {
// contains filtered or unexported fields
}
Accumulators manages multiple MOTAccumulator instances for multi-video evaluation.
This is thread-safe for concurrent accumulation across different videos.
func CompareDataframes ¶
func CompareDataframes(gt, predictions *MOTChallengeData, distanceFunc string, threshold float64) (*Accumulators, error)
CompareDataframes performs MOTChallenge evaluation on loaded GT and predictions.
Parameters:
- gt: Ground truth MOTChallenge data
- predictions: Tracker predictions MOTChallenge data
- distanceFunc: Distance function name ("iou", "euclidean", etc.)
- threshold: Distance threshold for valid matches (default 0.5 for IoU)
Returns: Populated Accumulators with all frames processed
func NewAccumulators ¶
func NewAccumulators() *Accumulators
NewAccumulators creates a new multi-video accumulator manager.
Returns: Initialized Accumulators instance
func (*Accumulators) ComputeMetrics ¶
func (a *Accumulators) ComputeMetrics() (*Metrics, error)
ComputeMetrics aggregates all accumulators and computes final metrics.
Returns: Metrics struct with computed values, or error
Edge cases:
- MOTA when numObjects == 0 → return 0.0 (not NaN)
- MOTP when numMatches == 0 → return NaN
func (*Accumulators) CreateAccumulator ¶
func (a *Accumulators) CreateAccumulator(videoName string) error
CreateAccumulator creates a new accumulator for a video sequence.
Parameters:
- videoName: Name of the video sequence
Returns: Error if accumulator already exists for this video
func (*Accumulators) PrintMetrics ¶
func (a *Accumulators) PrintMetrics() error
PrintMetrics prints a formatted summary of computed metrics.
Returns: Error if metric computation fails
func (*Accumulators) SaveMetrics ¶
func (a *Accumulators) SaveMetrics(filePath string) error
SaveMetrics exports metrics to a CSV file.
Parameters:
- filePath: Path to output CSV file
Returns: Error if file creation or metric computation fails
func (*Accumulators) Update ¶
func (a *Accumulators) Update(gtBBoxes [][]float64, gtIDs []int, predBBoxes [][]float64, predIDs []int, videoName string, threshold float64) error
Update processes a frame for a specific video.
Parameters:
- gtBBoxes: ground truth bounding boxes
- gtIDs: ground truth object IDs
- predBBoxes: predicted bounding boxes
- predIDs: tracker object IDs
- videoName: video sequence name
- threshold: IoU distance threshold (default 0.5)
Returns: Error if accumulator doesn't exist
type CoordinateTransformation ¶
type CoordinateTransformation interface {
// RelToAbs transforms points from relative (camera frame) to absolute (world frame) coordinates
RelToAbs(points *mat.Dense) *mat.Dense
// AbsToRel transforms points from absolute (world frame) to relative (camera frame) coordinates
AbsToRel(points *mat.Dense) *mat.Dense
}
CoordinateTransformation is an interface for transforming between relative and absolute coordinates. This is used for camera motion compensation in tracking.
Detections' and tracked objects' coordinates can be interpreted in 2 references: - Relative: their position on the current frame, (0, 0) is top left - Absolute: their position in a fixed space, (0, 0) is the top left of the first frame
Therefore, coordinate transformation in this context is an interface that can transform coordinates from one reference to another.
type Detection ¶
type Detection struct {
// Points are the original detection points in relative coordinates (camera frame)
Points *mat.Dense
// AbsolutePoints are the transformed points in absolute coordinates (world frame)
// Initially a copy of Points, updated by UpdateCoordinateTransformation
AbsolutePoints *mat.Dense
// Scores are optional per-point confidence scores (can be nil)
// Used for partial measurements in Kalman filter update
Scores []float64
// Data is custom user data storage (can be nil)
Data interface{}
// Label is the class label for multi-class tracking (can be nil)
// Objects with different labels are never matched
Label *string
// Embedding is the ReID embedding for re-identification (can be nil)
Embedding []float64
// Age is the age of this detection when added to past_detections
// Set by TrackedObject when storing past detections
Age int
}
Detection represents a detected object in a frame.
func NewDetection ¶
func NewDetection(points *mat.Dense, config *DetectionConfig) (*Detection, error)
NewDetection creates a new Detection from points and optional configuration.
Example - Simple (no config):
det, err := norfairgo.NewDetection(points, nil)
Example - With label:
det, err := norfairgo.NewDetection(points, &norfairgo.DetectionConfig{
Label: norfairgo.StringPtr("person"),
})
Example - Full config:
det, err := norfairgo.NewDetection(points, &norfairgo.DetectionConfig{
Scores: []float64{0.9, 0.8},
Label: norfairgo.StringPtr("person"),
Embedding: featureVector,
})
Parameters:
- points: Detection points, shape (n_points, n_dims) where n_dims is 2 or 3
- config: Optional configuration (can be nil)
Returns error if points have invalid shape.
func (*Detection) GetLabel ¶
GetLabel returns the detection label. Required by drawing.DetectionLike interface.
func (*Detection) GetPoints ¶
GetPoints returns the detection points in relative coordinates. Required by drawing.DetectionLike interface.
func (*Detection) GetScores ¶
GetScores returns the detection scores. Required by drawing.DetectionLike interface.
func (*Detection) UpdateCoordinateTransformation ¶
func (d *Detection) UpdateCoordinateTransformation(coordTransform CoordinateTransformation)
UpdateCoordinateTransformation transforms detection points to absolute coordinates. This is used for camera motion compensation.
If coordTransform is nil, this is a no-op.
type DetectionConfig ¶
type DetectionConfig struct {
// Scores are optional per-point confidence scores
// Used for partial measurements in Kalman filter update
Scores []float64
// Data is custom user data storage
Data interface{}
// Label is the class label for multi-class tracking
// Objects with different labels are never matched
Label *string
// Embedding is the ReID embedding for re-identification
Embedding []float64
}
DetectionConfig contains optional configuration for a Detection. All fields are optional and can be nil/zero.
type DetectionFileParser ¶
type DetectionFileParser struct {
// contains filtered or unexported fields
}
DetectionFileParser loads detections from MOTChallenge format text files.
The input format is CSV with columns: frame,id,bb_left,bb_top,bb_width,bb_height,conf,x,y,z
This converts to corner format: frame,id,x_min,y_min,x_max,y_max,conf,x,y,z
func NewDetectionFileParser ¶
func NewDetectionFileParser(inputPath string, informationFile *InformationFile) (*DetectionFileParser, error)
NewDetectionFileParser creates a new DetectionFileParser.
Parameters:
- inputPath: Path to sequence directory
- informationFile: Optional InformationFile (if nil, will load from inputPath/seqinfo.ini)
Returns: DetectionFileParser instance or error
func (*DetectionFileParser) Detections ¶
func (dfp *DetectionFileParser) Detections() <-chan []*Detection
Detections returns a channel that iterates through detections frame by frame.
This implements the iterator protocol using Go channels (matches video.go pattern).
func (*DetectionFileParser) Length ¶
func (dfp *DetectionFileParser) Length() int
Length returns the sequence length.
type Distance ¶
type Distance interface {
GetDistances(objects []*TrackedObject, candidates interface{}) *mat.Dense
}
Distance is the interface for all distance implementations
func DistanceByName ¶
DistanceByName is a convenience alias for GetDistanceByName. Panics if the distance name is invalid.
Example:
config := &TrackerConfig{
DistanceFunction: DistanceByName("iou"),
}
func GetDistanceByName ¶
GetDistanceByName selects a distance by name.
Returns the corresponding Distance implementation for the given name. Supports scalar distances (frobenius, mean_euclidean, mean_manhattan), vectorized distances (iou), and scipy metrics (euclidean, manhattan, etc.).
type Filter ¶
type Filter interface {
Predict()
Update(detectionPointsFlatten *mat.Dense, R, H *mat.Dense)
GetState() *mat.Dense
GetDimZ() int
// GetStateVector returns direct access to the state vector (for TrackedObject)
GetStateVector() *mat.Dense
// SetStateVector sets the state vector directly (for first-time point handling)
SetStateVector(x *mat.Dense)
}
Filter is an interface that all filters must implement
type FilterFactory ¶
FilterFactory is an interface for creating filters
type FilterPyKalmanFilter ¶
type FilterPyKalmanFilter struct {
*filterpy.KalmanFilter
}
FilterPyKalmanFilter wraps the internal filterpy.KalmanFilter to satisfy the Filter interface
func (*FilterPyKalmanFilter) GetStateVector ¶
func (kf *FilterPyKalmanFilter) GetStateVector() *mat.Dense
GetStateVector returns the state vector (wrapper for GetState to satisfy Filter interface)
func (*FilterPyKalmanFilter) SetStateVector ¶
func (kf *FilterPyKalmanFilter) SetStateVector(x *mat.Dense)
SetStateVector sets the state vector (wrapper for SetState to satisfy Filter interface)
type FilterPyKalmanFilterFactory ¶
type FilterPyKalmanFilterFactory struct {
RMult float64 // Multiplier for sensor measurement noise matrix
QMult float64 // Multiplier for process uncertainty
PMult float64 // Multiplier for initial covariance matrix (position entries)
}
FilterPyKalmanFilterFactory creates FilterPyKalmanFilter instances
func NewFilterPyKalmanFilterFactory ¶
func NewFilterPyKalmanFilterFactory(rMult, qMult, pMult float64) *FilterPyKalmanFilterFactory
NewFilterPyKalmanFilterFactory creates a factory with default parameters
func (*FilterPyKalmanFilterFactory) CreateFilter ¶
func (f *FilterPyKalmanFilterFactory) CreateFilter(initialDetection *mat.Dense) Filter
CreateFilter creates a new FilterPyKalmanFilter instance
type HomographyTransformation ¶
type HomographyTransformation struct {
HomographyMatrix *mat.Dense // 3x3 transformation matrix
InverseHomographyMatrix *mat.Dense // Pre-computed inverse for efficiency
}
HomographyTransformation represents a full perspective transformation using a 3x3 homography matrix. This handles camera rotation, scaling, skew, and perspective effects.
func NewHomographyTransformation ¶
func NewHomographyTransformation(homographyMatrix *mat.Dense) (*HomographyTransformation, error)
NewHomographyTransformation creates a new homography transformation with the given matrix. The matrix must be 3x3. The inverse is pre-computed for efficiency.
type HomographyTransformationGetter ¶
type HomographyTransformationGetter struct {
// Method is the OpenCV method for finding homographies.
// Valid options: gocv.HomographyMethodRANSAC (default), gocv.HomographyMethodLMEDS, gocv.HomographyMethodRHO
Method gocv.HomographyMethod
// RansacReprojThreshold is the maximum allowed reprojection error to treat a point pair as an inlier.
RansacReprojThreshold float64
// MaxIters is the maximum number of RANSAC iterations.
MaxIters int
// Confidence is the RANSAC confidence level (between 0 and 1).
Confidence float64
// ProportionPointsUsedThreshold is the minimum proportion of points that must be matched.
// If the proportion falls below this threshold, the reference frame is updated.
ProportionPointsUsedThreshold float64
// contains filtered or unexported fields
}
HomographyTransformationGetter calculates HomographyTransformation between points using RANSAC.
The camera movement is represented as a homography that matches the optical flow between the previous reference frame and the current. Comparing consecutive frames can make differences too small to correctly estimate the homography, so the reference frame is kept fixed as we progress through the video. Eventually, if the transformation can no longer match enough points, the reference frame is updated.
func NewHomographyTransformationGetter ¶
func NewHomographyTransformationGetter(ransacReprojThreshold float64, maxIters int, confidence, proportionPointsUsedThreshold float64) *HomographyTransformationGetter
NewHomographyTransformationGetter creates a new homography transformation getter with RANSAC.
func (*HomographyTransformationGetter) Call ¶
func (h *HomographyTransformationGetter) Call(currPts, prevPts *mat.Dense) (bool, CoordinateTransformation)
Call computes the homography transformation between current and previous points using RANSAC. Returns (shouldUpdateReference, transformation).
Algorithm: 1. Validate minimum 4 points (homography requires ≥4 correspondences) 2. Call gocv.FindHomography() with RANSAC 3. Count inliers and check proportion 4. Accumulate homographies via matrix multiplication (NOT addition!) 5. Determine if reference frame should be updated
type InformationFile ¶
type InformationFile struct {
// contains filtered or unexported fields
}
InformationFile parses MOTChallenge seqinfo.ini files to extract metadata.
func NewInformationFile ¶
func NewInformationFile(filePath string) (*InformationFile, error)
NewInformationFile creates a new InformationFile by reading the given file path.
func (*InformationFile) Search ¶
func (inf *InformationFile) Search(variableName string) (interface{}, error)
Search finds a variable in the information file and returns its value.
Parameters:
- variableName: The key to search for (e.g., "seqLength", "frameRate")
Returns: Value as interface{} (int if numeric, string otherwise) or error if not found
The format expected is "key=value" on each line.
func (*InformationFile) SearchInt ¶
func (inf *InformationFile) SearchInt(variableName string) (int, error)
SearchInt is a convenience method that returns the value as an int.
func (*InformationFile) SearchString ¶
func (inf *InformationFile) SearchString(variableName string) (string, error)
SearchString is a convenience method that returns the value as a string.
type MOTChallengeData ¶
type MOTChallengeData struct {
VideoName string
Frames map[int]*MOTChallengeFrame // map[frameID]*frame
}
MOTChallengeData holds parsed MOTChallenge format data for a single video.
Data is organized by frame number (1-indexed) for efficient frame-by-frame access.
func LoadMotchallenge ¶
func LoadMotchallenge(csvPath string) (*MOTChallengeData, error)
LoadMotchallenge loads MOTChallenge format CSV file into structured data.
Parameters:
- csvPath: Path to MOTChallenge CSV file (gt.txt or predictions.txt)
Returns: MOTChallengeData with frames organized by frame number
CSV Format: frame,id,bb_left,bb_top,bb_width,bb_height,conf,x,y,z
type MOTChallengeFrame ¶
type MOTChallengeFrame struct {
FrameID int
BBoxes [][]float64 // [x_min, y_min, x_max, y_max]
IDs []int
}
MOTChallengeFrame holds all detections/tracks for a single frame.
type Metrics ¶
type Metrics struct {
// Primary MOTChallenge metrics
MOTA float64 // Multi-Object Tracking Accuracy (range: -∞ to 1.0)
MOTP float64 // Multi-Object Tracking Precision (average IoU distance)
// Event counts
NumMatches int // True positives
NumFalsePositives int // False positives
NumMisses int // False negatives (missed detections)
NumSwitches int // ID switches
NumObjects int // Total ground truth objects
// Derived metrics
Precision float64 // TP / (TP + FP)
Recall float64 // TP / (TP + FN) = TP / NumObjects
// Extended MOTChallenge metrics
NumFragmentations int // Track fragmentations
MT float64 // Mostly Tracked (% of GT tracks covered >= 80%)
ML float64 // Mostly Lost (% of GT tracks covered <= 20%)
PT float64 // Partially Tracked (% of GT tracks 20% < covered < 80%)
MTCount int // Mostly Tracked count (matches py-motmetrics output)
MLCount int // Mostly Lost count (matches py-motmetrics output)
PTCount int // Partially Tracked count (matches py-motmetrics output)
NumTracks int // Total number of unique ground truth tracks
// ID metrics (Phase 2.3)
IDP float64 // ID Precision
IDR float64 // ID Recall
IDF1 float64 // ID F1-Score
}
Metrics contains computed MOTChallenge metrics for evaluation output.
This matches the output format of py-motmetrics compute_many().
func EvalMotChallenge ¶
EvalMotChallenge performs complete MOTChallenge evaluation from file paths.
Parameters:
- gtPath: Path to ground truth CSV file (e.g., "gt/gt.txt")
- predPath: Path to predictions CSV file (e.g., "predictions.txt")
- metricsToCompute: List of metric names to compute (nil = all metrics)
Returns: Metrics struct with computed values
This is the primary user-facing function for MOTChallenge evaluation.
type MetricsDataFrame ¶
type MetricsDataFrame struct {
Rows []MetricsRow // Per-video metrics + optional OVERALL
}
MetricsDataFrame holds metrics for multiple videos in a DataFrame-like structure.
Matches pandas.DataFrame returned by py-motmetrics compute_many() Rows are indexed by video name, with optional "OVERALL" aggregate row.
func NewMetricsDataFrame ¶
func NewMetricsDataFrame() *MetricsDataFrame
NewMetricsDataFrame creates an empty DataFrame.
func (*MetricsDataFrame) AddRow ¶
func (df *MetricsDataFrame) AddRow(row MetricsRow)
AddRow adds a metrics row to the DataFrame.
func (*MetricsDataFrame) Get ¶
func (df *MetricsDataFrame) Get(videoName, metricName string) (float64, bool)
Get retrieves a specific metric value for a video.
Parameters:
- videoName: Name of video (or "OVERALL")
- metricName: Name of metric field (e.g., "MOTA", "MOTP", "IDF1")
Returns: Metric value as float64, true if found, 0.0 and false otherwise.
func (*MetricsDataFrame) GetRow ¶
func (df *MetricsDataFrame) GetRow(videoName string) (MetricsRow, bool)
GetRow retrieves a row by video name.
Returns: MetricsRow and true if found, zero value and false otherwise.
type MetricsRow ¶
type MetricsRow struct {
VideoName string // Name of video sequence (or "OVERALL" for aggregate)
// Primary MOTChallenge metrics
MOTA float64 // Multi-Object Tracking Accuracy (range: -∞ to 1.0)
MOTP float64 // Multi-Object Tracking Precision (average IoU distance)
// Event counts
NumMatches int // True positives
NumFalsePositives int // False positives
NumMisses int // False negatives (missed detections)
NumSwitches int // ID switches
NumObjects int // Total ground truth objects
// Derived metrics
Precision float64 // TP / (TP + FP)
Recall float64 // TP / (TP + FN) = TP / NumObjects
// Extended MOTChallenge metrics (Phase 2)
NumFragmentations int // Track fragmentations
MT float64 // Mostly Tracked (% of GT tracks covered >= 80%)
ML float64 // Mostly Lost (% of GT tracks covered <= 20%)
PT float64 // Partially Tracked (% of GT tracks 20% < covered < 80%)
// ID metrics (Phase 2.3)
IDP float64 // ID Precision
IDR float64 // ID Recall
IDF1 float64 // ID F1-Score
}
MetricsRow represents metrics for a single video or aggregate summary.
This matches a single row in pandas DataFrame returned by py-motmetrics.
type MotionEstimator ¶
type MotionEstimator struct {
// Corner detection parameters
MaxPoints int // Maximum number of corner points to sample for optical flow
MinDistance int // Minimum distance between sampled points
BlockSize int // Size of averaging block for corner detection
QualityLevel float64 // Minimal accepted quality for corner detection (0.0 to 1.0)
// Transformation computation
TransformationsGetter TransformationGetter // Strategy for computing coordinate transformations
// Optional flow visualization
DrawFlow bool // Enable visual debugging by drawing optical flow vectors
FlowColor color.RGBA // Color for flow visualization
// contains filtered or unexported fields
}
MotionEstimator tracks camera motion across video frames using optical flow. It maintains a reference frame and tracks feature points between frames to compute coordinate transformations for camera motion compensation.
func NewMotionEstimator ¶
func NewMotionEstimator( maxPoints int, minDistance int, blockSize int, qualityLevel float64, transformationsGetter TransformationGetter, drawFlow bool, flowColor *color.RGBA, ) *MotionEstimator
NewMotionEstimator creates a new MotionEstimator with the specified parameters. If transformationsGetter is nil, it defaults to HomographyTransformationGetter.
func (*MotionEstimator) Close ¶
func (m *MotionEstimator) Close()
Close releases resources held by the MotionEstimator. Must be called when done using the MotionEstimator. Safe to call multiple times.
func (*MotionEstimator) Update ¶
func (m *MotionEstimator) Update(frame gocv.Mat, mask gocv.Mat) CoordinateTransformation
Update processes a new frame and computes the coordinate transformation for camera motion. Returns the transformation (or nil if it cannot be computed). The frame parameter is modified in-place if DrawFlow is enabled.
type NilCoordinateTransformation ¶
type NilCoordinateTransformation struct{}
NilCoordinateTransformation is a no-op transformation that returns points unchanged. This is used when camera motion is not being tracked.
type NoFilter ¶
type NoFilter struct {
// contains filtered or unexported fields
}
NoFilter implements a filter that does no prediction
func (*NoFilter) GetStateVector ¶
func (*NoFilter) SetStateVector ¶
type NoFilterFactory ¶
type NoFilterFactory struct{}
NoFilterFactory creates NoFilter instances
func NewNoFilterFactory ¶
func NewNoFilterFactory() *NoFilterFactory
NewNoFilterFactory creates a new NoFilterFactory
func (*NoFilterFactory) CreateFilter ¶
func (f *NoFilterFactory) CreateFilter(initialDetection *mat.Dense) Filter
type OptimizedKalmanFilter ¶
type OptimizedKalmanFilter struct {
// Simplified covariance representation (vectors instead of matrices)
PosVariance []float64
PosVelCovariance []float64
VelVariance []float64
// contains filtered or unexported fields
}
OptimizedKalmanFilter implements an optimized Kalman filter
func (*OptimizedKalmanFilter) GetDimZ ¶
func (okf *OptimizedKalmanFilter) GetDimZ() int
func (*OptimizedKalmanFilter) GetState ¶
func (okf *OptimizedKalmanFilter) GetState() *mat.Dense
func (*OptimizedKalmanFilter) GetStateVector ¶
func (okf *OptimizedKalmanFilter) GetStateVector() *mat.Dense
func (*OptimizedKalmanFilter) Predict ¶
func (okf *OptimizedKalmanFilter) Predict()
func (*OptimizedKalmanFilter) SetStateVector ¶
func (okf *OptimizedKalmanFilter) SetStateVector(x *mat.Dense)
type OptimizedKalmanFilterFactory ¶
type OptimizedKalmanFilterFactory struct {
RMult float64
QMult float64
PosVariance float64
PosVelCovariance float64
VelVariance float64
}
OptimizedKalmanFilterFactory creates OptimizedKalmanFilter instances
func NewOptimizedKalmanFilterFactory ¶
func NewOptimizedKalmanFilterFactory(rMult, qMult, posVar, posVelCov, velVar float64) *OptimizedKalmanFilterFactory
NewOptimizedKalmanFilterFactory creates a factory with default parameters
func (*OptimizedKalmanFilterFactory) CreateFilter ¶
func (f *OptimizedKalmanFilterFactory) CreateFilter(initialDetection *mat.Dense) Filter
type PredictionsTextFile ¶
type PredictionsTextFile struct {
// contains filtered or unexported fields
}
PredictionsTextFile generates a text file with tracked objects in MOTChallenge format.
The output format is CSV with columns: frame,id,bb_left,bb_top,bb_width,bb_height,-1,-1,-1,-1
func NewPredictionsTextFile ¶
func NewPredictionsTextFile(inputPath string, savePath string, informationFile *InformationFile) (*PredictionsTextFile, error)
NewPredictionsTextFile creates a new PredictionsTextFile for writing tracking results.
Parameters:
- inputPath: Path to the sequence being processed
- savePath: Directory where predictions/ folder will be created
- informationFile: Optional InformationFile (if nil, will load from inputPath/seqinfo.ini)
Returns: PredictionsTextFile instance or error
func (*PredictionsTextFile) Close ¶
func (ptf *PredictionsTextFile) Close() error
Close closes the output file (useful for manual cleanup). Safe to call multiple times (idempotent).
func (*PredictionsTextFile) Update ¶
func (ptf *PredictionsTextFile) Update(predictions []*TrackedObject, frameNumber *int) error
Update writes tracked object information for the current frame.
Parameters:
- predictions: List of TrackedObject instances
- frameNumber: Optional frame number (if nil, uses auto-incremented counter)
Format: frame_number,id,bb_left,bb_top,bb_width,bb_height,-1,-1,-1,-1
type ScalarDistance ¶
type ScalarDistance struct {
// contains filtered or unexported fields
}
ScalarDistance wraps a function that computes distance between one detection and one tracked object
func NewScalarDistance ¶
func NewScalarDistance(distanceFunction func(*Detection, *TrackedObject) float64) *ScalarDistance
NewScalarDistance creates a new ScalarDistance
func (*ScalarDistance) GetDistances ¶
func (sd *ScalarDistance) GetDistances(objects []*TrackedObject, candidates interface{}) *mat.Dense
GetDistances computes the distance matrix using scalar distance function
type ScipyDistance ¶
type ScipyDistance struct {
VectorizedDistance
// contains filtered or unexported fields
}
ScipyDistance implements scipy.spatial.distance.cdist functionality
func NewScipyDistance ¶
func NewScipyDistance(metric string) *ScipyDistance
NewScipyDistance creates a new ScipyDistance
type TrackedObject ¶
type TrackedObject struct {
// Dimensions
DimPoints int // Dimensionality per point (2 or 3)
NumPoints int // Number of points
// Runtime state (not in config)
InitialPeriod int // Initial period value (stored for Merge())
// State counters
HitCounter int // Current hit counter (object-level)
ReidHitCounter *int // Current ReID counter (nil until object dies)
PointHitCounter []int // Per-point hit counters
Age int // Age in frames
IsInitializing bool // Whether still in initialization phase
// IDs
InitializingID *int // Temporary ID during initialization
ID *int // Permanent instance ID (nil until initialized)
GlobalID *int // Permanent global ID (nil until initialized)
// Detection tracking
LastDetection *Detection // Last matched detection
LastDistance *float64 // Distance from last match
CurrentMinDistance *float64 // Current minimum distance (debug)
DetectedAtLeastOncePoints []bool // Which points have been detected at least once
PastDetections []*Detection // Past detections stored
// Filter
Filter Filter // Kalman filter for state estimation
DimZ int // Measurement dimension (dimPoints * numPoints)
Estimate *mat.Dense // Cached position estimate (updated after filter operations)
// Label and coordinate transform
Label *string // Class label
AbsToRel func(*mat.Dense) *mat.Dense // Absolute to relative coordinate transform
// contains filtered or unexported fields
}
TrackedObject represents an object being tracked across frames.
func NewTrackedObject ¶
func NewTrackedObject( objFactory *TrackedObjectFactory, initialDetection *Detection, config *TrackerConfig, period int, coordTransformations CoordinateTransformation, ) (*TrackedObject, error)
NewTrackedObject creates a new tracked object from an initial detection.
Parameters:
- objFactory: Factory for ID generation
- initialDetection: First detection to initialize object
- config: Tracker configuration (shared reference, immutable)
- period: Current frame period (varies per update)
- coordTransformations: Coordinate transformation for camera motion (optional)
func (*TrackedObject) EstimateVelocity ¶
func (to *TrackedObject) EstimateVelocity() *mat.Dense
EstimateVelocity returns the velocity estimate from the Kalman filter.
func (*TrackedObject) GetEstimate ¶
func (to *TrackedObject) GetEstimate(absolute bool) (*mat.Dense, error)
GetEstimate returns the position estimate from the Kalman filter.
Parameters:
- absolute: If true, returns absolute coordinates; if false, returns relative
func (*TrackedObject) GetID ¶
func (to *TrackedObject) GetID() *int
GetID returns the object's permanent ID. Required by drawing.TrackedObjectLike interface.
func (*TrackedObject) GetLabel ¶
func (to *TrackedObject) GetLabel() *string
GetLabel returns the object's label. Required by drawing.TrackedObjectLike interface.
func (*TrackedObject) GetLivePoints ¶
func (to *TrackedObject) GetLivePoints() []bool
GetLivePoints returns a boolean mask of which points are currently live. Alias for LivePoints() required by drawing.TrackedObjectLike interface.
func (*TrackedObject) Hit ¶
func (to *TrackedObject) Hit(detection *Detection, period int) error
Hit is called when the object is matched with a detection. It updates the Kalman filter and manages hit counters.
func (*TrackedObject) HitCounterIsPositive ¶
func (to *TrackedObject) HitCounterIsPositive() bool
HitCounterIsPositive returns whether the object is alive.
func (*TrackedObject) LivePoints ¶
func (to *TrackedObject) LivePoints() []bool
LivePoints returns a boolean mask of which points are currently live.
func (*TrackedObject) Merge ¶
func (to *TrackedObject) Merge(trackedObject *TrackedObject)
Merge merges another tracked object into this one (ReID matching). This keeps the old object's ID but takes the new object's state.
func (*TrackedObject) ReidHitCounterIsPositive ¶
func (to *TrackedObject) ReidHitCounterIsPositive() bool
ReidHitCounterIsPositive returns whether the object can still be ReID'd.
func (*TrackedObject) TrackerStep ¶
func (to *TrackedObject) TrackerStep()
TrackerStep is called once per frame for all tracked objects. It decrements counters, increments age, and calls filter prediction.
func (*TrackedObject) UpdateCoordinateTransformation ¶
func (to *TrackedObject) UpdateCoordinateTransformation(coordTransform CoordinateTransformation)
UpdateCoordinateTransformation updates the coordinate transformation function.
type TrackedObjectFactory ¶
type TrackedObjectFactory struct {
// contains filtered or unexported fields
}
TrackedObjectFactory is responsible for generating unique IDs for tracked objects. It maintains both instance-level IDs (unique within a tracker) and global IDs (unique across all trackers).
func NewTrackedObjectFactory ¶
func NewTrackedObjectFactory() *TrackedObjectFactory
NewTrackedObjectFactory creates a new TrackedObjectFactory instance.
func (*TrackedObjectFactory) Count ¶
func (f *TrackedObjectFactory) Count() int
Count returns the current instance-level counter value. This represents the total number of objects that have been fully initialized by this factory instance.
func (*TrackedObjectFactory) GetIDs ¶
func (f *TrackedObjectFactory) GetIDs() (id int, globalID int)
GetIDs returns both an instance-level ID and a global ID for a tracked object. This method should only be called when an object transitions from the initialization phase to the active tracking phase (i.e., when hit_counter exceeds initialization_delay).
Returns:
- id: Instance-level ID (unique within this tracker)
- globalID: Global ID (unique across all trackers in the application)
func (*TrackedObjectFactory) GetInitializingID ¶
func (f *TrackedObjectFactory) GetInitializingID() int
GetInitializingID returns a temporary ID for objects during initialization phase. This ID is assigned immediately when a tracked object is created, before it passes the initialization delay threshold.
Returns:
- int: A unique initializing ID (starts at 1, increments with each call)
func (*TrackedObjectFactory) InitializingCount ¶
func (f *TrackedObjectFactory) InitializingCount() int
InitializingCount returns the current initializing counter value. This represents the total number of objects that have been created (including those still in initialization phase).
type Tracker ¶
type Tracker struct {
// Configuration (immutable after creation)
Config *TrackerConfig
// State (mutable during tracking)
TrackedObjects []*TrackedObject
// contains filtered or unexported fields
}
Tracker is the main object tracking class that manages the lifecycle of tracked objects.
func NewTracker ¶
func NewTracker(config *TrackerConfig) (*Tracker, error)
NewTracker creates a new Tracker from a configuration.
Example:
tracker, err := norfairgo.NewTracker(&norfairgo.TrackerConfig{
DistanceFunction: norfairgo.DistanceByName("iou"),
DistanceThreshold: 0.5,
HitCounterMax: 30,
// Omitted fields will use sensible defaults
})
Zero/nil values in config will be replaced with defaults:
- DistanceFunction: euclidean (if nil)
- DistanceThreshold: 1.0 (if 0)
- HitCounterMax: 15 (if 0)
- InitializationDelay: hitCounterMax/2 (if -1)
- PointwiseHitCounterMax: 4 (if 0)
- DetectionThreshold: 0.0
- FilterFactory: OptimizedKalmanFilterFactory (if nil)
- PastDetectionsLength: 4 (if 0)
- ReidDistanceFunction: nil (disabled)
- ReidDistanceThreshold: 0.0
- ReidHitCounterMax: nil (disabled)
func (*Tracker) CurrentObjectCount ¶
CurrentObjectCount returns the number of currently active objects.
func (*Tracker) GetActiveObjects ¶
func (t *Tracker) GetActiveObjects() []*TrackedObject
GetActiveObjects returns objects that are not initializing and have positive hit counter.
func (*Tracker) TotalObjectCount ¶
TotalObjectCount returns the total number of objects ever created.
func (*Tracker) Update ¶
func (t *Tracker) Update( detections []*Detection, period int, coordTransformations CoordinateTransformation, ) []*TrackedObject
Update processes detections for the current frame and returns active tracked objects.
This implements the 8-stage tracking pipeline: 1. Coordinate transformation 2. Object cleanup 3. State prediction 4. Match initialized objects 5. Match initializing objects 6. ReID matching 7. Create new objects 8. Return active objects
Parameters:
- detections: List of detections for this frame (nil = no detections)
- period: Time period since last update (default: 1)
- coordTransformations: Coordinate transformation for camera motion (nil = no transformation)
type TrackerConfig ¶
type TrackerConfig struct {
// Distance function for matching detections to tracked objects.
// Use DistanceByName("euclidean") or pass a custom Distance implementation.
DistanceFunction Distance
// Maximum distance for a valid detection-object match.
// Pairs with distance > threshold will not be matched.
DistanceThreshold float64
// Maximum "hits" an object can accumulate before being clamped.
// Objects lose 1 hit per frame without detection, gain 2*period hits per match.
// Default: 15
HitCounterMax int
// Number of hits required before an object becomes "active".
// Objects in initialization phase are not returned to users.
// Use -1 for default (hitCounterMax / 2).
// Default: hitCounterMax / 2
InitializationDelay int
// Maximum hits for individual points (for pose estimation).
// Each point has its own hit counter for tracking reliability.
// Default: 4
PointwiseHitCounterMax int
// Minimum confidence score for a point to be considered detected.
// Points with scores below this threshold are excluded from Kalman updates.
// Default: 0.0
DetectionThreshold float64
// Factory for creating Kalman filters for tracked objects.
// Default: OptimizedKalmanFilterFactory with default parameters
FilterFactory FilterFactory
// Number of past detections to store per object.
// Used for metric learning and appearance-based distance functions.
// Default: 4
PastDetectionsLength int
// Re-identification (ReID) distance function for recovering lost identities.
// Set to nil to disable ReID.
// Default: nil (disabled)
ReidDistanceFunction Distance
// Maximum distance for ReID matching.
// Only applies when ReID is enabled.
// Default: 0.0
ReidDistanceThreshold float64
// How long a "dead" object survives for ReID matching.
// Objects with hit_counter <= 0 enter ReID mode with this counter value.
// Set to nil or 0 to disable ReID.
// Default: nil (disabled)
ReidHitCounterMax *int
}
TrackerConfig contains all configuration parameters for a Tracker. This separates configuration (immutable after creation) from state (mutable during tracking).
type TransformationGetter ¶
type TransformationGetter interface {
// Call computes the transformation between current and previous points.
// Returns: (shouldUpdateReference, transformation)
Call(currPts, prevPts *mat.Dense) (bool, CoordinateTransformation)
}
TransformationGetter is an interface for finding CoordinateTransformation between 2 sets of points. It takes current and previous point correspondences and returns whether the reference frame should be updated and the computed transformation.
type TranslationTransformation ¶
type TranslationTransformation struct {
MovementVector []float64 // [dx, dy] translation vector
}
TranslationTransformation represents a simple 2D translation (camera pan/tilt without rotation/zoom).
func NewTranslationTransformation ¶
func NewTranslationTransformation(movementVector []float64) (*TranslationTransformation, error)
NewTranslationTransformation creates a new translation transformation with the given movement vector.
type TranslationTransformationGetter ¶
type TranslationTransformationGetter struct {
// BinSize is the granularity for flow bucketing before calculating the mode.
// Optical flow is rounded to the nearest bin_size before finding the mode.
BinSize float64
// ProportionPointsUsedThreshold is the minimum proportion of points that must be matched.
// If the proportion falls below this threshold, the reference frame is updated.
ProportionPointsUsedThreshold float64
// contains filtered or unexported fields
}
TranslationTransformationGetter calculates TranslationTransformation between points using optical flow mode.
The camera movement is calculated as the mode of optical flow between the previous reference frame and the current frame. Comparing consecutive frames can make differences too small to correctly estimate the translation, so the reference frame is kept fixed as we progress through the video. Eventually, if the transformation can no longer match enough points, the reference frame is updated.
func NewTranslationTransformationGetter ¶
func NewTranslationTransformationGetter(binSize, proportionPointsUsedThreshold float64) *TranslationTransformationGetter
NewTranslationTransformationGetter creates a new translation transformation getter.
func (*TranslationTransformationGetter) Call ¶
func (t *TranslationTransformationGetter) Call(currPts, prevPts *mat.Dense) (bool, CoordinateTransformation)
Call computes the translation transformation between current and previous points. Returns (shouldUpdateReference, transformation).
Algorithm: 1. Calculate optical flow: flow = currPts - prevPts 2. Bin the flow vectors (round to bin_size) 3. Find mode (most common flow vector) 4. Check if proportion of points using mode is above threshold 5. Accumulate with previous transformation if reference frame not updated
type VectorizedDistance ¶
type VectorizedDistance struct {
// contains filtered or unexported fields
}
VectorizedDistance wraps a function that computes distances for all pairs at once
func NewVectorizedDistance ¶
func NewVectorizedDistance(distanceFunction func(candidates, objects *mat.Dense) *mat.Dense) *VectorizedDistance
NewVectorizedDistance creates a new VectorizedDistance
func (*VectorizedDistance) GetDistances ¶
func (vd *VectorizedDistance) GetDistances(objects []*TrackedObject, candidates interface{}) *mat.Dense
GetDistances computes the distance matrix using vectorized distance function
type Video ¶
type Video struct {
// contains filtered or unexported fields
}
Video wraps OpenCV VideoCapture and VideoWriter with progress tracking. Supports reading from video files or camera devices.
func NewVideo ¶
func NewVideo(opts VideoOptions) (*Video, error)
NewVideo creates a new Video instance. Exactly one of opts.Camera or opts.InputPath must be set.
func (*Video) Close ¶
Close releases all resources. Should be called with defer after creating a Video.
func (*Video) Frames ¶
Frames returns a channel that yields video frames. The channel is closed when all frames have been read or an error occurs.
func (*Video) GetOutputFilePath ¶
GetOutputFilePath returns the output file path. If outputPath is a directory, generates a filename based on input.
type VideoFromFrames ¶
type VideoFromFrames struct {
// contains filtered or unexported fields
}
VideoFromFrames reads image sequences from MOTChallenge-style directories. Expects a seqinfo.ini file with metadata and numbered image files.
func NewVideoFromFrames ¶
func NewVideoFromFrames(inputPath, savePath string, makeVideo bool) (*VideoFromFrames, error)
NewVideoFromFrames creates a new VideoFromFrames instance. Reads metadata from seqinfo.ini in the input directory.
func (*VideoFromFrames) Close ¶
func (vff *VideoFromFrames) Close() error
Close releases all resources.
func (*VideoFromFrames) Frames ¶
func (vff *VideoFromFrames) Frames() <-chan gocv.Mat
Frames returns a channel that yields frames from the image sequence.
type VideoOptions ¶
type VideoOptions struct {
// Input (exactly one must be set)
Camera *int
InputPath *string
// Output (optional)
OutputPath string // File path or directory (default: ".")
OutputFps float64 // Framerate (default: input fps)
OutputFourcc *string // Codec (default: auto-detect from extension)
OutputExt string // Extension for auto-naming (default: "mp4")
Label string // Progress bar label
}
VideoOptions configures Video creation.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package drawing provides visualization for tracked objects.
|
Package drawing provides visualization for tracked objects. |
|
internal
|
|
|
testutil
Package testutil provides common test utilities.
|
Package testutil provides common test utilities. |
|
tools
|
|
|
benchmark_rectangles
command
|