Swiftpack.co - Package - hybridgroup/gocv

GoCV

GoCV

GoDoc Travis Build Status AppVeyor Build status codecov Go Report Card License

The GoCV package provides Go language bindings for the OpenCV 3 computer vision library.

The GoCV package supports the latest releases of Go and OpenCV (v3.4.2) on Linux, macOS, and Windows. We intend to make the Go language a "first-class" client compatible with the latest developments in the OpenCV ecosystem.

GoCV also supports Intel OpenVINO. Check out the OpenVINO README for more info on how to use GoCV with the Intel OpenVINO toolkit.

How to use

Hello, video

This example opens a video capture device using device "0", reads frames, and shows the video in a GUI window:

package main

import (
	"gocv.io/x/gocv"
)

func main() {
	webcam, _ := gocv.VideoCaptureDevice(0)
	window := gocv.NewWindow("Hello")
	img := gocv.NewMat()

	for {
		webcam.Read(&img)
		window.IMShow(img)
		window.WaitKey(1)
	}
}

Face detect

GoCV

This is a more complete example that opens a video capture device using device "0". It also uses the CascadeClassifier class to load an external data file containing the classifier data. The program grabs each frame from the video, then uses the classifier to detect faces. If any faces are found, it draws a green rectangle around each one, then displays the video in an output window:

package main

import (
	"fmt"
	"image/color"

	"gocv.io/x/gocv"
)

func main() {
	deviceID := 0

	// open webcam
	webcam, err := gocv.VideoCaptureDevice(int(deviceID))
	if err != nil {
		fmt.Println(err)
		return
	}	
	defer webcam.Close()

	// open display window
	window := gocv.NewWindow("Face Detect")
	defer window.Close()

	// prepare image matrix
	img := gocv.NewMat()
	defer img.Close()

	// color for the rect when faces detected
	blue := color.RGBA{0, 0, 255, 0}

	// load classifier to recognize faces
	classifier := gocv.NewCascadeClassifier()
	defer classifier.Close()

	if !classifier.Load("data/haarcascade_frontalface_default.xml") {
		fmt.Println("Error reading cascade file: data/haarcascade_frontalface_default.xml")
		return
	}

	fmt.Printf("start reading camera device: %v\n", deviceID)
	for {
		if ok := webcam.Read(&img); !ok {
			fmt.Printf("cannot read device %v\n", deviceID)
			return
		}
		if img.Empty() {
			continue
		}

		// detect faces
		rects := classifier.DetectMultiScale(img)
		fmt.Printf("found %d faces\n", len(rects))

		// draw a rectangle around each face on the original image
		for _, r := range rects {
			gocv.Rectangle(&img, r, blue, 3)
		}

		// show the image in the window, and wait 1 millisecond
		window.IMShow(img)
		window.WaitKey(1)
	}
}

More examples

There are examples in the cmd directory of this repo in the form of various useful command line utilities, such as capturing an image file, streaming mjpeg video, counting objects that cross a line, and using OpenCV with Tensorflow for object classification.

How to install

To install GoCV, run the following command:

go get -u -d gocv.io/x/gocv

To run code that uses the GoCV package, you must also install OpenCV 3.4.2 on your system. Here are instructions for Ubuntu, OS X, and Windows.

Ubuntu/Linux

Installation

You can use make to install OpenCV 3.4.2 with the handy Makefile included with this repo. If you already have installed OpenCV, you do not need to do so again. The installation performed by the Makefile is minimal, so it may remove OpenCV options such as Python or Java wrappers if you have already installed OpenCV some other way.

Quick Install

The following commands should do everything to download and install OpenCV 3.4.2 on Linux:

cd $GOPATH/src/gocv.io/x/gocv
make install

If it works correctly, at the end of the entire process, the following message should be displayed:

gocv version: 0.14.0
opencv lib version: 3.4.2

That's it, now you are ready to use GoCV.

Complete Install

Here are details for each of the steps that are performed during the "Quick Install". If you have already run make install as described above, you do not need to run any of these commands.

Install required packages

First, you need to change the current directory to the location of the GoCV repo, so you can access the Makefile:

cd $GOPATH/src/gocv.io/x/gocv

Next, you need to update the system, and install any required packages:

make deps

Download source

Now, download the OpenCV 3.4.2 and OpenCV Contrib source code:

make download

Build

Build everything. This will take quite a while:

make build

