Documentation
¶
Overview ¶
Example ¶
Example demonstrates basic face recognition workflow
package main
import (
"fmt"
"log"
"github.com/lib-x/face"
)
func main() {
// Initialize recognizer
config := face.Config{
PigoCascadeFile: "./testdata/facefinder",
FaceEncoderModel: "./testdata/nn4.small2.v1.t7",
}
recognizer, err := face.NewFaceRecognizer(config)
if err != nil {
log.Fatal(err)
}
defer recognizer.Close()
// Register a person
err = recognizer.AddPerson("001", "Alice")
if err != nil {
log.Fatal(err)
}
fmt.Println("Face recognition system initialized")
fmt.Println("Person registered: Alice (ID: 001)")
}
Output: Face recognition system initialized Person registered: Alice (ID: 001)
Example (BatchRegistration) ¶
Example_batchRegistration demonstrates registering multiple persons with multiple photos
package main
import (
"fmt"
"log"
"github.com/lib-x/face"
)
func main() {
config := face.Config{
PigoCascadeFile: "./testdata/facefinder",
FaceEncoderModel: "./testdata/nn4.small2.v1.t7",
}
storage, _ := face.NewFileStorage("./testdata/face_db")
defer storage.Close()
recognizer, err := face.NewFaceRecognizer(
config,
face.WithStorage(storage),
)
if err != nil {
log.Fatal(err)
}
defer recognizer.Close()
// Batch registration data
persons := map[string]struct {
name string
photos []string
}{
"001": {name: "Alice", photos: []string{"alice1.jpg", "alice2.jpg"}},
"002": {name: "Bob", photos: []string{"bob1.jpg", "bob2.jpg"}},
}
// Register each person
for id, data := range persons {
recognizer.AddPerson(id, data.name)
fmt.Printf("Registered: %s (ID: %s)\n", data.name, id)
// In real scenario, would load and add photos here
// For example purposes, we just show the structure
for i := range data.photos {
fmt.Printf(" - Sample %d would be added\n", i+1)
}
}
// List all registered persons
persons_list := recognizer.ListPersons()
fmt.Printf("\nTotal registered: %d persons\n", len(persons_list))
}
Output: Registered: Alice (ID: 001) - Sample 1 would be added - Sample 2 would be added Registered: Bob (ID: 002) - Sample 1 would be added - Sample 2 would be added Total registered: 2 persons
Example (WorkflowComplete) ¶
Example_workflowComplete demonstrates a complete workflow
package main
import (
"fmt"
)
func main() {
fmt.Println("Complete Face Recognition Workflow:")
fmt.Println("")
fmt.Println("Step 1: Initialize recognizer with file storage")
fmt.Println("Step 2: Register persons and add face samples")
fmt.Println("Step 3: Save data (automatic with file storage)")
fmt.Println("Step 4: Load test image")
fmt.Println("Step 5: Detect and recognize faces")
fmt.Println("Step 6: Process recognition results")
fmt.Println("")
fmt.Println("API Usage:")
fmt.Println(" storage, _ := face.NewFileStorage(\"./face_db\")")
fmt.Println(" recognizer, _ := face.NewFaceRecognizer(config, face.WithStorage(storage))")
fmt.Println(" recognizer.AddPerson(\"001\", \"Alice\")")
fmt.Println(" recognizer.AddFaceSample(\"001\", img)")
fmt.Println(" results, _ := recognizer.Recognize(testImg)")
}
Output: Complete Face Recognition Workflow: Step 1: Initialize recognizer with file storage Step 2: Register persons and add face samples Step 3: Save data (automatic with file storage) Step 4: Load test image Step 5: Detect and recognize faces Step 6: Process recognition results API Usage: storage, _ := face.NewFileStorage("./face_db") recognizer, _ := face.NewFaceRecognizer(config, face.WithStorage(storage)) recognizer.AddPerson("001", "Alice") recognizer.AddFaceSample("001", img) results, _ := recognizer.Recognize(testImg)
Index ¶
- Variables
- func GetImageInfo(filepath string) (width, height, channels int, err error)
- func GetModelPath(outputDir, modelKey string) (string, error)
- func IsSupportedImageFormat(filename string) bool
- func ListAvailableModels()
- func LoadImage(filepath string) (gocv.Mat, error)
- func LoadImageFromBytes(data []byte) (gocv.Mat, error)
- func LoadImageFromStdImage(img image.Image) (gocv.Mat, error)
- func SaveImage(filepath string, img gocv.Mat) error
- type Config
- type DownloadProgress
- type FaceFeature
- type FaceRecognizer
- func (fr *FaceRecognizer) AddFaceSample(personID string, img gocv.Mat) error
- func (fr *FaceRecognizer) AddPerson(id, name string) error
- func (fr *FaceRecognizer) Close() error
- func (fr *FaceRecognizer) DetectFaces(img image.Image) []image.Rectangle
- func (fr *FaceRecognizer) ExtractFeature(faceImg gocv.Mat) ([]float32, error)
- func (fr *FaceRecognizer) GetModelConfig() ModelConfig
- func (fr *FaceRecognizer) GetPerson(id string) (*Person, error)
- func (fr *FaceRecognizer) GetSampleCount(personID string) (int, error)
- func (fr *FaceRecognizer) GetStorage() FaceStorage
- func (fr *FaceRecognizer) GetThreshold() float32
- func (fr *FaceRecognizer) ListPersons() []*Person
- func (fr *FaceRecognizer) LoadDatabase(filepath string) error
- func (fr *FaceRecognizer) Recognize(img gocv.Mat) ([]RecognizeResult, error)
- func (fr *FaceRecognizer) RemovePerson(id string) error
- func (fr *FaceRecognizer) SaveDatabase(filepath string) error
- func (fr *FaceRecognizer) SetThreshold(threshold float32)
- type FaceStorage
- type FileStorage
- func (s *FileStorage) Close() error
- func (s *FileStorage) DeletePerson(id string) error
- func (s *FileStorage) LoadAllPersons() ([]*Person, error)
- func (s *FileStorage) LoadPerson(id string) (*Person, error)
- func (s *FileStorage) PersonExists(id string) (bool, error)
- func (s *FileStorage) SavePerson(person *Person) error
- type JSONStorage
- func (s *JSONStorage) Close() error
- func (s *JSONStorage) DeletePerson(id string) error
- func (s *JSONStorage) LoadAllPersons() ([]*Person, error)
- func (s *JSONStorage) LoadPerson(id string) (*Person, error)
- func (s *JSONStorage) PersonExists(id string) (bool, error)
- func (s *JSONStorage) SavePerson(person *Person) error
- type MemoryStorage
- func (s *MemoryStorage) Close() error
- func (s *MemoryStorage) DeletePerson(id string) error
- func (s *MemoryStorage) LoadAllPersons() ([]*Person, error)
- func (s *MemoryStorage) LoadPerson(id string) (*Person, error)
- func (s *MemoryStorage) PersonExists(id string) (bool, error)
- func (s *MemoryStorage) SavePerson(person *Person) error
- type ModelConfig
- type ModelDownloader
- type ModelInfo
- type ModelType
- type Option
- func WithCustomModel(config ModelConfig) Option
- func WithMaxFaceSize(size int) Option
- func WithMinFaceSize(size int) Option
- func WithModelType(modelType ModelType) Option
- func WithPigoParams(params PigoParams) Option
- func WithSimilarityThreshold(threshold float32) Option
- func WithStorage(storage FaceStorage) Option
- type Person
- type PigoParams
- type ProgressCallback
- type RecognizeResult
- type StorageMetadata
Examples ¶
- Package
- Package (BatchRegistration)
- Package (WorkflowComplete)
- FaceRecognizer.AddFaceSample
- FaceRecognizer.AddPerson
- FaceRecognizer.ListPersons
- FaceRecognizer.Recognize
- GetStorageMetadata
- IsSupportedImageFormat
- LoadImage
- NewFileStorage
- NewJSONStorage
- NewMemoryStorage
- WithModelType
- WithSimilarityThreshold
Constants ¶
This section is empty.
Variables ¶
var AvailableModels = map[string]ModelInfo{ "pigo-facefinder": { Name: "Pigo Face Detector", URL: "https://raw.githubusercontent.com/esimov/pigo/master/cascade/facefinder", Filename: "facefinder", Size: 51764, Description: "Pigo cascade classifier for face detection", }, "openface": { Name: "OpenFace nn4.small2.v1", URL: "https://storage.cmusatyalab.org/openface-models/nn4.small2.v1.t7", Filename: "nn4.small2.v1.t7", MD5: "c95bfd8cc1adf05210e979ff623013b6", Size: 31510785, Description: "OpenFace face recognition model (96x96, 128-dim)", ModelType: ModelOpenFace, }, "openface-alternative": { Name: "OpenFace nn4.small2.v1 (Mirror)", URL: "https://raw.githubusercontent.com/pyannote/pyannote-data/master/openface.nn4.small2.v1.t7", Filename: "nn4.small2.v1.t7", Size: 31510785, Description: "OpenFace model from alternative mirror", ModelType: ModelOpenFace, }, "openface-kde": { Name: "OpenFace nn4.small2.v1 (KDE Mirror)", URL: "https://files.kde.org/digikam/facesengine/dnnface/openface_nn4.small2.v1.t7", Filename: "nn4.small2.v1.t7", Size: 31510785, Description: "OpenFace model from KDE mirror", ModelType: ModelOpenFace, }, }
AvailableModels Available models for download
var SupportedImageFormats = []string{
".jpg", ".jpeg",
".png",
".bmp",
".tif", ".tiff",
".webp",
".gif",
}
SupportedImageFormats lists all supported image formats
Functions ¶
func GetImageInfo ¶
GetImageInfo returns information about an image file
func GetModelPath ¶
GetModelPath returns the expected path for a downloaded model
func IsSupportedImageFormat ¶
IsSupportedImageFormat checks if the file extension is supported
Example ¶
ExampleIsSupportedImageFormat demonstrates format checking
package main
import (
"fmt"
"github.com/lib-x/face"
)
func main() {
formats := []string{
"photo.jpg",
"image.png",
"picture.gif",
"document.pdf", // Not supported
}
for _, filename := range formats {
if face.IsSupportedImageFormat(filename) {
fmt.Printf("%s: supported\n", filename)
} else {
fmt.Printf("%s: not supported\n", filename)
}
}
}
Output: photo.jpg: supported image.png: supported picture.gif: supported document.pdf: not supported
func ListAvailableModels ¶
func ListAvailableModels()
ListAvailableModels lists all available models
func LoadImage ¶
LoadImage loads an image from file path Supports: JPG, PNG, BMP, TIFF, WebP, GIF
Example ¶
ExampleLoadImage demonstrates how to load images in different formats
package main
import (
"fmt"
"github.com/lib-x/face"
)
func main() {
// Check if image format is supported
if face.IsSupportedImageFormat("photo.jpg") {
fmt.Println("JPEG format is supported")
}
// Load image from file
img, err := face.LoadImage("./testdata/sample.jpg")
if err != nil {
// Handle error - image file might not exist in example
fmt.Println("Image loading example (file may not exist)")
return
}
defer img.Close()
fmt.Println("Image loaded successfully")
}
Output: JPEG format is supported
func LoadImageFromBytes ¶
LoadImageFromBytes loads an image from byte slice
func LoadImageFromStdImage ¶
LoadImageFromStdImage converts standard Go image.Image to gocv.Mat
Types ¶
type Config ¶
type Config struct {
PigoCascadeFile string
FaceEncoderModel string
FaceEncoderConfig string // Optional config file for some models
}
Config holds the basic configuration for FaceRecognizer
type DownloadProgress ¶
type DownloadProgress struct {
Total int64
Downloaded int64
Percentage float64
Speed float64 // bytes per second
Elapsed time.Duration
}
DownloadProgress represents download progress
type FaceFeature ¶
FaceFeature represents a face feature vector
type FaceRecognizer ¶
type FaceRecognizer struct {
// contains filtered or unexported fields
}
FaceRecognizer is the main face recognition engine
func NewFaceRecognizer ¶
func NewFaceRecognizer(config Config, opts ...Option) (*FaceRecognizer, error)
NewFaceRecognizer creates a new FaceRecognizer instance
func (*FaceRecognizer) AddFaceSample ¶
func (fr *FaceRecognizer) AddFaceSample(personID string, img gocv.Mat) error
AddFaceSample adds a face sample for a specific person
Example ¶
ExampleFaceRecognizer_AddFaceSample demonstrates adding face samples
package main
import (
"fmt"
"log"
"github.com/lib-x/face"
)
func main() {
config := face.Config{
PigoCascadeFile: "./testdata/facefinder",
FaceEncoderModel: "./testdata/nn4.small2.v1.t7",
}
recognizer, err := face.NewFaceRecognizer(config)
if err != nil {
log.Fatal(err)
}
defer recognizer.Close()
// Register person first
recognizer.AddPerson("001", "Alice")
// Load image (example - file may not exist)
img, err := face.LoadImage("./testdata/alice.jpg")
if err != nil {
fmt.Println("Adding face sample example")
fmt.Println("Note: Sample image file not found")
return
}
defer img.Close()
// Add face sample
err = recognizer.AddFaceSample("001", img)
if err != nil {
log.Fatal(err)
}
fmt.Println("Face sample added for Alice")
}
Output: Adding face sample example Note: Sample image file not found
func (*FaceRecognizer) AddPerson ¶
func (fr *FaceRecognizer) AddPerson(id, name string) error
AddPerson adds a new person to the recognition database
Example ¶
ExampleFaceRecognizer_AddPerson demonstrates person registration
package main
import (
"fmt"
"log"
"github.com/lib-x/face"
)
func main() {
config := face.Config{
PigoCascadeFile: "./testdata/facefinder",
FaceEncoderModel: "./testdata/nn4.small2.v1.t7",
}
recognizer, err := face.NewFaceRecognizer(config)
if err != nil {
log.Fatal(err)
}
defer recognizer.Close()
// Add a person
err = recognizer.AddPerson("001", "Alice")
if err != nil {
log.Fatal(err)
}
// Add another person
err = recognizer.AddPerson("002", "Bob")
if err != nil {
log.Fatal(err)
}
fmt.Println("Registered: Alice")
fmt.Println("Registered: Bob")
}
Output: Registered: Alice Registered: Bob
func (*FaceRecognizer) DetectFaces ¶
func (fr *FaceRecognizer) DetectFaces(img image.Image) []image.Rectangle
DetectFaces detects faces in an image using Pigo
func (*FaceRecognizer) ExtractFeature ¶
func (fr *FaceRecognizer) ExtractFeature(faceImg gocv.Mat) ([]float32, error)
ExtractFeature extracts face feature vector using the configured model
func (*FaceRecognizer) GetModelConfig ¶
func (fr *FaceRecognizer) GetModelConfig() ModelConfig
GetModelConfig returns the current model configuration
func (*FaceRecognizer) GetPerson ¶
func (fr *FaceRecognizer) GetPerson(id string) (*Person, error)
GetPerson retrieves a person by ID
func (*FaceRecognizer) GetSampleCount ¶
func (fr *FaceRecognizer) GetSampleCount(personID string) (int, error)
GetSampleCount returns the number of samples for a person
func (*FaceRecognizer) GetStorage ¶
func (fr *FaceRecognizer) GetStorage() FaceStorage
GetStorage returns the storage backend
func (*FaceRecognizer) GetThreshold ¶
func (fr *FaceRecognizer) GetThreshold() float32
GetThreshold returns the current similarity threshold
func (*FaceRecognizer) ListPersons ¶
func (fr *FaceRecognizer) ListPersons() []*Person
ListPersons returns all registered persons
Example ¶
ExampleFaceRecognizer_ListPersons demonstrates listing registered persons
package main
import (
"fmt"
"log"
"github.com/lib-x/face"
)
func main() {
config := face.Config{
PigoCascadeFile: "./testdata/facefinder",
FaceEncoderModel: "./testdata/nn4.small2.v1.t7",
}
recognizer, err := face.NewFaceRecognizer(config)
if err != nil {
log.Fatal(err)
}
defer recognizer.Close()
// Add some persons
recognizer.AddPerson("001", "Alice")
recognizer.AddPerson("002", "Bob")
recognizer.AddPerson("003", "Charlie")
// List all persons
persons := recognizer.ListPersons()
fmt.Printf("Total registered persons: %d\n", len(persons))
for _, person := range persons {
fmt.Printf("ID: %s, Name: %s\n", person.ID, person.Name)
}
}
Output: Total registered persons: 3 ID: 001, Name: Alice ID: 002, Name: Bob ID: 003, Name: Charlie
func (*FaceRecognizer) LoadDatabase ¶
func (fr *FaceRecognizer) LoadDatabase(filepath string) error
LoadDatabase loads the face database from a JSON file
func (*FaceRecognizer) Recognize ¶
func (fr *FaceRecognizer) Recognize(img gocv.Mat) ([]RecognizeResult, error)
Recognize recognizes faces in an image
Example ¶
ExampleFaceRecognizer_Recognize demonstrates face recognition
package main
import (
"fmt"
"log"
"github.com/lib-x/face"
)
func main() {
config := face.Config{
PigoCascadeFile: "./testdata/facefinder",
FaceEncoderModel: "./testdata/nn4.small2.v1.t7",
}
recognizer, err := face.NewFaceRecognizer(config)
if err != nil {
log.Fatal(err)
}
defer recognizer.Close()
// This would normally recognize faces in an image
// For this example, we just show the API usage
fmt.Println("Face recognition API example:")
fmt.Println("1. Load image with LoadImage()")
fmt.Println("2. Call Recognize(img) to detect and identify faces")
fmt.Println("3. Process RecognizeResult for each detected face")
}
Output: Face recognition API example: 1. Load image with LoadImage() 2. Call Recognize(img) to detect and identify faces 3. Process RecognizeResult for each detected face
func (*FaceRecognizer) RemovePerson ¶
func (fr *FaceRecognizer) RemovePerson(id string) error
RemovePerson removes a person from the database
func (*FaceRecognizer) SaveDatabase ¶
func (fr *FaceRecognizer) SaveDatabase(filepath string) error
SaveDatabase saves the face database to a JSON file
func (*FaceRecognizer) SetThreshold ¶
func (fr *FaceRecognizer) SetThreshold(threshold float32)
SetThreshold sets the similarity threshold
type FaceStorage ¶
type FaceStorage interface {
// SavePerson saves a person and their features
SavePerson(person *Person) error
// LoadPerson loads a person by ID
LoadPerson(id string) (*Person, error)
// LoadAllPersons loads all persons
LoadAllPersons() ([]*Person, error)
// DeletePerson deletes a person by ID
DeletePerson(id string) error
// PersonExists checks if a person exists
PersonExists(id string) (bool, error)
// Close closes the storage connection
Close() error
}
FaceStorage defines the interface for face feature storage Implementations can use database, filesystem, or memory storage
type FileStorage ¶
type FileStorage struct {
// contains filtered or unexported fields
}
FileStorage implements filesystem-based storage (persistent)
func NewFileStorage ¶
func NewFileStorage(baseDir string) (*FileStorage, error)
NewFileStorage creates a new filesystem storage
Example ¶
ExampleNewFileStorage demonstrates persistent file storage
package main
import (
"fmt"
"log"
"github.com/lib-x/face"
)
func main() {
// Create file storage
storage, err := face.NewFileStorage("./testdata/face_db")
if err != nil {
log.Fatal(err)
}
defer storage.Close()
// Use with recognizer
config := face.Config{
PigoCascadeFile: "./testdata/facefinder",
FaceEncoderModel: "./testdata/nn4.small2.v1.t7",
}
recognizer, err := face.NewFaceRecognizer(
config,
face.WithStorage(storage),
)
if err != nil {
log.Fatal(err)
}
defer recognizer.Close()
fmt.Println("File storage initialized")
fmt.Println("Data will be persisted to: ./testdata/face_db")
}
Output: File storage initialized Data will be persisted to: ./testdata/face_db
func (*FileStorage) Close ¶
func (s *FileStorage) Close() error
func (*FileStorage) DeletePerson ¶
func (s *FileStorage) DeletePerson(id string) error
func (*FileStorage) LoadAllPersons ¶
func (s *FileStorage) LoadAllPersons() ([]*Person, error)
func (*FileStorage) LoadPerson ¶
func (s *FileStorage) LoadPerson(id string) (*Person, error)
func (*FileStorage) PersonExists ¶
func (s *FileStorage) PersonExists(id string) (bool, error)
func (*FileStorage) SavePerson ¶
func (s *FileStorage) SavePerson(person *Person) error
type JSONStorage ¶
type JSONStorage struct {
// contains filtered or unexported fields
}
JSONStorage implements a single JSON file storage (for small datasets)
func NewJSONStorage ¶
func NewJSONStorage(filepath string) (*JSONStorage, error)
NewJSONStorage creates a new JSON file storage
Example ¶
ExampleNewJSONStorage demonstrates single JSON file storage
package main
import (
"fmt"
"log"
"github.com/lib-x/face"
)
func main() {
// Create JSON storage
storage, err := face.NewJSONStorage("./testdata/faces.json")
if err != nil {
log.Fatal(err)
}
defer storage.Close()
fmt.Println("JSON storage initialized")
fmt.Println("Data file: ./testdata/faces.json")
}
Output: JSON storage initialized Data file: ./testdata/faces.json
func (*JSONStorage) Close ¶
func (s *JSONStorage) Close() error
func (*JSONStorage) DeletePerson ¶
func (s *JSONStorage) DeletePerson(id string) error
func (*JSONStorage) LoadAllPersons ¶
func (s *JSONStorage) LoadAllPersons() ([]*Person, error)
func (*JSONStorage) LoadPerson ¶
func (s *JSONStorage) LoadPerson(id string) (*Person, error)
func (*JSONStorage) PersonExists ¶
func (s *JSONStorage) PersonExists(id string) (bool, error)
func (*JSONStorage) SavePerson ¶
func (s *JSONStorage) SavePerson(person *Person) error
type MemoryStorage ¶
type MemoryStorage struct {
// contains filtered or unexported fields
}
MemoryStorage implements in-memory storage (default, fast but volatile)
func NewMemoryStorage ¶
func NewMemoryStorage() *MemoryStorage
NewMemoryStorage creates a new in-memory storage
Example ¶
ExampleNewMemoryStorage demonstrates in-memory storage
package main
import (
"fmt"
"log"
"github.com/lib-x/face"
)
func main() {
// Create in-memory storage
storage := face.NewMemoryStorage()
// Use with recognizer
config := face.Config{
PigoCascadeFile: "./testdata/facefinder",
FaceEncoderModel: "./testdata/nn4.small2.v1.t7",
}
recognizer, err := face.NewFaceRecognizer(
config,
face.WithStorage(storage),
)
if err != nil {
log.Fatal(err)
}
defer recognizer.Close()
fmt.Println("Memory storage initialized")
}
Output: Memory storage initialized
func (*MemoryStorage) Close ¶
func (s *MemoryStorage) Close() error
func (*MemoryStorage) DeletePerson ¶
func (s *MemoryStorage) DeletePerson(id string) error
func (*MemoryStorage) LoadAllPersons ¶
func (s *MemoryStorage) LoadAllPersons() ([]*Person, error)
func (*MemoryStorage) LoadPerson ¶
func (s *MemoryStorage) LoadPerson(id string) (*Person, error)
func (*MemoryStorage) PersonExists ¶
func (s *MemoryStorage) PersonExists(id string) (bool, error)
func (*MemoryStorage) SavePerson ¶
func (s *MemoryStorage) SavePerson(person *Person) error
type ModelConfig ¶
type ModelConfig struct {
Type ModelType
InputSize image.Point // Input image size for the model
FeatureDim int // Feature vector dimension
MeanValues gocv.Scalar // Mean values for normalization
ScaleFactor float64 // Scale factor for normalization
SwapRB bool // Swap Red and Blue channels
Crop bool // Center crop
}
ModelConfig holds model-specific configuration
type ModelDownloader ¶
type ModelDownloader struct {
OutputDir string
OnProgress ProgressCallback
Timeout time.Duration
SkipVerification bool
ProxyURL string // SOCKS5 or HTTP proxy URL (e.g., "socks5://127.0.0.1:10808")
}
ModelDownloader handles model file downloads
func NewModelDownloader ¶
func NewModelDownloader(outputDir string) *ModelDownloader
NewModelDownloader creates a new model downloader
func (*ModelDownloader) Download ¶
func (md *ModelDownloader) Download(modelKey string) error
Download downloads a model by its key
func (*ModelDownloader) DownloadAll ¶
func (md *ModelDownloader) DownloadAll() error
DownloadAll downloads all available models
func (*ModelDownloader) DownloadModel ¶
func (md *ModelDownloader) DownloadModel(model ModelInfo) error
DownloadModel downloads a specific model
func (*ModelDownloader) DownloadRequired ¶
func (md *ModelDownloader) DownloadRequired() error
DownloadRequired downloads only the required models for basic functionality
type ModelInfo ¶
type ModelInfo struct {
Name string
URL string
Filename string
MD5 string // Optional checksum
Size int64 // Expected size in bytes
Description string
ModelType ModelType
}
ModelInfo contains information about a downloadable model
type ModelType ¶
type ModelType string
ModelType defines the face encoding model type
const ( // ModelOpenFace is the OpenFace nn4.small2.v1 model (128-dim, 96x96 input) ModelOpenFace ModelType = "openface" // ModelFaceNet is the FaceNet model (128-dim, 160x160 input) ModelFaceNet ModelType = "facenet" // ModelArcFace is the ArcFace model (512-dim, 112x112 input) ModelArcFace ModelType = "arcface" // ModelDlib is the Dlib ResNet model (128-dim, 150x150 input) ModelDlib ModelType = "dlib" // ModelCustom allows custom model configuration ModelCustom ModelType = "custom" )
type Option ¶
type Option func(*FaceRecognizer)
Option is a function that configures FaceRecognizer
func WithCustomModel ¶
func WithCustomModel(config ModelConfig) Option
WithCustomModel sets a custom model configuration
func WithMaxFaceSize ¶
WithMaxFaceSize sets the maximum face size for detection
func WithMinFaceSize ¶
WithMinFaceSize sets the minimum face size for detection
func WithModelType ¶
WithModelType sets the model type (uses predefined configuration)
Example ¶
ExampleWithModelType demonstrates using different model types
package main
import (
"fmt"
"log"
"github.com/lib-x/face"
)
func main() {
config := face.Config{
PigoCascadeFile: "./testdata/facefinder",
FaceEncoderModel: "./testdata/nn4.small2.v1.t7",
}
// Use OpenFace model (default)
recognizer, err := face.NewFaceRecognizer(
config,
face.WithModelType(face.ModelOpenFace),
)
if err != nil {
log.Fatal(err)
}
defer recognizer.Close()
modelConfig := recognizer.GetModelConfig()
fmt.Printf("Model type: %s\n", modelConfig.Type)
fmt.Printf("Feature dimension: %d\n", modelConfig.FeatureDim)
fmt.Printf("Input size: %dx%d\n", modelConfig.InputSize.X, modelConfig.InputSize.Y)
}
Output: Model type: openface Feature dimension: 128 Input size: 96x96
func WithPigoParams ¶
func WithPigoParams(params PigoParams) Option
WithPigoParams sets custom Pigo detector parameters
func WithSimilarityThreshold ¶
WithSimilarityThreshold sets the similarity threshold for recognition
Example ¶
ExampleWithSimilarityThreshold demonstrates setting similarity threshold
package main
import (
"fmt"
"log"
"github.com/lib-x/face"
)
func main() {
config := face.Config{
PigoCascadeFile: "./testdata/facefinder",
FaceEncoderModel: "./testdata/nn4.small2.v1.t7",
}
// Create recognizer with custom threshold
recognizer, err := face.NewFaceRecognizer(
config,
face.WithSimilarityThreshold(0.7), // Higher threshold = stricter matching
)
if err != nil {
log.Fatal(err)
}
defer recognizer.Close()
threshold := recognizer.GetThreshold()
fmt.Printf("Similarity threshold set to: %.2f\n", threshold)
}
Output: Similarity threshold set to: 0.70
func WithStorage ¶
func WithStorage(storage FaceStorage) Option
WithStorage sets a custom storage backend
type Person ¶
type Person struct {
ID string `json:"id"`
Name string `json:"name"`
Features []FaceFeature `json:"features"`
// contains filtered or unexported fields
}
Person represents a person with multiple face samples
type PigoParams ¶
type PigoParams struct {
MinSize int // Minimum face size
MaxSize int // Maximum face size
ShiftFactor float64 // Shift factor
ScaleFactor float64 // Scale factor
QualityThreshold float32 // Detection quality threshold
}
PigoParams holds Pigo face detector parameters
type ProgressCallback ¶
type ProgressCallback func(progress DownloadProgress)
ProgressCallback is called during download to report progress
type RecognizeResult ¶
type RecognizeResult struct {
PersonID string `json:"person_id"`
PersonName string `json:"person_name"`
Confidence float32 `json:"confidence"`
BoundingBox image.Rectangle `json:"bounding_box"`
}
RecognizeResult represents a face recognition result
type StorageMetadata ¶
type StorageMetadata struct {
TotalPersons int `json:"total_persons"`
TotalFeatures int `json:"total_features"`
LastUpdated time.Time `json:"last_updated"`
}
StorageMetadata contains metadata about stored persons
func GetStorageMetadata ¶
func GetStorageMetadata(storage FaceStorage) (*StorageMetadata, error)
GetMetadata returns metadata about the storage
Example ¶
ExampleGetStorageMetadata demonstrates getting storage statistics
package main
import (
"fmt"
"log"
"github.com/lib-x/face"
)
func main() {
storage := face.NewMemoryStorage()
// Create person data for example
person := &face.Person{
ID: "001",
Name: "Alice",
Features: []face.FaceFeature{
{PersonID: "001", Feature: make([]float32, 128)},
{PersonID: "001", Feature: make([]float32, 128)},
},
}
storage.SavePerson(person)
// Get metadata
metadata, err := face.GetStorageMetadata(storage)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Total persons: %d\n", metadata.TotalPersons)
fmt.Printf("Total features: %d\n", metadata.TotalFeatures)
}
Output: Total persons: 1 Total features: 2