2021-07-16 14:34:05 +02:00
|
|
|
package face
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"fmt"
|
|
|
|
"image"
|
|
|
|
"io/ioutil"
|
2021-08-11 13:21:05 +02:00
|
|
|
"os"
|
2021-07-16 14:34:05 +02:00
|
|
|
"path"
|
|
|
|
"path/filepath"
|
|
|
|
"runtime/debug"
|
|
|
|
"sync"
|
|
|
|
|
2021-08-11 13:21:05 +02:00
|
|
|
"github.com/photoprism/photoprism/pkg/fs"
|
|
|
|
|
2021-07-16 14:34:05 +02:00
|
|
|
"github.com/disintegration/imaging"
|
|
|
|
"github.com/photoprism/photoprism/pkg/txt"
|
|
|
|
tf "github.com/tensorflow/tensorflow/tensorflow/go"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Net is a wrapper for the TensorFlow Facenet model.
|
|
|
|
type Net struct {
|
|
|
|
model *tf.SavedModel
|
|
|
|
modelPath string
|
2021-08-11 13:21:05 +02:00
|
|
|
cachePath string
|
2021-07-16 14:34:05 +02:00
|
|
|
disabled bool
|
|
|
|
modelName string
|
|
|
|
modelTags []string
|
|
|
|
mutex sync.Mutex
|
|
|
|
}
|
|
|
|
|
2021-08-11 13:21:05 +02:00
|
|
|
// NewNet returns a new TensorFlow Facenet instance.
|
|
|
|
func NewNet(modelPath, cachePath string, disabled bool) *Net {
|
|
|
|
if err := os.MkdirAll(filepath.Join(cachePath, "faces"), os.ModePerm); err != nil {
|
|
|
|
log.Errorf("faces: failed creating cache folder")
|
|
|
|
}
|
|
|
|
|
|
|
|
return &Net{modelPath: modelPath, cachePath: cachePath, disabled: disabled, modelTags: []string{"serve"}}
|
2021-07-16 14:34:05 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Detect runs the detection and facenet algorithms over the provided source image.
|
|
|
|
func (t *Net) Detect(fileName string) (faces Faces, err error) {
|
|
|
|
faces, err = Detect(fileName)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return faces, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if t.disabled {
|
|
|
|
return faces, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
err = t.loadModel()
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return faces, err
|
|
|
|
}
|
|
|
|
|
2021-08-11 13:21:05 +02:00
|
|
|
fileHash := fs.Hash(fileName)
|
|
|
|
|
2021-07-16 14:34:05 +02:00
|
|
|
for i, f := range faces {
|
|
|
|
if f.Face.Col == 0 && f.Face.Row == 0 {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2021-09-01 20:46:15 +02:00
|
|
|
if img, err := t.getFaceCrop(fileName, fileHash, &faces[i]); err != nil {
|
2021-08-11 13:21:05 +02:00
|
|
|
log.Errorf("faces: failed to decode image: %v", err)
|
|
|
|
} else if embeddings := t.getEmbeddings(img); len(embeddings) > 0 {
|
|
|
|
faces[i].Embeddings = embeddings
|
2021-07-16 14:34:05 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return faces, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// ModelLoaded tests if the TensorFlow model is loaded.
|
|
|
|
func (t *Net) ModelLoaded() bool {
|
|
|
|
return t.model != nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t *Net) loadModel() error {
|
|
|
|
t.mutex.Lock()
|
|
|
|
defer t.mutex.Unlock()
|
|
|
|
|
|
|
|
if t.ModelLoaded() {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
modelPath := path.Join(t.modelPath)
|
|
|
|
|
2021-08-11 13:21:05 +02:00
|
|
|
log.Infof("faces: loading %s", txt.Quote(filepath.Base(modelPath)))
|
2021-07-16 14:34:05 +02:00
|
|
|
|
|
|
|
// Load model
|
|
|
|
model, err := tf.LoadSavedModel(modelPath, t.modelTags, nil)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
t.model = model
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-09-01 20:46:15 +02:00
|
|
|
func (t *Net) getFaceCrop(fileName, fileHash string, f *Face) (img image.Image, err error) {
|
|
|
|
if f == nil {
|
|
|
|
return img, fmt.Errorf("face is nil")
|
|
|
|
}
|
|
|
|
|
|
|
|
area := f.Face
|
|
|
|
|
2021-08-11 13:21:05 +02:00
|
|
|
cacheFolder := filepath.Join(t.cachePath, "faces", string(fileHash[0]), string(fileHash[1]), string(fileHash[2]))
|
|
|
|
|
|
|
|
if err := os.MkdirAll(cacheFolder, os.ModePerm); err != nil {
|
|
|
|
log.Errorf("faces: failed creating cache folder")
|
|
|
|
}
|
|
|
|
|
2021-09-01 20:46:15 +02:00
|
|
|
f.Thumb = fmt.Sprintf("%s-%s", fileHash, area.String())
|
|
|
|
cacheFile := filepath.Join(cacheFolder, f.Thumb+fs.JpegExt)
|
2021-08-11 13:21:05 +02:00
|
|
|
|
|
|
|
if !fs.FileExists(cacheFile) {
|
|
|
|
// Do nothing.
|
|
|
|
} else if img, err := imaging.Open(cacheFile); err != nil {
|
2021-08-12 12:05:10 +02:00
|
|
|
log.Errorf("faces: failed loading cached crop %s", filepath.Base(cacheFile))
|
2021-08-11 13:21:05 +02:00
|
|
|
} else {
|
2021-08-13 20:04:59 +02:00
|
|
|
log.Debugf("faces: using cached crop %s", filepath.Base(cacheFile))
|
2021-08-11 13:21:05 +02:00
|
|
|
return img, nil
|
|
|
|
}
|
|
|
|
|
2021-09-01 20:46:15 +02:00
|
|
|
x, y := area.TopLeft()
|
2021-07-16 14:34:05 +02:00
|
|
|
|
|
|
|
imageBuffer, err := ioutil.ReadFile(fileName)
|
2021-08-11 13:21:05 +02:00
|
|
|
img, err = imaging.Decode(bytes.NewReader(imageBuffer), imaging.AutoOrientation(true))
|
|
|
|
|
2021-07-16 14:34:05 +02:00
|
|
|
if err != nil {
|
2021-08-11 13:21:05 +02:00
|
|
|
return img, err
|
2021-07-16 14:34:05 +02:00
|
|
|
}
|
|
|
|
|
2021-09-01 20:46:15 +02:00
|
|
|
img = imaging.Crop(img, image.Rect(y, x, y+area.Scale, x+area.Scale))
|
2021-08-29 13:26:05 +02:00
|
|
|
img = imaging.Fill(img, CropSize, CropSize, imaging.Center, imaging.Lanczos)
|
2021-07-16 14:34:05 +02:00
|
|
|
|
2021-08-11 13:21:05 +02:00
|
|
|
if err := imaging.Save(img, cacheFile); err != nil {
|
2021-08-12 12:05:10 +02:00
|
|
|
log.Errorf("faces: failed caching crop %s", filepath.Base(cacheFile))
|
2021-08-11 13:21:05 +02:00
|
|
|
} else {
|
2021-08-12 12:05:10 +02:00
|
|
|
log.Debugf("faces: saved crop %s", filepath.Base(cacheFile))
|
2021-08-11 13:21:05 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return img, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t *Net) getEmbeddings(img image.Image) [][]float32 {
|
2021-08-29 13:26:05 +02:00
|
|
|
tensor, err := imageToTensor(img, CropSize, CropSize)
|
2021-07-16 14:34:05 +02:00
|
|
|
|
|
|
|
if err != nil {
|
2021-08-11 13:21:05 +02:00
|
|
|
log.Errorf("faces: failed to convert image to tensor: %v", err)
|
2021-07-16 14:34:05 +02:00
|
|
|
}
|
2021-08-12 12:05:10 +02:00
|
|
|
|
2021-08-29 13:26:05 +02:00
|
|
|
// TODO: pre-whiten image as in facenet
|
2021-07-16 14:34:05 +02:00
|
|
|
|
|
|
|
trainPhaseBoolTensor, err := tf.NewTensor(false)
|
2021-08-12 12:05:10 +02:00
|
|
|
|
2021-07-16 14:34:05 +02:00
|
|
|
output, err := t.model.Session.Run(
|
|
|
|
map[tf.Output]*tf.Tensor{
|
|
|
|
t.model.Graph.Operation("input").Output(0): tensor,
|
|
|
|
t.model.Graph.Operation("phase_train").Output(0): trainPhaseBoolTensor,
|
|
|
|
},
|
|
|
|
[]tf.Output{
|
|
|
|
t.model.Graph.Operation("embeddings").Output(0),
|
|
|
|
},
|
|
|
|
nil)
|
|
|
|
|
|
|
|
if err != nil {
|
2021-08-11 13:21:05 +02:00
|
|
|
log.Errorf("faces: %s", err)
|
2021-07-16 14:34:05 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
if len(output) < 1 {
|
2021-08-11 13:21:05 +02:00
|
|
|
log.Errorf("faces: inference failed, no output")
|
2021-07-16 14:34:05 +02:00
|
|
|
} else {
|
|
|
|
return output[0].Value().([][]float32)
|
|
|
|
}
|
2021-08-12 12:05:10 +02:00
|
|
|
|
2021-07-16 14:34:05 +02:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func imageToTensor(img image.Image, imageHeight, imageWidth int) (tfTensor *tf.Tensor, err error) {
|
|
|
|
defer func() {
|
|
|
|
if r := recover(); r != nil {
|
2021-08-11 13:21:05 +02:00
|
|
|
err = fmt.Errorf("faces: %s (panic)\nstack: %s", r, debug.Stack())
|
2021-07-16 14:34:05 +02:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
if imageHeight <= 0 || imageWidth <= 0 {
|
2021-08-11 13:21:05 +02:00
|
|
|
return tfTensor, fmt.Errorf("faces: image width and height must be > 0")
|
2021-07-16 14:34:05 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
var tfImage [1][][][3]float32
|
|
|
|
|
|
|
|
for j := 0; j < imageHeight; j++ {
|
|
|
|
tfImage[0] = append(tfImage[0], make([][3]float32, imageWidth))
|
|
|
|
}
|
|
|
|
|
|
|
|
for i := 0; i < imageWidth; i++ {
|
|
|
|
for j := 0; j < imageHeight; j++ {
|
|
|
|
r, g, b, _ := img.At(i, j).RGBA()
|
|
|
|
tfImage[0][j][i][0] = convertValue(r)
|
|
|
|
tfImage[0][j][i][1] = convertValue(g)
|
|
|
|
tfImage[0][j][i][2] = convertValue(b)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return tf.NewTensor(tfImage)
|
|
|
|
}
|
|
|
|
|
|
|
|
func convertValue(value uint32) float32 {
|
|
|
|
return (float32(value>>8) - float32(127.5)) / float32(127.5)
|
|
|
|
}
|