Applying morphological transformations to images