【问题标题】:How to change the grey scale value of a region in an image?如何改变图像中某个区域的灰度值?
【发布时间】:2019-01-09 21:31:51
【问题描述】:

我是 Python 新手,不太清楚如何解决这个问题。

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

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

请检查图片。

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

【问题讨论】:

    标签: python image-processing


    【解决方案1】:

    我想这就是你想要的。 cmets 应该很好地解释了我在做什么:

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

    所以,如果我从这张图片开始:

    (中间)边缘如下所示:

    结果如下:


    如果您希望轮廓更粗/更细,请增加/减少6 in:

    selem = square(6)
    

    如果您希望轮廓更亮/更暗,请增加/减少128 in:

    imnp[np.nonzero(fatedges)] = 128
    

    关键字:图像、图像处理、增肥、加厚、轮廓、跟踪、边缘、突出显示、Numpy、PIL、枕头、边缘、边缘、形态学、结构元素、skimage、scikit-image、侵蚀,侵蚀,扩张,扩张。

    【讨论】:

    • 谢谢马克。我意识到我没有正确地问我的问题。图像并不总是正方形。有时它也会是 L 形图像。我编辑了原始帖子以显示它。
    • 其实我觉得你又把我坑了!您在 Google 驱动器中提供的示例图像已经在形状周围有一个灰色边框 - 与您在问题中显示的没有边框的图像不同。编写代码时假设白色形状周围没有初始灰色边框。
    • 哈哈对不起。我确实上传了错误的图像。非常感谢马克,这正是我所需要的。我只需要对其进行一些更改并添加批处理代码。非常感谢您的帮助。
    • 酷 - 很高兴我们最终到达了那里。祝你的项目好运!
    【解决方案2】:

    我可以用更简单的方式解释你的问题,所以我想我也会回答这个更简单的问题。也许您的形状周围已经有灰色边缘(例如您共享的 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')
    

    【讨论】:

      猜你喜欢
      • 2021-01-05
      • 2019-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-09
      • 2015-06-08
      相关资源
      最近更新 更多