Install

Once the code is built, you are ready to install:

make sudo_install

Verifying the installation

To verify your installation you can run one of the included examples.

First, change the current directory to the location of the GoCV repo:

cd $GOPATH/src/gocv.io/x/gocv

Now you should be able to build or run any of the examples:

go run ./cmd/version/main.go

The version program should output the following:

gocv version: 0.14.0
opencv lib version: 3.4.2

Cleanup extra files

After the installation is complete, you can remove the extra files and folders:

make clean

Cache builds

If you are running a version of Go older than v1.10 and not modifying GoCV source, precompile the GoCV package to significantly decrease your build times:

go install gocv.io/x/gocv

Custom Environment

By default, pkg-config is used to determine the correct flags for compiling and linking OpenCV. This behavior can be disabled by supplying -tags customenv when building/running your application. When building with this tag you will need to supply the CGO environment variables yourself.

For example:

export CGO_CPPFLAGS="-I/usr/local/include"
export CGO_LDFLAGS="-L/usr/local/lib -lopencv_core -lopencv_face -lopencv_videoio -lopencv_imgproc -lopencv_highgui -lopencv_imgcodecs -lopencv_objdetect -lopencv_features2d -lopencv_video -lopencv_dnn -lopencv_xfeatures2d"

Please note that you will need to run these 2 lines of code one time in your current session in order to build or run the code, in order to setup the needed ENV variables. Once you have done so, you can execute code that uses GoCV with your custom environment like this:

go run -tags customenv ./cmd/version/main.go

Alpine 3.7 Docker image

There is a Docker image with Alpine 3.7 that has been created by project contributor @denismakogon. You can find it located at https://github.com/denismakogon/gocv-alpine.

macOS

Installation

You can install OpenCV 3.4.2 using Homebrew:

brew install opencv

If you already have an earlier version of OpenCV installed, you should probably upgrade it to the latest version, instead of installing:

brew upgrade opencv

Verifying the installation

To verify your installation you can run one of the included examples.

First, change the current directory to the location of the GoCV repo:

cd $GOPATH/src/gocv.io/x/gocv

Now you should be able to build or run any of the examples:

go run ./cmd/version/main.go

The version program should output the following:

gocv version: 0.14.0
opencv lib version: 3.4.2

Cache builds

If you are running a version of Go older than v1.10 and not modifying GoCV source, precompile the GoCV package to significantly decrease your build times:

go install gocv.io/x/gocv

Custom Environment

By default, pkg-config is used to determine the correct flags for compiling and linking OpenCV. This behavior can be disabled by supplying -tags customenv when building/running your application. When building with this tag you will need to supply the CGO environment variables yourself.

For example:

export CGO_CXXFLAGS="--std=c++11"
export CGO_CPPFLAGS="-I/usr/local/Cellar/opencv/3.4.2/include"
export CGO_LDFLAGS="-L/usr/local/Cellar/opencv/3.4.2/lib -lopencv_stitching -lopencv_superres -lopencv_videostab -lopencv_aruco -lopencv_bgsegm -lopencv_bioinspired -lopencv_ccalib -lopencv_dnn_objdetect -lopencv_dpm -lopencv_face -lopencv_photo -lopencv_fuzzy -lopencv_hfs -lopencv_img_hash -lopencv_line_descriptor -lopencv_optflow -lopencv_reg -lopencv_rgbd -lopencv_saliency -lopencv_stereo -lopencv_structured_light -lopencv_phase_unwrapping -lopencv_surface_matching -lopencv_tracking -lopencv_datasets -lopencv_dnn -lopencv_plot -lopencv_xfeatures2d -lopencv_shape -lopencv_video -lopencv_ml -lopencv_ximgproc -lopencv_calib3d -lopencv_features2d -lopencv_highgui -lopencv_videoio -lopencv_flann -lopencv_xobjdetect -lopencv_imgcodecs -lopencv_objdetect -lopencv_xphoto -lopencv_imgproc -lopencv_core"

Please note that you will need to run these 3 lines of code one time in your current session in order to build or run the code, in order to setup the needed ENV variables. Once you have done so, you can execute code that uses GoCV with your custom environment like this:

go run -tags customenv ./cmd/version/main.go

Windows

Installation

The following assumes that you are running a 64-bit version of Windows 10.

In order to build and install OpenCV 3.4.2 on Windows, you must first download and install MinGW-W64 and CMake, as follows.

