I'm currently using opencv to detect simple countours on shapes. At first, I used c++ and everything worked well. Now, I'm trying to do the same with Python as I need to use it online, and the contours detection doesn't seem to be working as well.
Here is my c++ code :
_src = cv::imread(_imagePath);
cv::Mat gray;
cv::cvtColor(_src, gray, CV_BGR2GRAY);
cv::Mat bw;
cv::Canny(gray, bw, 0, 50, 5);
cv::findContours(bw.clone(), allCountours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE);
As you can see, it's quite simple, the same code is Python is :
self._src = cv2.imread(self._imagePath)
gray = cv2.cvtColor(self._src, cv2.COLOR_BGR2GRAY)
bw = cv2.Canny(gray, 0, 50, 5)
allCountours, hierarchy = cv2.findContours(bw.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
To show the results, i used drawcontours with random colors on the different contours :
As you can see, in c++ each shape contour is detected properly, evn though it's not perfect, whereas in Python I have much more contours. Every time a line breaks a little, a new contour is detected. Any idea how I could fix this ? Thanks you !
Contours is a Python list of all the contours in the image. Each individual contour is a Numpy array of (x,y) coordinates of boundary points of the object. Note. We will discuss second and third arguments and about hierarchy in details later.
Find the ContoursUse the findContours() function to detect the contours in the image.
What are contours? Contours can be explained simply as a curve joining all the continuous points (along the boundary), having same color or intensity. The contours are a useful tool for shape analysis and object detection and recognition. For better accuracy, use binary images.
The C++ function signature is as follows:
void Canny(InputArray image, OutputArray edges, double threshold1, double threshold2, int apertureSize=3, bool L2gradient=false )
And for Python it is:
cv.Canny(image, edges, threshold1, threshold2, aperture_size=3) → None
As you can see, the last parameter is unavailable in Python. It might be the case that it is set to true
. Could you try that?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With