python image convert_使用python PIL将RGB图像转换为纯黑白imag

另一个选项(在需要使用分段遮罩时,这对于科学目的很有用)是简单地应用阈值:#!/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,它看起来是这样的:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值