【问题标题】:Python Image/Pillow: How to make the background more white of imagesPython Image/Pillow:如何使图像的背景更白
【发布时间】:2019-12-03 22:35:19
【问题描述】:

我有这样的图片:

我想做的是使图像的背景更白,以便字母更明显。从我的角度来看,这是一个很好的图像:

我在 Python 中使用 Pillow。先感谢您!

【问题讨论】:

    标签: python-3.x python-imaging-library


    【解决方案1】:

    最简单的大概是这样使用ImageOps.autocontrast()来增加对比度:

    from PIL import Image, ImageOps
    
    # Open image as greyscale
    im = Image.open('letter.png').convert('L')
    
    # Autocontrast
    result = ImageOps.autocontrast(im) 
    
    # Save
    result.save('result.png')
    


    更复杂的方法是使用 Otsu 阈值将像素最佳地拆分为 2 种颜色,但为此您需要像这样的 scikit-image

    from skimage import filters
    from skimage.io import imread, imsave
    
    # Load image as greyscale
    img = imread('letter.png', as_gray=True)
    
    # Get Otsu threshold - result is 151
    threshold = filters.threshold_otsu(img) 
    

    您现在可以继续,将阈值以上的所有像素设为白色,并将低于阈值的像素保持原样:

    img[img>threshold] = 255
    imsave('result.png',img)
    

    或者,您可以设置一个完整的阈值,使所有像素最终变为纯黑色或纯白色:

    result = (img>threshold).astype(np.uint8) * 255 
    imsave('result.png',result)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-02
      • 1970-01-01
      • 1970-01-01
      • 2021-06-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多