I have hundreds of PNG images for which I have to generate corresponding B&W images that show the outer outline of the object. The source PNG image has alpha channel, so the "no object" parts of the image are 100% transparent.
The tricky part is that if the object has holes in it, those should not be seen in the outline. So, if the source image is, say, donut, the respective contour image would be a jagged circular line with no concentric smaller line in the middle.
Here is an example image, source and its contour:
Is there any library or command-line tool that can do this? Ideally, something that could be used from Python.
Contours in image processing. Contours are designed using edges. They are edges with an identity, geometrical parameters and are continuous. They are useful for shape analysis and object recognition.
findContours() function. First one is source image, second is contour retrieval mode, third is contour approximation method and it outputs the image, contours, and hierarchy. 'contours' is a Python list of all the contours in the image.
The mode cv2. RETR_TREE finds all the promising contour lines and reconstructs a full hierarchy of nested contours. The method cv2. CHAIN_APPROX_SIMPLE returns only the endpoints that are necessary for drawing the contour line.
You specify the image you want to show the contours in, the contours structure that was created from earlier, and the -1 flag says to draw all of the contours in the image. If it all works out, you should only have one contour detected.
We use a marching squares method to find constant valued contours in an image. In skimage.measure.find_contours, array values are linearly interpolated to provide better precision of the output contours. Contours which intersect the image edge are open; all others are closed.
The above method is RETR_TREE where all contours as well as their occurrence Hierarchy is maintained . We will look about it in more details below Retrieves only the extreme outer contours.
Talking about contouring it is a very useful operation when our use case involves geological terrain images or studying weather maps, etc. Let’s do it… Step 1 – Importing required packages.
I agree with amgaera. OpenCV in Python is one of the best tools you can use if you want to find contours. As with his/her post, use the findContours
method and use the RETR_EXTERNAL
flag to get the outer most contour of the shape. Here's some reproducible code for you to illustrate this point. You first need to install OpenCV and NumPy
to get this going.
I'm not sure what platform you're using, but:
apt-get
on libopencv-dev
and python-numpy
(i.e. sudo apt-get install libopencv-dev python-numpy
). brew install opencv
then brew install numpy
. http://www.lfd.uci.edu/~gohlke/pythonlibs/
- Check the OpenCV package and install all of the dependencies it is asking for, including NumPy
which you can find on this page.In any case, I took your donut image, and I extracted just the image with the donut. In other words, I created this image:
As for your images being PNG and having an alpha channel, that actually doesn't matter. So long as you have only a single object contained in this image, we actually don't need tho access the alpha channel at all. Once you download this image, save it as donut.png
, then go ahead and run this code:
import cv2 # Import OpenCV
import numpy as np # Import NumPy
# Read in the image as grayscale - Note the 0 flag
im = cv2.imread('donut.png', 0)
# Run findContours - Note the RETR_EXTERNAL flag
# Also, we want to find the best contour possible with CHAIN_APPROX_NONE
contours, hierarchy = cv2.findContours(im.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
# Create an output of all zeroes that has the same shape as the input
# image
out = np.zeros_like(im)
# On this output, draw all of the contours that we have detected
# in white, and set the thickness to be 3 pixels
cv2.drawContours(out, contours, -1, 255, 3)
# Spawn new windows that shows us the donut
# (in grayscale) and the detected contour
cv2.imshow('Donut', im)
cv2.imshow('Output Contour', out)
# Wait indefinitely until you push a key. Once you do, close the windows
cv2.waitKey(0)
cv2.destroyAllWindows()
Let's go through the code slowly. First we import the OpenCV and NumPy packages. I imported NumPy as np
, and if you look at numpy
docs and tutorials everywhere, they do this to minimize typing. OpenCV and NumPy work with each other, which is why you need to install both packages. We then read in the image using imread
. I set the flag to be 0
to make the image grayscale to make things simple. Once I load in the image, I then run findContours
, and the output of this function outputs a tuple of two things:
contours
- This is an array structure that gives you the (x,y)
co-ordinates of each contour detected in your image.hierarchy
- This contains additional information about the contours you've detected, like the topology, but let's skip this for the sake of this post.Take note that I specified RETR_EXTERNAL
to detect the outer most contour of the object. I also specify the CHAIN_APPROX_NONE
flag to ensure we get the full contour without any approximations. Once we detect the contours, we create a new output image that is entirely black. This will contain our detected outer contour of the donut. Once we create this image, we run the drawContours
method. You specify the image you want to show the contours in, the contours structure that was created from earlier, and the -1
flag says to draw all of the contours in the image. If it all works out, you should only have one contour detected. You then specify what colour you want the contour to look like. In our case, we want this to be white. After, you specify how thick you want the contour to be drawn. I chose a thickness of 3 pixels.
Last thing we want to do is show what the results look like. I call imshow
to show what the original donut image looks like (grayscale) and what the output contour looks like. imshow
isn't the end of the story. You won't see any output until you invoke cv2.waitKey(0)
. What this is saying now is you can display the images indefinitely until you push a key. Once you press on a key, the cv2.destroyAllWindows()
call closes all of the windows that were spawned.
This is what I get (once you rearrange the windows so that they're side-by-side):
As an additional bonus, if you want to save the image, you just run imwrite
to save the image. You specify the name of the image you want to write, and the variable you are accessing. As such, you would do something like:
cv2.imwrite('contour.png', out)
You'll then save this contour image to file which is named contour.png
.
This should be enough to get you started.
Good luck!
OpenCV has a findContours function that does exactly what you want. You will need to set contour retrieval mode to CV_RETR_EXTERNAL
. To load your images use the imread function.
I would recommend ImageMagick which is available for free from here. It is included in many Linux distibutions anyway. It has Python, Perl ,PHP, C/C++ bindings available as well.
I am just using it from the command-line below.
convert donut.png -channel A -morphology EdgeOut Diamond +channel -fx 'a' -negate output.jpg
Basically, the -channel A
selects the alpha (transparency) and applies the morphology to extract the outline of the opaque area. Then the +channel
tells ImageMagick I am now addressing all channels again. The -fx
is a custom function (operator) in which I set each pixel of the output image to a
- the alpha value in the modified alpha channel.
Edited
The following may be quicker than using the above fx
operator:
convert donut.png -channel RGBA -separate -delete 0-2 -morphology EdgeOut Diamond -negate output.png
Result:
If you have many hundreds (or thousands) of images to outline, I would recommend GNU Parallel, available from here. Then it will use all your CPU cores to get the job done quickly. Your command will look something like this - BUT PLEASE BACKUP FIRST and work on a copy till you get the hang of it!
parallel convert {} -channel A -morphology EdgeOut Diamond +channel -fx 'a' -negate {.}.jpg ::: *.png
That says to use everything after :::
as the files to process. Then in parallel, using all available cores, convert each PNG file and change its name to the corresponding JPEG file as the output filename.
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