Example #1
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)
}
Example #2
0
func detectedMotion(im *opencv.IplImage) {
	t := time.Now()
	d := t.Sub(lastNotified)
	if d < *notifyInterval {
		return
	}
	lastNotified = t

	log.Printf("Motion detected!")

	const tempFile = "/tmp/im.png"
	opencv.SaveImage(tempFile, im, 0)
	m := email.NewMessage("Motion detected", fmt.Sprintf("Motion detected at %v\n", t))
	m.From = *user + "@gmail.com"
	m.To = []string{*user + "@gmail.com"}
	err := m.Attach(tempFile)
	if err != nil {
		log.Printf("Couldn't attach image: %v\n", err)
	}
	err = email.Send("smtp.gmail.com:587",
		smtp.PlainAuth("", *user, *password, "smtp.gmail.com"),
		m)
	if err != nil {
		log.Printf("Couldn't send mail: %v\n", err)
		return
	}

	log.Printf("Sent email...\n")
}
Example #3
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
}
Example #4
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)
}
Example #5
0
func StreamVideo(ws *websocket.Conn, quit chan struct{}, capturechan chan *opencv.Capture) {
	revel.INFO.Printf("%s", "Access capture")
	capture := <-capturechan
	capturechan <- capture
	ticker := time.NewTicker(time.Millisecond * 10)
	for {
		select {
		case <-quit:
			revel.INFO.Printf("%s", "Goroutine closed")
			return
		case <-ticker.C:
			frame := capture.QueryFrame()

			//img := opencv.EncodeImage(".jpg", frame.ImageData(), 0)
			//
			//size := frame.ImageSize()
			//imgbuff := ((*[1 << 30]byte))(frame.ImageData())[:size]
			//fmt.Println(size)

			opencv.SaveImage("frame.jpg", frame, 0)
			img, _ := os.Open("frame.jpg")
			stats, _ := img.Stat()
			size := stats.Size()
			imgbuf := make([]byte, 0)
			chunkbuf := make([]byte, size)
			for {
				_, err := img.Read(chunkbuf)
				if err == io.EOF {
					img.Close()
					break
				}
				imgbuf = append(imgbuf, chunkbuf...)
			}

			result := "data:image/jpg;base64," + base64.StdEncoding.EncodeToString(imgbuf)
			err := websocket.Message.Send(ws, result)
			if err != nil {
				ticker.Stop()
				revel.INFO.Printf("%s %s", "ERROR:", err)
			}
		}
	}
}
Example #6
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)
			}
		}
	}
}
Example #7
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
}