Last active
April 16, 2021 19:26
-
-
Save deosjr/14bc5aa98ea9a391b9582001027bbaf3 to your computer and use it in GitHub Desktop.
Print a moustache on everyone's face using openCV
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"image" | |
"image/color" | |
"math" | |
"gocv.io/x/gocv" | |
) | |
const filled = -1 | |
const n = 50 | |
var black = color.RGBA{0, 0, 0, 0} | |
// adapted from gocv tutorial | |
func main() { | |
webcam, err := gocv.VideoCaptureDevice(0) | |
if err != nil { | |
panic(err) | |
} | |
defer webcam.Close() | |
window := gocv.NewWindow("Snorbot") | |
defer window.Close() | |
img := gocv.NewMat() | |
defer img.Close() | |
classifier := gocv.NewCascadeClassifier() | |
defer classifier.Close() | |
if !classifier.Load("../../gocv/data/haarcascade_frontalface_default.xml") { | |
fmt.Println("Error reading cascade file: data/haarcascade_frontalface_default.xml") | |
return | |
} | |
for { | |
if ok := webcam.Read(&img); !ok { | |
fmt.Printf("cannot read device\n") | |
return | |
} | |
if img.Empty() { | |
continue | |
} | |
rects := classifier.DetectMultiScale(img) | |
for _, r := range rects { | |
mid := r.Min.Add(r.Size().Div(2)).Add(image.Point{0, r.Dy() / 4}) | |
w := float64(r.Dx()) / 4.0 | |
h := float64(r.Dy()) / 16.0 | |
moustacheHalf(mid, &img, w, h, 1) | |
moustacheHalf(mid, &img, w, h, -1) | |
} | |
window.IMShow(img) | |
window.WaitKey(1) | |
} | |
} | |
func moustacheHalf(mid image.Point, img *gocv.Mat, w, h float64, mod int) { | |
pts := []image.Point{image.Pt(mid.X, mid.Y)} | |
for i := 0; i < n; i++ { | |
step := float64(i+1) / float64(n) | |
p := image.Pt(mid.X+mod*int(step*w), mid.Y-int(math.Sin(0.7*step*2*math.Pi)*h)) | |
pts = append(pts, p) | |
} | |
points := [][]image.Point{pts} | |
pv := gocv.NewPointsVectorFromPoints(points) | |
defer pv.Close() | |
gocv.FillPoly(img, pv, black) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment