Cannot find contours using OpenCV3 but code works on on OpenCV2

Question:

Here is the code that does NOT work:

original_image = cv2.imread(test_image,cv2.IMREAD_GRAYSCALE);
bin_ada = cv2.adaptiveThreshold(original_image,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,43,0);
img,contours, hierachy = cv2.findContours(bin_ada,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE,(0,0));

Here is the code that does work:

original_image = cv2.imread(test_image,cv2.IMREAD_GRAYSCALE);
bin_ada = cv2.adaptiveThreshold(original_image,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,43,0);
contours, hierachy = cv2.findContours(bin_ada,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE,(0,0));

The difference is that the first code is running with Python3 and Newer OpenCV libraries (3.4.1) while the second code is running with Python2 and Older OpenCV libraries (2.4.5).

Is this a bug? Or is there a simple explanation as to why the first piece of code does not work?

The error is this:

OpenCV(3.4.1) /io/opencv/modules/imgproc/src/contours.cpp:1894: error: (-215) _contours.empty() || (_contours.channels() == 2 && _contours.depth() == 4) in function findContours

I’d appreciate any help

Asked By: aarelovich

||

Answers:

You don’t need the last argument of findContours, it is an offset and you are setting to (0,0) (if you do need an offset use offset=(y,x)).

This code worked in python 3.6.3 and opencv 3.4

import cv2
import numpy as np

original_image = cv2.imread("./1.jpeg",cv2.IMREAD_GRAYSCALE);
bin_ada = cv2.adaptiveThreshold(original_image,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,43,0);
img,contours, hierachy = cv2.findContours(bin_ada,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE);
Answered By: Fred Guth
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.