打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
python实现彩色图片批量转换黑白照片!

彩色图片转换成黑白图片的还是比较简单,真正的转换过程其实只需要一行代码块就能实现。

若是黑白图片转换成彩色图片的话过程就比较复杂了,今天这里只说明彩色图片转换成黑白图片的python实现过程。

使用的环境相关参数列表如下:

操作系统:Windows7
开发工具:pycharm 2021.1
python内核版本:3.8.6
python非标准库:pillow

若是没有安装pillow的非标准库的话,使用pip的方式安装一下就OK了。

pip install pillow -i https://pypi.tuna.tsinghua.edu.cn/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='./')

最后的测试过程就是在百度上面随便找一张看起来顺眼的彩色照片来测试一下效果。

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
文件夹里所有的图片调整大小-Python
PIL 拼接图片实践
如何用Python读取Excel中图片?又如何用Python往Excel中写入图片?
使用Python实现批量更改文件夹下图片的名称
Python:创建数据集目录,新建文件夹
利用Python和Tensorflow构建卷积神经网络的9个步骤
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服