Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I separate contours of touching objects using erode?

I'm getting this problem:

http://img38.imageshack.us/img38/5856/questao.png

I'm using Python and OpenCV. I'm trying to separate the contours of the touching coins using erode. I thresholded the image and then tried to apply the erode but nothing happened. I've read the documentation and still don't understand very well how the getStruturingElement and erode works.

  1. I've thresholded the image.

  2. used erode on the thresholded image.

and still nothing. What am I using wrong here?

Here's part of the code:

import cv2, numpy as np

#1.Reads Image
objectImage = cv2.imread('P1000713s.jpg')

#2.Converts to Gray level
cvtcolorImage = cv2.cvtColor(objectImage,cv2.COLOR_RGB2GRAY)

#3.Thresholds
imgSplit = cv2.split(objectImage)
flag,b = cv2.threshold(imgSplit[2],0,255,cv2.THRESH_OTSU) 

#4.Erodes the Thresholded Image
element = cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3))
cv2.erode(b,element)

cv2.imshow('Eroded',b)
like image 688
Cap.Alvez Avatar asked Nov 17 '12 17:11

Cap.Alvez


People also ask

How do you find contours?

findContours() function, first one is source image, second is contour retrieval mode, third is contour approximation method. And it outputs a modified image, the contours and hierarchy. contours is a Python list of all the contours in the image.


2 Answers

I know this is an old question, but I had similar problems, and found this problem via Google.

As far as I know cv2.erode() doesn't change the source image, instead it returns a new image with the change applied.

changing your line containing the erode call to:

b = cv2.erode(b,element)

should let you see the changes when you call the cv2.imshow(...,b)

like image 189
Christian Sonne Avatar answered Oct 02 '22 04:10

Christian Sonne


Looking at your image, it's possible that a 3x3 cross mask will always stay within the thresholded area. Rather than using MORPH_CROSS, use MORPH_ELLIPSE.

If the coins are still "touching" after one call, you could always run multiple calls to erode, but be warned that this will have a destructive effect on your image.

like image 40
Chris Avatar answered Oct 02 '22 03:10

Chris