使用Python PIL将RGB图像转换为纯黑白图像

2024-09-21 00:19:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python图像库进行一些非常简单的图像处理,但是我在将灰度图像转换为单色(黑白)图像时遇到了问题。如果在将图像更改为灰度(convert('L'))后保存,则图像将按您的预期进行渲染。但是,如果我将图像转换为单色,单波段图像,它只会给我噪声,正如您在下面的图像中看到的。有没有一种简单的方法可以使用PIL/python将彩色png图像转换为纯黑白图像?

from PIL import Image 
import ImageEnhance
import ImageFilter
from scipy.misc import imsave
image_file = Image.open("convert_image.png") # open colour image
image_file= image_file.convert('L') # convert image to monochrome - this works
image_file= image_file.convert('1') # convert image to black and white
imsave('result_col.png', image_file)

Original ImageConverted Image


Tags: tofrom图像imageimportconvertpilpng
3条回答

用于创建具有自定义阈值的双层(黑白)图像的仅PIL解决方案:

from PIL import Image
img = Image.open('mB96s.png')
thresh = 200
fn = lambda x : 255 if x > thresh else 0
r = img.convert('L').point(fn, mode='1')
r.save('foo.png')

只是

r = img.convert('1')
r.save('foo.png')

你得到一个抖动的图像。

从左到右输入图像、黑白转换结果和抖动结果:

Input ImageBlack and White ResultDithered Result

您可以单击图像以查看未缩放版本。

from PIL import Image 
image_file = Image.open("convert_image.png") # open colour image
image_file = image_file.convert('1') # convert image to black and white
image_file.save('result.png')

收益率

enter image description here

另一个选项(在需要使用分段遮罩时,这对于科学目的很有用)是简单地应用阈值:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Binarize (make it black and white) an image with Python."""

from PIL import Image
from scipy.misc import imsave
import numpy


def binarize_image(img_path, target_path, threshold):
    """Binarize an image."""
    image_file = Image.open(img_path)
    image = image_file.convert('L')  # convert image to monochrome
    image = numpy.array(image)
    image = binarize_array(image, threshold)
    imsave(target_path, image)


def binarize_array(numpy_array, threshold=200):
    """Binarize a numpy array."""
    for i in range(len(numpy_array)):
        for j in range(len(numpy_array[0])):
            if numpy_array[i][j] > threshold:
                numpy_array[i][j] = 255
            else:
                numpy_array[i][j] = 0
    return numpy_array


def get_parser():
    """Get parser object for script xy.py."""
    from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
    parser = ArgumentParser(description=__doc__,
                            formatter_class=ArgumentDefaultsHelpFormatter)
    parser.add_argument("-i", "--input",
                        dest="input",
                        help="read this file",
                        metavar="FILE",
                        required=True)
    parser.add_argument("-o", "--output",
                        dest="output",
                        help="write binarized file hre",
                        metavar="FILE",
                        required=True)
    parser.add_argument("--threshold",
                        dest="threshold",
                        default=200,
                        type=int,
                        help="Threshold when to show white")
    return parser


if __name__ == "__main__":
    args = get_parser().parse_args()
    binarize_image(args.input, args.output, args.threshold)

对于./binarize.py -i convert_image.png -o result_bin.png --threshold 200,它看起来是这样的:

enter image description here

相关问题 更多 >

    热门问题