彩色图片转换成黑白图片的还是比较简单,真正的转换过程其实只需要一行代码块就能实现。
若是黑白图片转换成彩色图片的话过程就比较复杂了,今天这里只说明彩色图片转换成黑白图片的python实现过程。
使用的环境相关参数列表如下:
操作系统:Windows7
开发工具:pycharm 2021.1
python内核版本:3.8.6
python非标准库:pillow
若是没有安装pillow的非标准库的话,使用pip的方式安装一下就OK了。
pip install pillow -i https://pypi.tuna./simple/
开发一个函数colour_trans_single,以图片的输入输出路径为参数实现一个单张图片的转换过程。
# Importing the Image module from the PIL library.
from PIL import Image
def colour_trans_single(image_path_in=None, image_path_out=None):
"""
This function takes an image path, converts it to a numpy array, converts it to a grayscale image, and saves it to a new
file.
:param image_path_in: The path to the image you want to convert
:param image_path_out: The path to the output image
"""
image = Image.open(image_path_in) # 打开输入的图片返回Image对象
image = image.convert('L') # 实现图片灰度转换
image.save(image_path_out) # 保存转换完成的图片对象
使用上述函数colour_trans_single,其实就已经完成了单张图片转换为黑白图片的转换过程。
若是需要批量转换操作的,再开发一个路径处理函数batch_trans然后使用循环的方式去调用单张图片转换函数colour_trans_single即可实现批量转换。
# Importing the os module.
import os
# A logging library.
from loguru import logger
def batch_trans(dir_in=None, dir_out=None):
"""
This function takes a directory of .txt files and converts them to .csv files
:param dir_in: the directory where the input files are located
:param dir_out: the directory where the output files will be saved
"""
if dir_in is None or dir_out is None:
logger.error('输入或输出的文件夹路径为空!')
else:
for file_name in os.listdir(dir_in):
if file_name.__contains__('.') and \
(file_name.split('.')[1] == 'png' or file_name.split('.')[1] == 'jpg'
or file_name.split('.')[1] == 'PNG' or file_name.split('.')[1] == 'jpeg'):
logger.info('当前文件名称:{0}'.format(file_name))
logger.info('当前文件属性校验为图片,可以进行转换操作!')
colour_trans_single(os.path.join(dir_in, file_name), os.path.join(dir_out, file_name))
batch_trans(dir_in='./', dir_out='./')
最后的测试过程就是在百度上面随便找一张看起来顺眼的彩色照片来测试一下效果。

