我正在使用 Python 图像库进行一些非常简单的图像处理,但是我在将灰度图像转换为单色(黑白)图像时遇到了麻烦。如果我在将图像更改为灰度(转换('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)
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')
产量
另一个选项(例如,当您需要使用分割蒙版时,出于科学目的,这很有用)是简单地应用阈值:
#!/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
:
正如 Martin Thoma 所说,您通常需要应用阈值。但是您可以使用简单的矢量化来完成此操作,它的运行速度比该答案中使用的 for 循环快得多。
下面的代码将图像的像素转换为 0(黑色)和 1(白色)。
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
#Pixels higher than this will be 1. Otherwise 0.
THRESHOLD_VALUE = 200
#Load image and convert to greyscale
img = Image.open("photo.png")
img = img.convert("L")
imgData = np.asarray(img)
thresholdedData = (imgData > THRESHOLD_VALUE) * 1.0
plt.imshow(thresholdedData)
plt.show()
这就是我的做法,它有更好的效果,就像灰色滤镜一样
from PIL import Image
img = Image.open("profile.png")
BaW = img.convert("L")
BaW.save("profileBaW.png")
BaW.show()
这是使用 Python 实现此操作的简单方法:
import numpy as np
import imageio
image = imageio.imread(r'[image-path]', as_gray=True)
# getting the threshold value
thresholdValue = np.mean(image)
# getting the dimensions of the image
xDim, yDim = image.shape
# turn the image into a black and white image
for i in range(xDim):
for j in range(yDim):
if (image[i][j] > thresholdValue):
image[i][j] = 255
else:
image[i][j] = 0