Exemple #1
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
}
Exemple #2
0
func TestWindowDriverShowImage(t *testing.T) {
	d := initTestWindowDriver()
	_, currentfile, _, _ := runtime.Caller(0)
	image := cv.LoadImage(path.Join(path.Dir(currentfile), "lena-256x256.jpg"))
	d.Start()
	d.ShowImage(image)
}
Exemple #3
0
func main() {
	_, currentfile, _, _ := runtime.Caller(0)
	filename := path.Join(path.Dir(currentfile), "./images/gopher.png")
	if len(os.Args) == 2 {
		filename = os.Args[1]
	}

	image := opencv.LoadImage(filename)
	if image == nil {
		panic("LoadImage fail")
	}
	defer image.Release()

	win := opencv.NewWindow("Go-OpenCV")
	defer win.Destroy()

	win.SetMouseCallback(func(event, x, y, flags int) {
		fmt.Printf("event = %d, x = %d, y = %d, flags = %d\n",
			event, x, y, flags,
		)
	})
	win.CreateTrackbar("Thresh", 1, 100, func(pos int) {
		fmt.Printf("pos = %d\n", pos)
	})

	win.ShowImage(image)

	opencv.WaitKey(0)
}
Exemple #4
0
func TestUtils(t *testing.T) {
	_, currentfile, _, _ := runtime.Caller(0)
	image := cv.LoadImage(path.Join(path.Dir(currentfile), "lena-256x256.jpg"))
	rect := DetectFaces("haarcascade_frontalface_alt.xml", image)
	gobottest.Refute(t, len(rect), 0)
	gobottest.Refute(t, DrawRectangles(image, rect, 0, 0, 0, 0), nil)
}
Exemple #5
0
func main() {
	filename := "../images/lena.jpg"
	if len(os.Args) == 2 {
		filename = os.Args[1]
	}

	image := opencv.LoadImage(filename)
	if image == nil {
		panic("LoadImage fail")
	}
	defer image.Release()

	win := opencv.NewWindow("Go-OpenCV")
	defer win.Destroy()

	win.SetMouseCallback(func(event, x, y, flags int) {
		fmt.Printf("event = %d, x = %d, y = %d, flags = %d\n",
			event, x, y, flags,
		)
	})
	win.CreateTrackbar("Thresh", 1, 100, func(pos int) {
		fmt.Printf("pos = %d\n", pos)
	})

	win.ShowImage(image)

	opencv.WaitKey(0)
}
Exemple #6
0
func resize(path string, fileInfo os.FileInfo, err error) error {
	if fileInfo.IsDir() {
		return nil
	}
	//fmt.Printf("Processing: %s\n", path)

	srcImg := opencv.LoadImage(path)
	if srcImg == nil {
		return errors.New("Error loading image: " + path)
	}
	defer srcImg.Release()

	var fileName = fileInfo.Name()
	var extension = filepath.Ext(fileName)
	var nameNoExt = strings.TrimRight(fileName, extension)

	for _, res := range resolutions {
		//fmt.Printf("Resolution %dx%d\n", res.width, res.height)
		thumbW := res.width
		thumbH := res.height
		thumbnail := opencv.Resize(srcImg, int(thumbW), int(thumbH), 1)
		name := filepath.Join(destDir, fmt.Sprintf("%s__%dx%d_%d_%s", nameNoExt, res.width, res.height, time.Now().Unix(), extension))

		opencv.SaveImage(name, thumbnail, 0)
	}
	//fmt.Printf("Done processing: %s\n", path)
	return nil
}
Exemple #7
0
func main() {
	filename := "demo.jpg"
	srcImg := opencv.LoadImage(filename)
	if srcImg == nil {
		panic("Loading Image failed")
	}
	defer srcImg.Release()
	resized1 := opencv.Resize(srcImg, 400, 0, 0)
	resized2 := opencv.Resize(srcImg, 300, 500, 0)
	resized3 := opencv.Resize(srcImg, 300, 500, 2)
	opencv.SaveImage("resized1.jpg", resized1, 0)
	opencv.SaveImage("resized2.jpg", resized2, 0)
	opencv.SaveImage("resized3.jpg", resized3, 0)
}
Exemple #8
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)
}
Exemple #9
0
func main() {
	_, currentfile, _, _ := runtime.Caller(0)
	filename := path.Join(path.Dir(currentfile), "../images/lena.jpg")
	if len(os.Args) == 2 {
		filename = os.Args[1]
	}

	image := opencv.LoadImage(filename)
	if image == nil {
		panic("LoadImage fail")
	}
	defer image.Release()

	crop := opencv.Crop(image, 0, 0, 50, 50)
	opencv.SaveImage("/tmp/crop.jpg", crop, 0)
	crop.Release()

	os.Exit(0)
}
Exemple #10
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)
			}
		}
	}
}
Exemple #11
0
func main() {
	filename := "../images/fruits.jpg"
	if len(os.Args) == 2 {
		filename = os.Args[1]
	}

	img0 := opencv.LoadImage(filename)
	if img0 == nil {
		panic("LoadImage fail")
	}
	defer img0.Release()

	fmt.Print("Hot keys: \n",
		"\tESC - quit the program\n",
		"\tr - restore the original image\n",
		"\ti or ENTER - run inpainting algorithm\n",
		"\t\t(before running it, paint something on the image)\n",
	)

	img := img0.Clone()
	inpainted := img0.Clone()
	inpaint_mask := opencv.CreateImage(img0.Width(), img0.Height(), 8, 1)

	opencv.Zero(inpaint_mask)
	//opencv.Zero( inpainted )

	win := opencv.NewWindow("image")
	defer win.Destroy()

	prev_pt := opencv.Point{-1, -1}
	win.SetMouseCallback(func(event, x, y, flags int, param ...interface{}) {
		if img == nil {
			os.Exit(0)
		}

		if event == opencv.CV_EVENT_LBUTTONUP ||
			(flags&opencv.CV_EVENT_FLAG_LBUTTON) == 0 {
			prev_pt = opencv.Point{-1, -1}
		} else if event == opencv.CV_EVENT_LBUTTONDOWN {
			prev_pt = opencv.Point{x, y}
		} else if event == opencv.CV_EVENT_MOUSEMOVE &&
			(flags&opencv.CV_EVENT_FLAG_LBUTTON) != 0 {
			pt := opencv.Point{x, y}
			if prev_pt.X < 0 {
				prev_pt = pt
			}

			rgb := opencv.ScalarAll(255.0)
			opencv.Line(inpaint_mask, prev_pt, pt, rgb, 5, 8, 0)
			opencv.Line(img, prev_pt, pt, rgb, 5, 8, 0)
			prev_pt = pt

			win.ShowImage(img)
		}
	})
	win.ShowImage(img)
	opencv.WaitKey(0)

	win2 := opencv.NewWindow("inpainted image")
	defer win2.Destroy()
	win2.ShowImage(inpainted)

	for {
		key := opencv.WaitKey(20)
		if key == 27 {
			os.Exit(0)
		} else if key == 'r' {
			opencv.Zero(inpaint_mask)
			opencv.Copy(img0, img, nil)
			win.ShowImage(img)
		} else if key == 'i' || key == '\n' {
			opencv.Inpaint(img, inpaint_mask, inpainted, 3,
				opencv.CV_INPAINT_TELEA,
			)
			win2.ShowImage(inpainted)
		}
	}
	os.Exit(0)
}
Exemple #12
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
}
Exemple #13
0
func main() {
	filename := "../images/lena.jpg"
	if len(os.Args) == 2 {
		filename = os.Args[1]
	}

	image := opencv.LoadImage(filename)
	if image == nil {
		panic("LoadImage fail")
	}
	defer image.Release()

	w := image.Width()
	h := image.Height()

	// Create the output image
	cedge := opencv.CreateImage(w, h, opencv.IPL_DEPTH_8U, 3)
	defer cedge.Release()

	// Convert to grayscale
	gray := opencv.CreateImage(w, h, opencv.IPL_DEPTH_8U, 1)
	edge := opencv.CreateImage(w, h, opencv.IPL_DEPTH_8U, 1)
	defer gray.Release()
	defer edge.Release()

	opencv.CvtColor(image, gray, opencv.CV_BGR2GRAY)

	win := opencv.NewWindow("Edge")
	defer win.Destroy()

	win.SetMouseCallback(func(event, x, y, flags int, param ...interface{}) {
		fmt.Printf("event = %d, x = %d, y = %d, flags = %d\n",
			event, x, y, flags,
		)
	})

	win.CreateTrackbar("Thresh", 1, 100, func(pos int, param ...interface{}) {
		edge_thresh := pos

		opencv.Smooth(gray, edge, opencv.CV_BLUR, 3, 3, 0, 0)
		opencv.Not(gray, edge)

		// Run the edge detector on grayscale
		opencv.Canny(gray, edge, float64(edge_thresh), float64(edge_thresh*3), 3)

		opencv.Zero(cedge)
		// copy edge points
		opencv.Copy(image, cedge, edge)

		win.ShowImage(cedge)

		fmt.Printf("pos = %d\n", pos)
	})
	win.ShowImage(image)

	for {
		key := opencv.WaitKey(20)
		if key == 27 {
			os.Exit(0)
		}
	}

	os.Exit(0)
}