Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 13 additions & 13 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
*.bmp
*.png
*.jpg
*.jpeg
*.json
pigo
build
packages
wasm/lib.wasm
wasm/js/wasm_exec.js
!/testdata/*.png
!/testdata/*.jpg
!/examples/**/*.png
*.bmp
*.png
*.jpg
*.jpeg
*.json
pigo
build
packages
wasm/lib.wasm
wasm/js/wasm_exec.js
!/testdata/*.png
!/testdata/*.jpg
!/examples/**/*.png
examples/*/*.so
Empty file modified Makefile
100755 → 100644
Empty file.
9 changes: 4 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,16 +105,15 @@ cParams := pigo.CascadeParams{
},
}

p := pigo.NewPigo()
// Unpack the binary file. This will return the number of cascade trees,
// Unpack the facefinder binary file. This will return the number of cascade trees,
// the tree depth, the threshold and the prediction from tree's leaf nodes.
classifier := p.Unpack()
classifier := pigo.Unpack()

angle := 0.0 // cascade rotation angle. 0.0 is 0 radians and 1.0 is 2*pi radians
faceAngle := 0.0 // cascade rotation angle. 0.0 is 0 radians and 1.0 is 2*pi radians

// Run the classifier over the obtained leaf nodes and return the detection results.
// The result contains quadruplets representing the row, column, scale and detection score.
dets := classifier.RunCascade(cParams, angle)
dets := classifier.RunCascade(cParams, faceAngle)

// Calculate the intersection over union (IoU) of two clusters.
dets = classifier.ClusterDetections(dets, 0.2)
Expand Down
50 changes: 23 additions & 27 deletions cmd/pigo/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@ const (
errorColor = "\x1b[31m"
defaultColor = "\x1b[0m"

perturb = 63
confidenceLevel = 5.0
perturbation = 63
)

// Version indicates the current build version.
Expand All @@ -76,7 +77,7 @@ type faceDetector struct {
destination string
puploc bool
flploc bool
angle float64
faceAngle float64
minSize int
maxSize int
shiftFactor float64
Expand Down Expand Up @@ -108,7 +109,7 @@ func main() {
maxSize = flag.Int("max", 1000, "Maximum size of face")
shiftFactor = flag.Float64("shift", 0.15, "Shift detection window by percentage")
scaleFactor = flag.Float64("scale", 1.15, "Scale detection window by percentage")
angle = flag.Float64("angle", 0.0, "0.0 is 0 radians and 1.0 is 2*pi radians")
faceAngle = flag.Float64("angle", 0.0, "0.0 is 0 radians and 1.0 is 2*pi radians")
iouThreshold = flag.Float64("iou", 0.15, "Intersection over union (IoU) threshold")
marker = flag.String("marker", "rect", "Detection marker: rect|circle|ellipse")
puploc = flag.Bool("puploc", false, "Activate pupils/eyes localization")
Expand All @@ -135,13 +136,13 @@ func main() {
spinner.Start()

det = &faceDetector{
angle: *angle,
destination: *destination,
minSize: *minSize,
maxSize: *maxSize,
shiftFactor: *shiftFactor,
scaleFactor: *scaleFactor,
iouThreshold: *iouThreshold,
faceAngle: *faceAngle,
puploc: *puploc,
flploc: *flploc,
markDetEyes: *markEyes,
Expand Down Expand Up @@ -283,38 +284,35 @@ func (fd *faceDetector) detectFaces(source string) ([]pigo.Detection, error) {
Dim: cols,
}

cParams := pigo.CascadeParams{
cParams := &pigo.CascadeParams{
MinSize: det.minSize,
MaxSize: det.maxSize,
ShiftFactor: det.shiftFactor,
ScaleFactor: det.scaleFactor,
ImageParams: *imgParams,
}

p := pigo.NewPigo()
plc = pigo.NewPuplocCascade()

// Unpack the facefinder binary file. This will return the number of cascade trees,
// the tree depth, the threshold and the prediction from tree's leaf nodes.
classifier := p.Unpack()
classifier := pigo.UnpackCascade()

if det.puploc || det.flploc {
plc, err = plc.ReadCascade()
plc, err = pigo.UnpackPlc()
if err != nil {
return nil, fmt.Errorf("failed to unpack the pupil localization cascade file: %w", err)
}
}

if det.flploc {
flpcs, err = plc.ReadCascadeDir()
flpcs, err = pigo.ReadFlpCascadeDir()
if err != nil {
return nil, fmt.Errorf("failed to unpack the facial landmark points cascade files: %w", err)
}
}

// Run the classifier over the obtained leaf nodes and return the detection results.
// The result contains quadruplets representing the row, column, scale and detection score.
faces := classifier.RunCascade(cParams, det.angle)
faces := classifier.RunClassifier(cParams, det.faceAngle)

// Calculate the intersection over union (IoU) of two clusters.
faces = classifier.ClusterDetections(faces, det.iouThreshold)
Expand All @@ -324,8 +322,6 @@ func (fd *faceDetector) detectFaces(source string) ([]pigo.Detection, error) {

// drawFaces marks the detected faces with the marker type defined as parameter (rectangle|circle|ellipse).
func (fd *faceDetector) drawFaces(faces []pigo.Detection, marker string) ([]detection, error) {
var qThresh float32 = 5.0

var (
detections = make([]detection, 0, len(faces))
eyesCoords = make([]coord, 0, len(faces))
Expand All @@ -334,7 +330,7 @@ func (fd *faceDetector) drawFaces(faces []pigo.Detection, marker string) ([]dete
)

for _, face := range faces {
if face.Q > qThresh {
if face.Q > confidenceLevel {
switch marker {
case markerRectangle:
dc.DrawRectangle(float64(face.Col-face.Scale/2),
Expand Down Expand Up @@ -384,19 +380,19 @@ func (fd *faceDetector) drawFaces(faces []pigo.Detection, marker string) ([]dete
Row: face.Row - int(0.075*float32(face.Scale)),
Col: face.Col - int(0.175*float32(face.Scale)),
Scale: float32(face.Scale) * 0.25,
Perturbs: perturb,
Perturbs: perturbation,
}
leftEye := plc.RunDetector(puploc, *imgParams, det.angle, false)
leftEye := plc.RunClassifier(puploc, imgParams, det.faceAngle, false)
if leftEye.Row > 0 && leftEye.Col > 0 {
if det.angle > 0 {
if det.faceAngle > 0 {
drawEyeDetectionMarker(ctx,
float64(cols/2-(face.Col-leftEye.Col)),
float64(rows/2-(face.Row-leftEye.Row)),
float64(leftEye.Scale),
color.RGBA{R: 255, G: 0, B: 0, A: 255},
det.markDetEyes,
)
angle := (det.angle * 180) / math.Pi
angle := (det.faceAngle * 180) / math.Pi
rotated := imaging.Rotate(faceZone, 2*angle, color.Transparent)
final := imaging.FlipH(rotated)

Expand All @@ -422,12 +418,12 @@ func (fd *faceDetector) drawFaces(faces []pigo.Detection, marker string) ([]dete
Row: face.Row - int(0.075*float32(face.Scale)),
Col: face.Col + int(0.185*float32(face.Scale)),
Scale: float32(face.Scale) * 0.25,
Perturbs: perturb,
Perturbs: perturbation,
}

rightEye := plc.RunDetector(puploc, *imgParams, det.angle, false)
rightEye := plc.RunClassifier(puploc, imgParams, det.faceAngle, false)
if rightEye.Row > 0 && rightEye.Col > 0 {
if det.angle > 0 {
if det.faceAngle > 0 {
drawEyeDetectionMarker(ctx,
float64(cols/2-(face.Col-rightEye.Col)),
float64(rows/2-(face.Row-rightEye.Row)),
Expand All @@ -436,7 +432,7 @@ func (fd *faceDetector) drawFaces(faces []pigo.Detection, marker string) ([]dete
det.markDetEyes,
)
// convert radians to angle
angle := (det.angle * 180) / math.Pi
angle := (det.faceAngle * 180) / math.Pi
rotated := imaging.Rotate(faceZone, 2*angle, color.Transparent)
final := imaging.FlipH(rotated)

Expand All @@ -460,7 +456,7 @@ func (fd *faceDetector) drawFaces(faces []pigo.Detection, marker string) ([]dete
if det.flploc {
for _, eye := range eyeCascades {
for _, flpc := range flpcs[eye] {
flp := flpc.LandmarkPoint(leftEye, rightEye, *imgParams, perturb, false)
flp := flpc.LandmarkPoint(leftEye, rightEye, imgParams, perturbation, false)
if flp.Row > 0 && flp.Col > 0 {
drawEyeDetectionMarker(dc,
float64(flp.Col),
Expand All @@ -476,7 +472,7 @@ func (fd *faceDetector) drawFaces(faces []pigo.Detection, marker string) ([]dete
})
}

flp = flpc.LandmarkPoint(leftEye, rightEye, *imgParams, perturb, true)
flp = flpc.LandmarkPoint(leftEye, rightEye, imgParams, perturbation, true)
if flp.Row > 0 && flp.Col > 0 {
drawEyeDetectionMarker(dc,
float64(flp.Col),
Expand All @@ -496,7 +492,7 @@ func (fd *faceDetector) drawFaces(faces []pigo.Detection, marker string) ([]dete

for _, mouth := range mouthCascades {
for _, flpc := range flpcs[mouth] {
flp := flpc.LandmarkPoint(leftEye, rightEye, *imgParams, perturb, false)
flp := flpc.LandmarkPoint(leftEye, rightEye, imgParams, perturbation, false)
if flp.Row > 0 && flp.Col > 0 {
drawEyeDetectionMarker(dc,
float64(flp.Col),
Expand All @@ -513,7 +509,7 @@ func (fd *faceDetector) drawFaces(faces []pigo.Detection, marker string) ([]dete
}
}
}
flp := flpcs["lp84"][0].LandmarkPoint(leftEye, rightEye, *imgParams, perturb, true)
flp := flpcs["lp84"][0].LandmarkPoint(leftEye, rightEye, imgParams, perturbation, true)
if flp.Row > 0 && flp.Col > 0 {
drawEyeDetectionMarker(dc,
float64(flp.Col),
Expand Down
150 changes: 150 additions & 0 deletions demos/native/facedet/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
package main

import (
"fmt"
"image"
"log"
"os"

"gioui.org/app"
"gioui.org/io/key"
"gioui.org/io/system"
"gioui.org/layout"
"gioui.org/op"
"gioui.org/op/paint"
"gioui.org/unit"
"gioui.org/widget"
demo "github.com/esimov/pigo/demos/native"
pigo "github.com/esimov/pigo/pkg"
"github.com/fogleman/gg"
"github.com/pion/mediadevices"
_ "github.com/pion/mediadevices/pkg/driver/camera" // This is required to register camera adapter
"github.com/pion/mediadevices/pkg/io/video"
"github.com/pion/mediadevices/pkg/prop"
)

const (
windowWidth = 1024
windowHeight = 640
)

var (
c *demo.Constructor
media video.Reader
)

func main() {
classifier := pigo.UnpackCascade()

mediaStream, err := mediadevices.GetUserMedia(mediadevices.MediaStreamConstraints{
Video: func(c *mediadevices.MediaTrackConstraints) {
c.Width = prop.Int(windowWidth)
c.Height = prop.Int(windowHeight)
},
})
if err != nil {
log.Fatalf("failed to detect user media: %v", err)
}

imgCtx := gg.NewContext(windowWidth, windowHeight)
c, err = demo.NewConstructor(imgCtx, classifier, nil, nil)
if err != nil {
log.Fatalf("failed to instantiate constructor: %v", err)
}

// since we're trying to access the raw data, we need to cast Track to its real type, *mediadevices.VideoTrack
videoTrack := mediaStream.GetVideoTracks()[0].(*mediadevices.VideoTrack)
defer videoTrack.Close()

media = videoTrack.NewReader(false)

go func() {
w := new(app.Window)
w.Option(
app.Title("PIGO - Face detection demo"),
app.Size(unit.Dp(windowWidth), unit.Dp(windowHeight)),
)

// Center window to the middle of the screen
w.Perform(system.ActionCenter)

if err := run(w); err != nil {
log.Fatal(err)
}

os.Exit(0)
}()

app.Main()
}

func run(w *app.Window) error {
var ops op.Ops

for {
switch e := w.Event().(type) {
case app.DestroyEvent:
return e.Err
case app.FrameEvent:
// This graphics context is used for managing the rendering state.
gtx := app.NewContext(&ops, e)

frame, release, err := media.Read()
if err != nil {
return fmt.Errorf("error encountered reading video frame: %w", err)
}

if img, ok := frame.(*image.YCbCr); ok {
scaleX := float64(windowWidth) / float64(img.Bounds().Dx())
scaleY := float64(windowHeight) / float64(img.Bounds().Dy())

c.ImgCtx.Push()
c.ImgCtx.Scale(scaleX, scaleY)
c.ImgCtx.DrawImage(frame, 0, 0)

c.DetectAndDraw(img)

c.ImgCtx.Pop()
}
release()

src := paint.NewImageOp(c.ImgCtx.Image())
src.Add(gtx.Ops)

layout.Stack{}.Layout(gtx,
layout.Stacked(func(gtx layout.Context) layout.Dimensions {
imageWidget := widget.Image{
Src: src,
Fit: widget.Fill,
Position: layout.Center,
}

return imageWidget.Layout(gtx)
}),
)

for {
event, ok := gtx.Event(key.Filter{
Name: key.NameEscape,
})
if !ok {
break
}
switch event := event.(type) {
case key.Event:
switch event.Name {
case key.NameEscape:
w.Perform(system.ActionClose)
return nil
}
}
}

// Pass the drawing operations to the GPU.
e.Frame(gtx.Ops)

// Redraw the window immediately.
gtx.Execute(op.InvalidateCmd{})
}
}
}
Loading
Loading