Retrieving the outline or silhouette of an image in Python

I want to extract the silhouette of an image, and I'm trying to do this using the outline function of MatplotLib. This is my code:

from PIL import Image from pylab import * # read image to array im = array(Image.open('HOJA.jpg').convert('L')) # create a new figure figure() # show contours with origin upper left corner contour(im, origin='image') axis('equal') show() 

This is my original image:

Original

And this is my result:

Contour

But I just want to show the outer contour, the silhouette. Only read lines in this example.

How can i do this? I read the contour documentation, but I cannot get what I want.

If you know the best way to do this in Python, please tell me! (MatplotLib, OpenCV, etc.)

+6
source share
3 answers

If you want to stick to your outline approach, you can simply add a level argument with a threshold value for the image between the white background and the sheet.

You can use the histogram to find the corresponding value. But in this case, any value is slightly lower than 255.

So:

 contour(im, levels=[245], colors='black', origin='image') 

enter image description here

Make sure you order Scikit-Image if you want to do serious image processing. It contains several detection algorithms, etc.

http://scikit-image.org/docs/dev/auto_examples/

+12
source

For those who want an OpenCV solution, here it is:

 ret,thresh = cv2.threshold(image,245,255,0) contours, hierarchy = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE) tam = 0 for contorno in contours: if len(contorno) > tam: contornoGrande = contorno tam = len(contorno) cv2.drawContours(image,contornoGrande.astype('int'),-1,(0,255,0),2) cv2.imshow('My image',image) cv2.waitKey() cv2.destroyAllWindows() 

In this example, I draw the largest outline. Remember that the "image" must be a single-channel array.

You have to change the parameters of the threshold function, the findContours function and the drawContours function to get what you want.

I am doing a conversion to 'int' in the drawContours function because there is an error in Open CV 2.4.3, and if you do not perform this conversion, the program is interrupted. This is a mistake .

+4
source

I would recommend using OpenCV for better performance. It has findContour functions available from python using cv2 binding. This function can be set to return only the external circuit.

You will also have to generate an image.

0
source

All Articles