登录
首页 >  Golang >  Go问答

Golang go-face:如何进行全面的人脸捕捉

来源:stackoverflow

时间:2024-02-17 10:18:17 148浏览 收藏

本篇文章主要是结合我之前面试的各种经历和实战开发中遇到的问题解决经验整理的,希望这篇《Golang go-face:如何进行全面的人脸捕捉》对你有很大帮助!欢迎收藏,分享给更多的需要的朋友学习~

问题内容

我正在使用 https://github.com/kagami/go-face 在 golang 中进行人脸识别,我尝试了 go-face 库中给出的示例。在该示例中,它检测图像中有多少张脸,并将脸部图像与其他多个脸部图像进行分类。

现在我只想在循环面部范围时裁剪每个面部。如果有人在捕捉每张面孔时遇到同样的问题,请尝试这个示例答案。

package main

import (
    "fmt"
    "log"
    "path/filepath"

    "github.com/Kagami/go-face"
)

// Path to directory with models and test images. Here it's assumed it
// points to the  clone.
const dataDir = "testdata"

var (
    modelsDir = filepath.Join(dataDir, "models")
    imagesDir = filepath.Join(dataDir, "images")
)

// This example shows the basic usage of the package: create an
// recognizer, recognize faces, classify them using few known ones.
func main() {
    // Init the recognizer.
    rec, err := face.NewRecognizer(modelsDir)
    if err != nil {
        log.Fatalf("Can't init face recognizer: %v", err)
    }
    // Free the resources when you're finished.
    defer rec.Close()

    // Test image with 10 faces.
    testImagePristin := filepath.Join(imagesDir, "pristin.jpg")
    // Recognize faces on that image.
    faces, err := rec.RecognizeFile(testImagePristin)
    if err != nil {
        log.Fatalf("Can't recognize: %v", err)
    }
    if len(faces) != 10 {
        log.Fatalf("Wrong number of faces")
    }

    // Fill known samples. In the real world you would use a lot of images
    // for each person to get better classification results but in our
    // example we just get them from one big image.
    var samples []face.Descriptor
    var cats []int32
    for i, f := range faces {
        samples = append(samples, f.Descriptor)
        // Each face is unique on that image so goes to its own category.
        cats = append(cats, int32(i))
    }
    // Name the categories, i.e. people on the image.
    labels := []string{
        "Sungyeon", "Yehana", "Roa", "Eunwoo", "Xiyeon",
        "Kyulkyung", "Nayoung", "Rena", "Kyla", "Yuha",
    }
    // Pass samples to the recognizer.
    rec.SetSamples(samples, cats)

    // Now let's try to classify some not yet known image.
    testImageNayoung := filepath.Join(imagesDir, "nayoung.jpg")
    nayoungFace, err := rec.RecognizeSingleFile(testImageNayoung)
    if err != nil {
        log.Fatalf("Can't recognize: %v", err)
    }
    if nayoungFace == nil {
        log.Fatalf("Not a single face on the image")
    }
    catID := rec.Classify(nayoungFace.Descriptor)
    if catID < 0 {
        log.Fatalf("Can't classify")
    }
    // Finally print the classified label. It should be "Nayoung".
    fmt.Println(labels[catID])
}

正确答案


将使用face.rectangle点来捕捉每个面

package main

import (
    "fmt"
    "log"
    "path/filepath"

    "github.com/Kagami/go-face"
)

// Path to directory with models and test images. Here it's assumed it
// points to the  clone.
const dataDir = "testdata"

var (
    modelsDir = filepath.Join(dataDir, "models")
    imagesDir = filepath.Join(dataDir, "images")
)

// This example shows the basic usage of the package: create an
// recognizer, recognize faces, classify them using few known ones.
func main() {
    // Init the recognizer.
    rec, err := face.NewRecognizer(modelsDir)
    if err != nil {
        log.Fatalf("Can't init face recognizer: %v", err)
    }
    // Free the resources when you're finished.
    defer rec.Close()

    // Test image with 10 faces.
    testImagePristin := filepath.Join(imagesDir, "pristin.jpg")
    // Recognize faces on that image.
    faces, err := rec.RecognizeFile(testImagePristin)
    if err != nil {
        log.Fatalf("Can't recognize: %v", err)
    }
    if len(faces) != 10 {
        log.Fatalf("Wrong number of faces")
    }

    // Fill known samples. In the real world you would use a lot of images
    // for each person to get better classification results but in our
    // example we just get them from one big image.
    var samples []face.Descriptor
    var cats []int32
    for i, f := range faces {
   // Croping each face and save as image for reference
    err := saveFace(f.Rectangle.Min.X, f.Rectangle.Min.Y, f.Rectangle.Max.X, 
        f.Rectangle.Max.Y, int(i))
    

         if err != nil {
            fmt.Println(err)
        }

        samples = append(samples, f.Descriptor)
        // Each face is unique on that image so goes to its own category.
        cats = append(cats, int32(i))
    }
    // Name the categories, i.e. people on the image.
    labels := []string{
        "Sungyeon", "Yehana", "Roa", "Eunwoo", "Xiyeon",
        "Kyulkyung", "Nayoung", "Rena", "Kyla", "Yuha",
    }
    // Pass samples to the recognizer.
    rec.SetSamples(samples, cats)

    // Now let's try to classify some not yet known image.
    testImageNayoung := filepath.Join(imagesDir, "nayoung.jpg")
    nayoungFace, err := rec.RecognizeSingleFile(testImageNayoung)
    if err != nil {
        log.Fatalf("Can't recognize: %v", err)
    }
    if nayoungFace == nil {
        log.Fatalf("Not a single face on the image")
    }
    catID := rec.Classify(nayoungFace.Descriptor)
    if catID < 0 {
        log.Fatalf("Can't classify")
    }
    // Finally print the classified label. It should be "Nayoung".
    fmt.Println(labels[catID])
}

func saveFace(top int, bottom int, right int, left int, fid int) error {
    testImagePristin := filepath.Join(imagesDir, "pristin.jpg")

    img, err := readImage(testImagePristin)
    if err != nil {
        return err
    }
    img, err = cropImage(img, image.Rect(top, bottom, right, left))
    if err != nil {
        return err
    }
    facePath := fmt.Sprintf("images/%d.png", fid)
    return writeImage(img, facePath)

}

// readImage reads a image file from disk.
func readImage(name string) (image.Image, error) {
    testImagePristin := filepath.Join(imagesDir, "pristin.jpg")

    fd, err := os.Open(testImagePristin)
    if err != nil {
        return nil, err
    }
    defer fd.Close()

    // image.Decode requires that you import the right image package. We've
    // decode jpeg files then we would need to import "image/jpeg".
    img, _, err := image.Decode(fd)
    if err != nil {
        return nil, err
    }

    return img, nil
}

// cropImage takes an image and crops it to the specified rectangle.
func cropImage(img image.Image, crop image.Rectangle) (image.Image, error) {
    type subImager interface {
        SubImage(r image.Rectangle) image.Image
        //Newfunc() int
    }

    // method called SubImage. If it does, then we can use SubImage to crop the
    // image.
    simg, ok := img.(subImager)
    if !ok {
        return nil, fmt.Errorf("image does not support cropping")
    }

    return simg.SubImage(crop), nil
}

// writeImage writes an Image back to the disk.
func writeImage(img image.Image, name string) error {
    fd, err := os.Create(name)
    if err != nil {
        return err
    }
    defer fd.Close()

    return png.Encode(fd, img)
}

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>