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

Reach your personal and professional goals

Unlock access to hundreds of expert online courses and degrees from top universities and educators to gain accredited qualifications and professional CV-building certificates.

Join over 18 million learners to launch, switch or build upon your career, all at your own pace, across a wide range of topic areas.

Start Learning now