如何更改图像中某个区域的灰度值?

时间:2019-01-09 21:31:52

标签: python image-processing

我是Python的新手,不确定如何解决此问题。

我想做的是拍摄黑白图像,并将边缘(x像素厚)的值从255更改为其他灰度值。

我需要对文件夹内的一组png图像执行此操作。所有图像将是几何形状(主要是直线的组合),没有疯狂的曲线或图案。使用Python 3。

请检查图像。

Original 1

Desired 1

Original 2

Desired 2

典型文件如下所示: https://drive.google.com/open?id=13ls1pikNsO7ZbsHatC6cOr4O6Fj0MPOZ

2 个答案:

答案 0 :(得分:0)

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.

答案 1 :(得分:0)

我可以用一种更简单的方式解释您的问题,所以我想我也会回答这个简单的问题。也许您的形状周围已经有灰色的边缘(例如您共享的Google驱动器文件),并且只想将所有既不是黑色也不是白色的像素更改为不同的颜色-并且它们是边缘的事实无关紧要。这样容易得多:

#!/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')