MinGW-W64

Download and run the MinGW-W64 compiler installer from https://sourceforge.net/projects/mingw-w64/?source=typ_redirect.

The latest version of the MinGW-W64 toolchain is 7.3.0, but any version from 7.X on should work.

Choose the options for "posix" threads, and for "seh" exceptions handling, then install to the default location c:\Program Files\mingw-w64\x86_64-7.3.0-posix-seh-rt_v5-rev2.

Add the C:\Program Files\mingw-w64\x86_64-7.3.0-posix-seh-rt_v5-rev2\mingw64\bin path to your System Path.

CMake

Download and install CMake https://cmake.org/download/ to the default location. CMake installer will add CMake to your system path.

OpenCV 3.4.2 and OpenCV Contrib Modules

The following commands should do everything to download and install OpenCV 3.4.2 on Windows:

cd %USERPROFILE%\go\src\gocv.io\x\gocv
.\win_build_opencv.cmd

It will probably take at least 1 hour to download and build.

Last, add C:\opencv\build\install\x64\mingw\bin to your System Path.

Verifying the installation

Change the current directory to the location of the GoCV repo:

cd %USERPROFILE%\go\src\gocv.io\x\gocv

Now you should be able to build or run any of the command examples:

go run .\cmd\version\main.go

The version program should output the following:

gocv version: 0.14.0
opencv lib version: 3.4.2

That's it, now you are ready to use GoCV.

Cache builds

If you are running a version of Go older than v1.10 and not modifying GoCV source, precompile the GoCV package to significantly decrease your build times:

go install gocv.io/x/gocv

Custom Environment

By default, OpenCV is expected to be in C:\opencv\build\install\include. This behavior can be disabled by supplying -tags customenv when building/running your application. When building with this tag you will need to supply the CGO environment variables yourself.

Due to the way OpenCV produces DLLs, including the version in the name, using this method is required if you're using a different version of OpenCV.

For example:

set CGO_CXXFLAGS="--std=c++11"
set CGO_CPPFLAGS=-IC:\opencv\build\install\include
set CGO_LDFLAGS=-LC:\opencv\build\install\x64\mingw\lib -lopencv_core342 -lopencv_face342 -lopencv_videoio342 -lopencv_imgproc342 -lopencv_highgui342 -lopencv_imgcodecs342 -lopencv_objdetect342 -lopencv_features2d342 -lopencv_video342 -lopencv_dnn342 -lopencv_xfeatures2d342 -lopencv_plot342 -lopencv_tracking342 -lopencv_img_hash342

Please note that you will need to run these 3 lines of code one time in your current session in order to build or run the code, in order to setup the needed ENV variables. Once you have done so, you can execute code that uses GoCV with your custom environment like this:

go run -tags customenv .\cmd\version\main.go

Android

There is some work in progress for running GoCV on Android using Gomobile. For information on how to install OpenCV/GoCV for Android, please see: https://gist.github.com/ogero/c19458cf64bd3e91faae85c3ac887481

See original discussion here: https://github.com/hybridgroup/gocv/issues/235

How to contribute

Please take a look at our CONTRIBUTING.md document to understand our contribution guidelines.

Then check out our ROADMAP.md document to know what to work on next.

Why this project exists

The https://github.com/go-opencv/go-opencv package for Go and OpenCV does not support any version above OpenCV 2.x, and work on adding support for OpenCV 3 has stalled for over a year, mostly due to the complexity of SWIG.

The GoCV package uses a C-style wrapper around the OpenCV 3 C++ classes to avoid having to deal with applying SWIG to a huge existing codebase. The mappings are intended to match as closely as possible to the original OpenCV project structure, to make it easier to find things, and to be able to figure out where to add support to GoCV for additional OpenCV image filters, algorithms, and other features.

For example, the OpenCV videoio module wrappers can be found in the GoCV package in the videoio.* files.

This package was inspired by the original https://github.com/go-opencv/go-opencv project, the blog post https://medium.com/@peterleyssens/using-opencv-3-from-golang-5510c312a3c and the repo at https://github.com/sensorbee/opencv thank you all!

License

Licensed under the Apache 2.0 license. Copyright (c) 2017-2018 The Hybrid Group.

Logo generated by GopherizeMe - https://gopherize.me

Github

link
Stars: 1179
Help us keep the lights on

Dependencies

Used By

