How to change the grey scale value of a region in an image?

Viewed 550

I am new to Python and not really sure how to attack this problem.

What I am trying to do is to take a black and white image and change the value of the edge (x pixels thick) from 255 to some other greyscale value.

I need to do this to a set of png images inside of a folder. All images will be geometric (mostly a combination of straight lines) no crazy curves or patterns. Using Python 3.

Please check the images.

Original 1

Desired 1

Original 2

Desired 2

A typical file will look like this: https://drive.google.com/open?id=13ls1pikNsO7ZbsHatC6cOr4O6Fj0MPOZ

2 Answers

I think this is what you want. The comments should explain pretty well what I going on:

#!/usr/bin/env python3

import numpy as np
from PIL import Image, ImageFilter
from skimage.morphology import dilation, square

# Open input image and ensure it is greyscale
image = Image.open('XYbase.png').convert('L')

# Find the edges
edges = image.filter(ImageFilter.FIND_EDGES)

# Convert edges to Numpy array and dilate (fatten) with our square structuring element
selem = square(6)
fatedges = dilation(np.array(edges),selem)

# Make Numpy version of our original image and set all fatedges to brightness 128
imnp = np.array(image)
imnp[np.nonzero(fatedges)] = 128

# Convert Numpy image back to PIL image and save
Image.fromarray(imnp).save('result.png')

So, if I start with this image:

enter image description here

The (intermediate) edges look like this:

enter image description here

And I get this as the result:

enter image description here


If you want the outlines fatter/thinner, increase/decrease the 6 in:

selem = square(6)

If you want the outlines lighter/darker, increase/decrease the 128 in:

imnp[np.nonzero(fatedges)] = 128

Keywords: image, image processing, fatten, thicken, outline, trace, edge, highlight, Numpy, PIL, Pillow, edge, edges, morphology, structuring element, skimage, scikit-image, erode, erosion, dilate, dilation.

I can interpret your question in a much simpler way, so I thought I'd answer that simpler question too. Maybe you already have a grey-ish edge around your shapes (like the Google drive files you shared) and just want to change all pixels that are neither black nor white into a different colour - and the fact that they are edges is irrelevant. That is much easier:

#!/usr/bin/env python3

import numpy as np
from PIL import Image

# Open input image and ensure it is greyscale
image = Image.open('XYBase.png').convert('L')

# Make Numpy version
imnp = np.array(image)

# Set all pixels that are neither black nor white to 220
imnp[(imnp>0) & (imnp<255)] = 220

# Convert Numpy image back to PIL image and save
Image.fromarray(imnp).save('result.png')
Related