Skip main navigation

Practical: Erosion and Dilation in Python

A practical exercise showing an implementation of the pixel dilation in Python, and how to convert it to an erosion step.
An image of a brown leaf on a white background at various stages of thresholding and pixel dilation. Shown left to right are the original colour image, grayscale version, thresholded version, and dilated version.

We saw how to perform dilation on thesholded images in the previous videos. This practical gives you a chance to try this for yourself, as well as adapting the code so it performs the erosion algorithm instead.

All the instructions you need are in the attached pdf Erosion practical.

The image data used in the practical is displayed below (right-click, save image as to use).

The image of a brown leaf on a white background used in the practical

The code for dilation is below (copy / paste to use):

from ij.gui import NewImage
from ij import IJ

# get the current image selected in Fiji
imp = IJ.getImage()
processor = imp.getProcessor()

# get width and height of image
w = processor.getWidth()
h = processor.getHeight()

# make new image (initially filled with black pixels)
output = NewImage.createImage("Dilated",w, h, 1, 8, NewImage.FILL_BLACK)
output_processor = output.getProcessor()

# search all neighbouring pixels of each pixel in turn
for x in range(1, w-1):
for y in range(1, h-1):
foundWhite = False
for a in range(x-1, x+2):
for b in range(y-1, y+2):
if(processor.getPixel(a,b)==255):
foundWhite = True

if foundWhite:
output_processor.setColor(255)
output_processor.drawPixel(x,y)

# show the result
output.show()

Alternatively the code can also be found at our Github repository https://github.com/nlmellor/PhenoDataCampp/tree/main/ImageAnalysis/code.

Please let us know how you get on in the comments below.

This article is from the free online

Introduction to Image Analysis for Plant Phenotyping

Created by
FutureLearn - Learning For Life

Our purpose is to transform access to education.

We offer a diverse selection of courses from leading universities and cultural institutions from around the world. These are delivered one step at a time, and are accessible on mobile, tablet and desktop, so you can fit learning around your life.

We believe learning should be an enjoyable, social experience, so our courses offer the opportunity to discuss what you’re learning with others as you go, helping you make fresh discoveries and form new ideas.
You can unlock new opportunities with unlimited access to hundreds of online short courses for a year by subscribing to our Unlimited package. Build your knowledge with top universities and organisations.

Learn more about how FutureLearn is transforming access to education