diff --git a/images/shapes.png b/images/shapes.png new file mode 100644 index 0000000..357bf4e Binary files /dev/null and b/images/shapes.png differ diff --git a/opencv/cxtype.go b/opencv/cxtype.go index 9fe7603..9037ef0 100644 --- a/opencv/cxtype.go +++ b/opencv/cxtype.go @@ -661,6 +661,24 @@ type Graph C.CvGraph type Chain C.CvChain type Contour C.CvContour +type ContourType struct { + mode C.int + method C.int + offset Point +} + +const ( + CV_RETR_EXTERNAL = C.CV_RETR_EXTERNAL + CV_RETR_LIST = C.CV_RETR_LIST + CV_RETR_CCOMP = C.CV_RETR_CCOMP + CV_RETR_TREE = C.CV_RETR_TREE + + CV_CHAIN_APPROX_NONE = C.CV_CHAIN_APPROX_NONE + CV_CHAIN_APPROX_SIMPLE = C.CV_CHAIN_APPROX_SIMPLE + CV_CHAIN_APPROX_TC89_L1 = C.CV_CHAIN_APPROX_TC89_L1 + CV_CHAIN_APPROX_TC89_KCOS = C.CV_CHAIN_APPROX_TC89_KCOS +) + /****************************************************************************************\ * Sequence types * \****************************************************************************************/ diff --git a/opencv/imgproc.go b/opencv/imgproc.go index 93b8070..83ae702 100644 --- a/opencv/imgproc.go +++ b/opencv/imgproc.go @@ -52,3 +52,32 @@ func Crop(src *IplImage, x, y, width, height int) *IplImage { return dest } + +func CreateContourType() *ContourType { + return &ContourType{CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point{0, 0}} +} + +func (this *ContourType) FindContours(image *IplImage) []*Contour { + storage := C.cvCreateMemStorage(0) + header_size := (C.size_t)(unsafe.Sizeof(C.CvContour{})) + var seq *C.CvSeq + C.cvFindContours( + unsafe.Pointer(image), + storage, + &seq, + C.int(header_size), + this.mode, + this.method, + C.cvPoint(C.int(this.offset.X), C.int(this.offset.Y))) + + var contours []*Contour + for i := 0; i < (int)(seq.total); i++ { + contour := (*Contour)((*_Ctype_CvContour)(unsafe.Pointer(C.cvGetSeqElem(seq, C.int(i))))) + contours = append(contours, contour) + } + + storage_c := (*C.CvMemStorage)(storage) + C.cvReleaseMemStorage(&storage_c) + + return contours +} diff --git a/opencv/imgproc_test.go b/opencv/imgproc_test.go index 85ed22e..759dc06 100644 --- a/opencv/imgproc_test.go +++ b/opencv/imgproc_test.go @@ -1,6 +1,7 @@ package opencv import ( + "log" "path" "runtime" "testing" @@ -55,3 +56,24 @@ func TestCrop(t *testing.T) { t.Fatalf("excepted width is 200, returned %d\n", crop.Height()) } } + +func TestFindContours(t *testing.T) { + _, currentfile, _, _ := runtime.Caller(0) + filename := path.Join(path.Dir(currentfile), "../images/shapes.png") + + image := LoadImage(filename) + if image == nil { + t.Fatal("LoadImage fail") + } + defer image.Release() + + grayscale_image := CreateImage(image.Width(), image.Height(), IPL_DEPTH_8U, 1) + CvtColor(image, grayscale_image, CV_BGR2GRAY) + defer grayscale_image.Release() + + cType := CreateContourType() + contours := cType.FindContours(grayscale_image) + for i, c := range contours { + log.Printf("Contour[%v] = %v", i, c) + } +}