2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > python黑色背景rbg_使用python PIL将RGB图像转换为纯黑白图像

python黑色背景rbg_使用python PIL将RGB图像转换为纯黑白图像

时间:2021-04-12 05:55:37

相关推荐

python黑色背景rbg_使用python PIL将RGB图像转换为纯黑白图像

另一个选择(例如,当您需要使用分段蒙版时,对于科学目的很有用)只是应用阈值:

#!/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,它看起来像这样:

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。