Total: 0

Releases

0.14.0 - Jul 5, 2018

  • build
    • Add -lopencv_calib3d341 to the linker
    • auto-confirm on package installs from make deps command
    • display PowerShell download status for OpenCV files
    • obtain caffe test config file from new location in Travis build
    • remove VS only dependencies from OpenCV build, copy caffe test config file from new location
    • return back to GoCV directory after OpenCV install
    • update for release of OpenCV v3.4.2
    • use PowerShell for scripted OpenCV install for Windows
    • win32 version number has not changed yet
  • calib3d
    • Add Calibrate for Fisheye model(WIP)
  • core
    • add GetTickCount function
    • add GetTickFrequency function
    • add Size() and FromPtr() methods to Mat
    • add Total method to Mat
    • Added RotateFlag type
    • correct CopyTo to use pointer to Mat as destination
    • functions converting Image to Mat
    • rename implementation to avoid conflicts with Windows
    • stricter use of reflect.SliceHeader
  • dnn
    • add backend/device options to caffe and tensorflow DNN examples
    • add Close to Layer
    • add first version of dnn-pose-detection example
    • add further comments to object detection/tracking DNN example
    • add GetPerfProfile function to Net
    • add initial Layer implementation alongside enhancements to Net
    • add InputNameToIndex to Layer
    • add new functions allowing DNN backends such as OpenVINO
    • additional refactoring and comments in dnn-pose-detection example
    • cleanup DNN face detection example
    • correct const for device targets to be called Target
    • correct test that expected init slice with blank entries
    • do not init slice with blank entries, since added via append
    • further cleanup of DNN face detection example
    • make dnn-pose-detection example use Go channels for async operation
    • refactoring and additional comments for object detection/tracking DNN example
    • refine comment in header for style transfer example
    • working style transfer example
    • added ForwardLayers() to accomodate models with multiple output layers
  • docs
    • add scripted Windows install info to README
    • Added a sample gocv workflow contributing guideline
    • mention docker image in README.
    • mention work in progress on Android
    • simplify and add missing step in Linux installation in README
    • update contributing instructions to match latest version
    • update ROADMAP from recent calib3d module contribution
    • update ROADMAP from recent imgproc histogram contribution
  • examples
    • cleanup header for caffe dnn classifier
    • show how to use either Caffe or Tensorflow for DNN object detection
    • further improve dnn samples
    • rearrange and add comments to dnn style transfer example
    • remove old copy of pose detector
    • remove unused example
  • features2d
    • free memory allocation bug for C.KeyPoints as pointed out by @tzununbekov
    • Adding opencv::drawKeypoints() support
  • imgproc
    • add equalizeHist function
    • Added opencv::calcHist implementation
  • openvino
    • add needed environment config to execute examples
    • further details in README explaining how to use
    • remove opencv contrib references as they are not included in OpenVINO
  • videoio
    • Add OpenVideoCapture
    • Use gocv.VideoCaptureFile if string is specified for device.

0.13.0 - May 29, 2018

  • build
    • Add cgo directives to contrib
    • contrib subpackage also needs cpp 11 or greater for a warning free build on Linux
    • Deprecate env scripts and update README
    • Don't set --std=c++1z on non-macOS
    • Remove CGO vars from CI and correct Windows cgo directives
    • Support pkg-config via cgo directives
    • we actually do need cpp 11 or greater for a warning free build on Linux
  • docs
    • add a Github issue template to project
    • provide specific examples of using custom environment
  • imgproc
    • add HoughLinesPWithParams() function
  • openvino
    • add build tag specific to openvino
    • add roadmap info
    • add smoke test for ie

