Example #1
0
func main() {
	hd, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		panic(err)
	}

	cp := path.Join(hd, "haarcascade_frontalface_alt.xml")

	if _, err := os.Stat(cp); err != nil {
		panic(err)
	}

	cm := opencv.NewCameraCapture(0)
	cs := opencv.LoadHaarClassifierCascade(cp)

	p := &pair.Checker{Camera: cm, Cascade: cs}
	t, err := p.Present()

	if err != nil {
		panic(err)
	}

	if !t {
		os.Stderr.WriteString("Your pair must be playing ping pong\n")
		os.Exit(1)
	}
}
Example #2
0
func faceDetect(settings CropSettings, i image.Image, o image.Image) error {

	cvImage := opencv.FromImage(i)
	_, err := os.Stat(settings.FaceDetectionHaarCascadeFilepath)
	if err != nil {
		return err
	}
	cascade := opencv.LoadHaarClassifierCascade(settings.FaceDetectionHaarCascadeFilepath)
	faces := cascade.DetectObjects(cvImage)

	gc := draw2dimg.NewGraphicContext((o).(*image.RGBA))

	if settings.DebugMode == true {
		log.Println("Faces detected:", len(faces))
	}

	for _, face := range faces {
		if settings.DebugMode == true {
			log.Printf("Face: x: %d y: %d w: %d h: %d\n", face.X(), face.Y(), face.Width(), face.Height())
		}
		draw2dkit.Ellipse(
			gc,
			float64(face.X()+(face.Width()/2)),
			float64(face.Y()+(face.Height()/2)),
			float64(face.Width()/2),
			float64(face.Height())/2)
		gc.SetFillColor(color.RGBA{255, 0, 0, 255})
		gc.Fill()
	}
	return nil
}
Example #3
0
func detectFace(input *image.Image, multiple bool) (*bytes.Buffer, error) {
	daniel := opencv.LoadImage("static/daniel.jpg").ToImage()
	hdaniel := int(daniel.Bounds().Dy())
	wdaniel := int(daniel.Bounds().Dx())
	_image := opencv.FromImage(*input)
	cascade := opencv.LoadHaarClassifierCascade("haarcascade_frontalface_alt.xml")
	faces := cascade.DetectObjects(_image)
	found := false
	bounds := (*input).Bounds()
	output := image.NewRGBA(bounds)
	draw.Draw(output, bounds, *input, image.ZP, draw.Src)
	for _, value := range faces {
		x := int(value.X())
		y := int(value.Y())
		w := int(value.Width())
		h := int(value.Height())
		y2 := y + h
		h = hdaniel * w / wdaniel
		y = y2 - h
		danielTmp := resize.Resize(uint(w), uint(h), daniel, resize.Lanczos3)
		if multiple || !found {
			draw.Draw(output, image.Rect(x, y, x+w, y+h), danielTmp, image.ZP, draw.Src)
		}
		found = true
	}
	if !found {
		return nil, errors.New("No faces found")
	}
	toOut := new(bytes.Buffer)
	err := jpeg.Encode(toOut, output, nil)
	if err != nil {
		return nil, err
	}
	return toOut, nil
}
Example #4
0
func main() {
	cap := opencv.NewCameraCapture(0)
	if cap == nil {
		panic("can not open camera")
	}
	defer cap.Release()

	_, currentfile, _, _ := runtime.Caller(0)
	cascade := opencv.LoadHaarClassifierCascade(path.Join(path.Dir(currentfile), "haarcascade_frontalface_alt.xml"))
	timeout := time.Second * 10
	lastFace := time.Now()

	for {
		if cap.GrabFrame() {
			img := cap.RetrieveFrame(1)
			if img == nil {
				continue
			}
			hasFaces, _ := ProcessImage(img, cascade)
			if hasFaces {
				lastFace = time.Now()
			} else {
				delta := time.Since(lastFace)
				fmt.Println("no faces for %ts", delta)
				if delta > timeout {
					fmt.Println("lock!")
					lock()
					time.Sleep(time.Second * 60)
				}
			}
		}

		time.Sleep(time.Second)
	}
}
Example #5
0
func faceDetect(i *image.Image, o *image.Image) {

	cvImage := opencv.FromImage(*i)
	_, err := os.Stat(faceDetectionHaarCascade)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	cascade := opencv.LoadHaarClassifierCascade(faceDetectionHaarCascade)
	faces := cascade.DetectObjects(cvImage)

	gc := draw2dimg.NewGraphicContext((*o).(*image.RGBA))

	if debug == true {
		fmt.Println("Faces detected:", len(faces))
	}

	for _, face := range faces {
		if debug == true {
			fmt.Printf("Face: x: %d y: %d w: %d h: %d\n", face.X(), face.Y(), face.Width(), face.Height())
		}
		draw2dkit.Ellipse(
			gc,
			float64(face.X()+(face.Width()/2)),
			float64(face.Y()+(face.Height()/2)),
			float64(face.Width()/2),
			float64(face.Height())/2)
		gc.SetFillColor(color.RGBA{255, 0, 0, 255})
		gc.Fill()
	}

}
Example #6
0
func init() {

	if _, err := os.Stat(haarCascade); os.IsNotExist(err) {
		panic(haarCascade + " not found")
	}
	cascade = opencv.LoadHaarClassifierCascade(haarCascade)
	semaphore = make(chan struct{}, runtime.NumCPU())
}
Example #7
0
func NewEyeMarker(classifierPath string) *eyeMarker {
	//_, currentfile, _, _ := runtime.Caller(0)
	var classifierFile = opencv.LoadHaarClassifierCascade(classifierPath)

	if classifierFile == nil {
		panic("Classifier must not be nil")
	}
	return &eyeMarker{classifierFile, 0, []int{}, []int{}}
}
Example #8
0
func NewFaceDetector() *FaceDetector {

	detector := &FaceDetector{
		eyeCascade:      opencv.LoadHaarClassifierCascade("/home/joakim/opencv-2.4.9/data/haarcascades/haarcascade_eye.xml"),
		glassesCascade:  opencv.LoadHaarClassifierCascade("/home/joakim/opencv-2.4.9/data/haarcascades/haarcascade_eye_tree_eyeglasses.xml"),
		lefteyeCascade:  opencv.LoadHaarClassifierCascade("/home/joakim/opencv-2.4.9/data/haarcascades/haarcascade_mcs_lefteye.xml"),
		righteyeCascade: opencv.LoadHaarClassifierCascade("/home/joakim/opencv-2.4.9/data/haarcascades/haarcascade_mcs_righteye.xml"),
		faceCascade:     opencv.LoadHaarClassifierCascade("/home/joakim/Go/src/github.com/lazywei/go-opencv/samples/haarcascade_frontalface_alt.xml"),
		mouthCascade:    opencv.LoadHaarClassifierCascade("/home/joakim/opencv-2.4.9/data/haarcascades/haarcascade_mcs_mouth.xml"),
		noseCascade:     opencv.LoadHaarClassifierCascade("/home/joakim/opencv-2.4.9/data/haarcascades/haarcascade_mcs_nose.xml"),
	}
	return detector
}
Example #9
0
func main() {
	_, currentfile, _, _ := runtime.Caller(0)
	image := opencv.LoadImage(path.Join(path.Dir(currentfile), "../images/lena.jpg"))

	cascade := opencv.LoadHaarClassifierCascade(path.Join(path.Dir(currentfile), "haarcascade_frontalface_alt.xml"))
	faces := cascade.DetectObjects(image)

	for _, value := range faces {
		opencv.Rectangle(image,
			opencv.Point{value.X() + value.Width(), value.Y()},
			opencv.Point{value.X(), value.Y() + value.Height()},
			opencv.ScalarAll(255.0), 1, 1, 0)
	}

	win := opencv.NewWindow("Face Detection")
	win.ShowImage(image)
	opencv.WaitKey(0)
}
Example #10
0
func faceDetect(settings CropSettings, i image.Image, o image.Image, scale float64) ([]Face, error) {
	cvImage := opencv.FromImage(i)
	_, err := os.Stat(settings.FaceDetectionHaarCascadeFilepath)
	if err != nil {
		return []Face{}, err
	}

	cascade := opencv.LoadHaarClassifierCascade(settings.FaceDetectionHaarCascadeFilepath)
	faces := cascade.DetectObjects(cvImage)

	gc := draw2dimg.NewGraphicContext((o).(*image.RGBA))

	if settings.DebugMode == true {
		log.Println("Faces detected:", len(faces))
	}

	if len(faces) == 0 {
		return []Face{}, ErrNoFacesFound
	}

	resultFaces := []Face{}

	for _, face := range faces {
		if settings.DebugMode == true {
			log.Printf("Face: x: %d y: %d w: %d h: %d\n", face.X(), face.Y(), face.Width(), face.Height())
		}
		draw2dkit.Ellipse(
			gc,
			float64(face.X()+(face.Width()/2)),
			float64(face.Y()+(face.Height()/2)),
			float64(face.Width()/2),
			float64(face.Height())/2)
		gc.SetFillColor(color.RGBA{255, 0, 0, 255})
		gc.Fill()

		x := int(float64(face.X()) * scale)
		y := int(float64(face.Y()) * scale)
		width := int(float64(face.Width()) * scale)
		height := int(float64(face.Height()) * scale)
		resultFaces = append(resultFaces, Face{X: x, Y: y, Width: width, Height: height})
	}

	return resultFaces, nil
}
Example #11
0
func main() {
	win := opencv.NewWindow("Go-OpenCV Webcam Face Detection")
	defer win.Destroy()

	cap := opencv.NewCameraCapture(0)
	if cap == nil {
		panic("cannot open camera")
	}
	defer cap.Release()

	cwd, err := os.Getwd()
	if err != nil {
		panic(err)
	}
	cascade := opencv.LoadHaarClassifierCascade(path.Join(cwd, "haarcascade_frontalface_alt.xml"))

	fmt.Println("Press ESC to quit")
	for {
		if cap.GrabFrame() {
			img := cap.RetrieveFrame(1)
			if img != nil {
				faces := cascade.DetectObjects(img)
				for _, value := range faces {
					opencv.Circle(img,
						opencv.Point{
							value.X() + (value.Width() / 2),
							value.Y() + (value.Height() / 2),
						},
						value.Width()/2,
						opencv.ScalarAll(255.0), 1, 1, 0)
				}

				win.ShowImage(img)
			} else {
				fmt.Println("nil image")
			}
		}
		key := opencv.WaitKey(1)

		if key == 27 {
			os.Exit(0)
		}
	}
}
func ProcessbetterImage(img *opencv.IplImage, win *opencv.Window, pos int) error {
	_, currentfile, _, _ := runtime.Caller(0)
	//image := opencv.LoadImage(path.Join(path.Dir(currentfile), "../images/eye.jpg"))

	if counter == 1 {
		//find eye, cache them and then mark them
		counter = 0
		cachedPointsCenterY = []int{}
		cachedPointsCenterX = []int{}

		if haarClassifier == nil {
			//load and cache haarClassifier
			haarClassifier = opencv.LoadHaarClassifierCascade(path.Join(path.Dir(currentfile), "/cascades/haarcascade_eye_tree_eyeglasses.xml"))
		}

		rects := haarClassifier.DetectObjects(img)

		for _, value := range rects {

			var pointRect1 = opencv.Point{value.X() + value.Width(), value.Y()}
			var pointRect2 = opencv.Point{value.X(), value.Y() + value.Height()}
			var centerPointX = int((pointRect1.X + pointRect2.X) / 2)
			var centerPointY = int((pointRect1.Y + pointRect2.Y) / 2)

			var center = opencv.Point{centerPointX, centerPointY}
			cachedPointsCenterX = append(cachedPointsCenterX, center.X)
			cachedPointsCenterY = append(cachedPointsCenterY, center.Y)

			//draw eye marker
			drawEyeMarker(img, center)
		}
	} else {
		//if we have a cached value
		for i := 0; i < len(cachedPointsCenterY); i++ {
			drawEyeMarker(img, opencv.Point{cachedPointsCenterX[i], cachedPointsCenterY[i]})
		}

	}
	win.ShowImage(img)
	//counter for cache
	counter = counter + 1
	return nil
}
Example #13
0
//detects faces and crops em out
func cropFaces(inputs []string, dirOut string, harrcascade string) {
	err := os.MkdirAll(dirOut, 0777) // makes dir if not exists
	if err != nil {
		fmt.Printf("Could not create directory %s\n", dirOut)
		log.Fatal(err)
	}

	fmt.Printf("Cropping %d images.\n", len(inputs))

	for _, element := range inputs {

		outPath := dirOut + "face_" + filepath.Base(element)

		image := opencv.LoadImage(element)
		if image == nil {
			panic("Loading Image " + element + "failed")
		}
		defer image.Release()

		//detect some faces
		cascade := opencv.LoadHaarClassifierCascade(harrcascade)
		faces := cascade.DetectObjects(image)
		if len(faces) == 0 {
			fmt.Printf("Found no face in %s\n", element)
		}

		for _, value := range faces {
			//Some invalid stuff filtering
			if value.Width() < image.Width() && value.Height() < image.Height() && value.Width() > 0 && value.Height() > 0 {
				//crop out the face
				crop := opencv.Crop(image, value.X(), value.Y(), value.Width(), value.Height())
				//save cropped
				opencv.SaveImage(outPath, crop, 0)
				crop.Release()
			} else {
				fmt.Printf("Couldn't save: %s", value)
			}
		}
	}
}
func main() {

	cap := opencv.NewCameraCapture(0)
	if cap == nil {
		panic("cannot open camera")
	}
	defer cap.Release()

	cwd, err := os.Getwd()
	if err != nil {
		panic(err)
	}
	cascade := opencv.LoadHaarClassifierCascade(path.Join(cwd, "haarcascade_frontalface_alt.xml"))

	fmt.Println("Press ESC to quit")
	for {
		if cap.GrabFrame() {
			img := cap.RetrieveFrame(1)
			if img != nil {
				faces := cascade.DetectObjects(img)
				for _, value := range faces {
					leftX := value.X()
					rightX := leftX + value.Width()
					lowY := value.Y()
					highY := lowY + value.Height()
					log.Println("Face Seen! LowLeft Corner: (", leftX, ", ", lowY, "), UpRight Corner: (", rightX, ", ", highY, ")")
				}

			} else {
				fmt.Println("nil image")
			}
		}
		key := opencv.WaitKey(1)

		if key == 27 {
			os.Exit(0)
		}
	}
}
Example #15
0
func faces(r io.Reader) ([]*Face, error) {
	cascade := opencv.LoadHaarClassifierCascade(path.Join(currentDir(), "haarcascade_frontalface_alt.xml"))
	return detect(cascade, r)
}
func (s smartcropResizer) smartResize(input image.Image, dstWidth, dstHeight int) (image.Image, error) {
	if dstWidth < 0 || dstHeight < 0 {
		return nil, fmt.Errorf("Please specify both width and height for your target image")
	}

	scaledInput, scale, err := normalizeInput(input, 1024)
	if err != nil {
		return input, err
	}

	cvImage := opencv.FromImage(scaledInput)
	_, err = os.Stat(s.haarcascade)
	if err != nil {
		return input, err
	}

	cascade := opencv.LoadHaarClassifierCascade(s.haarcascade)
	faces := cascade.DetectObjects(cvImage)

	if len(faces) == 0 {
		return nil, ErrNoFacesFound
	}

	var biggestFace *opencv.Rect

	for _, f := range faces {
		if biggestFace == nil {
			biggestFace = f
			continue
		}

		biggestArea := biggestFace.Width() * biggestFace.Height()
		currentArea := f.Width() * f.Height()
		if biggestArea < currentArea {
			biggestFace = f
		}
	}

	log.Printf("Faces found %d\n", len(faces))

	if biggestFace == nil {
		return nil, ErrNoFacesFound
	}

	faceArea := biggestFace.Width() * biggestFace.Height()
	imagePixels := scaledInput.Bounds().Dx() * scaledInput.Bounds().Dy()

	faceAreaPercentage := float64(faceArea) / float64(imagePixels)
	if faceAreaPercentage < faceImageTreshold {
		return nil, fmt.Errorf("face area too small: %.2f.\n", faceAreaPercentage)
	}

	if sub, ok := input.(subImager); ok {
		x := int(float64(biggestFace.X()) * scale)
		y := int(float64(biggestFace.Y()) * scale)
		width := int(float64(biggestFace.Width()) * scale)
		height := int(float64(biggestFace.Height()) * scale)

		facePoint := image.Pt(x, y)
		target := image.Rect(0, 0, int(float64(dstWidth)*scale), int(float64(dstHeight)*scale))
		r := image.Rect(0, 0, x+width, y+height).Add(facePoint)
		for !target.In(r) && r.Min.X > 0 && r.Min.Y > 0 {
			r = image.Rect(r.Min.X-1, r.Min.Y-1, r.Max.X+1, r.Max.Y+1)
		}

		cropImage := sub.SubImage(r)
		return imaging.Thumbnail(cropImage, dstWidth, dstHeight, imaging.Lanczos), nil
	}

	return input, err
}
Example #17
0
func processResponse(resp *http.Response) error {
	var imgExtension string

	// skip not modified or other weird headers that dont include payload
	if resp.StatusCode != 200 {
		return nil
	}

	// skip gzipped assets that ignored us when told no gzip
	if "gzip" == resp.Header.Get("Content-Encoding") {
		return nil
	}

	switch resp.Header.Get("Content-Type") {
	case "image/jpeg":
		imgExtension = ".jpg"
	case "image/png":
		imgExtension = ".png"
	case "image/gif":
		imgExtension = ".gif"
	}

	if "" != imgExtension {
		//log.Println("Processing", resp.Request.Method, resp.Request.URL.String())
		// save locally
		fileName := path.Join(os.TempDir(), strconv.FormatInt(time.Now().UnixNano(), 10)+imgExtension)
		file, _ := os.Create(fileName)
		defer os.Remove(fileName)

		// dump Body to file
		io.Copy(file, resp.Body)
		file.Close()
		resp.Body.Close()

		// detect faces
		image := opencv.LoadImage(fileName, -1)
		defer image.Release()
		if image != nil {
			cascade := opencv.LoadHaarClassifierCascade("./deface_files/haarcascade_frontalface_alt.xml")
			faces := cascade.DetectObjects(image)

			// replace faces
			if len(faces) > 0 {
				rageGuy := opencv.LoadImage("./deface_files/rage-guy.png", -1)
				defer rageGuy.Release()
				for _, value := range faces {
					faceWidth := value.Width()
					faceHeight := value.Height()
					faceX := value.X()
					faceY := value.Y()
					if (faceWidth <= 0) || (faceHeight <= 0) || (faceX > image.Width()) || (faceY > image.Height()) {
						//log.Println("Invalid rectangle for", resp.Request.Method, resp.Request.URL.String(), faceWidth, faceHeight, faceX, faceY)
						continue
					}

					resizedRageGuy := opencv.Resize(rageGuy, faceWidth, faceHeight, 0)
					rect := &opencv.Rect{}
					rect.Init(faceX, faceY, faceWidth, faceHeight)
					image.SetROI(*rect)
					// blending them horribly inefficiently because cvSplit/cvThreshold are not exposed in go
					// and dont want to link to C
					for y := 0; y < resizedRageGuy.Height(); y++ {
						for x := 0; x < resizedRageGuy.Width(); x++ {
							src := image.Get2D(x, y).Val()
							overlay := resizedRageGuy.Get2D(x, y).Val()
							if overlay[3] > 0 {
								image.Set2D(x, y, opencv.NewScalar(overlay[0], overlay[1], overlay[2], src[3]))
							}
						}
					}
					image.ResetROI()
					resizedRageGuy.Release()
				}
			}

			// save modified image and pass it to Body
			opencv.SaveImage(fileName, image, 0)
		} else {
			//log.Println("Couldnt load image", resp.Request.Method, resp.Request.URL.String())
		}

		file, _ = os.Open(fileName)
		resp.Body = ioutil.NopCloser(file)

		// update content length
		fileInfo, _ := file.Stat()
		resp.ContentLength = fileInfo.Size()
		resp.Header.Set("Content-Length", strconv.FormatInt(fileInfo.Size(), 10))
	}

	return nil
}
Example #18
0
// loadHaarClassifierCascade returns open cv HaarCascade loaded
func loadHaarClassifierCascade(haar string) *cv.HaarCascade {
	return cv.LoadHaarClassifierCascade(haar)
}