0.12.0 - May 24, 2018

  • build
    • convert to CRLF
    • Enable verbosity for travisCI
    • Further improvements to Makefile
  • core
    • Add Rotate, VConcat
    • Adding InScalarRange and NewMatFromScalarWithSize functions
    • Changed NewMatFromScalarWithSize to NewMatWithSizeFromScalar
    • implement CheckRange(), Determinant(), EigenNonSymmetric(), Min(), and MinMaxIdx() functions
    • implement PerspectiveTransform() and Sqrt() functions
    • implement Transform() and Transpose() functions
    • Make toByteArray safe for empty byte slices
    • Renamed InScalarRange to InRangeWithScalar
  • docs
    • nicer error if we can't read haarcascade_frontalface_default
    • correct some ROADMAP links
    • Fix example command.
    • Fix executable name in help text.
    • update ROADMAP from recent contributions
  • imgproc
    • add BoxFilter and SqBoxFilter functions
    • Fix the hack to convert C arrays to Go slices.
  • videoio
    • Add isColor to VideoWriterFile
    • Check numerical parameters for gocv.VideoWriterFile
    • CodecString()
  • features2d
    • add BFMatcher
  • img_hash
    • Add contrib/img_hash module
    • add GoDocs for new img_hash module
    • Add img-similarity as an example for img_hash
  • openvino
    • adds support for Intel OpenVINO toolkit PVL
    • starting experimental work on OpenVINO IE
    • update README files for Intel OpenVINO toolkit support
    • WIP on IE can load an IR network

0.11.0 - Mar 26, 2018

  • build
    • Add astyle config
    • Astyle cpp/h files
    • remove duplication in Makefile for astyle
  • core
    • Add GetVecfAt() function to Mat
    • Add GetVeciAt() function to Mat
    • Add Mat.ToImage()
    • add MeanStdDev() method to Mat
    • add more functions
    • Compare Mat Type directly
    • further cleanup for GoDocs and enforce type for convariance operations
    • Make borderType in CopyMakeBorder be type BorderType
    • Mat Type() should return MatType
    • remove unused convenience functions
    • use Mat* to indicate when a Mat is mutable aka an output parameter
  • dnn
    • add a ssd sample and a GetBlobChannel helper
    • added another helper func and a pose detection demo
  • docs
    • add some additional detail about adding OpenCV functions to GoCV
    • updates to contribution guidelines
    • fill out complete list of needed imgproc functions for sections that have work started
    • indicate that missing imgproc functions need implementation
    • mention the WithParams patterns to be used for functions with default params
    • update README for the Mat* based API changes
    • update ROADMAP for recent changes especially awesome recent core contributions from @berak
  • examples
    • Fix tf-classifier example
    • move new DNN advanced examples into separate folders
    • Update doc for the face contrib package
    • Update links in caffe-classifier demo
    • WIP on hand gestures tracking example
  • highgui
    • fix constant in NewWindow
  • imgproc
    • Add Ellipse() and FillPoly() functions
    • Add HoughCirclesWithParams() func
    • correct output Mat to for ConvexHull()
    • rename param being used for Mat image to be modified
  • tracking
    • add support for TrackerMIL, TrackerBoosting, TrackerMedianFlow, TrackerTLD, TrackerKCF, TrackerMOSSE, TrackerCSRT trackers
    • removed mutitracker, added Csrt, rebased
    • update GoDocs and minor renaming based on gometalint output

0.10.0 - Mar 5, 2018

  • build
    • install unzip before build
    • overwrite when unzipping file to install Tensorflow test model
    • use -DCPU_DISPATCH= flag for build to avoid problem with disabled AVX on Windows
    • update unzipped file when installing Tensorflow test model
  • core
    • add Compare() and CountNonZero() functions
    • add getter/setter using optional params for multi-dimensional Mat using row/col/channel
    • Add mat subtract function
    • add new toRectangle function to DRY up conversion from CRects to []image.Rectangle
    • add split subtract sum wrappers
    • Add toCPoints() helper function
    • Added Mat.CopyToWithMask() per #47
    • added Pow() method
    • BatchDistance BorderInterpolate CalcCovarMatrix CartToPolar
    • CompleteSymm ConvertScaleAbs CopyMakeBorder Dct
    • divide, multiply
    • Eigen Exp ExtractChannels
    • operations on a 3d Mat are not same as a 2d multichannel Mat
    • resolve merge conflict with duplicate Subtract() function
    • run gofmt on core tests
    • Updated type for Mat.GetUCharAt() and Mat.SetUCharAt() to reflect uint8 instead of int8
  • docs
    • update ROADMAP of completed functions in core from recent contributions
  • env
    • check loading resources
    • Add distribution detection to deps rule
    • Add needed environment variables for Linux
  • highgui
    • add some missing test coverage on WaitKey()
  • imgproc
    • Add adaptive threshold function
    • Add pyrDown and pyrUp functions
    • Expose DrawContours()
    • Expose WarpPerspective and GetPerspectiveTransform
    • implement ConvexHull() and ConvexityDefects() functions
  • opencv
    • update to OpenCV version 3.4.1