彩色圖片轉(zhuǎn)換成黑白圖片的還是比較簡(jiǎn)單,真正的轉(zhuǎn)換過(guò)程其實(shí)只需要一行代碼塊就能實(shí)現(xiàn)。
若是黑白圖片轉(zhuǎn)換成彩色圖片的話過(guò)程就比較復(fù)雜了,今天這里只說(shuō)明彩色圖片轉(zhuǎn)換成黑白圖片的python實(shí)現(xiàn)過(guò)程。
使用的環(huán)境相關(guān)參數(shù)列表如下:
操作系統(tǒng):Windows7
開(kāi)發(fā)工具:pycharm 2021.1
python內(nèi)核版本:3.8.6
python非標(biāo)準(zhǔn)庫(kù):pillow
若是沒(méi)有安裝pillow的非標(biāo)準(zhǔn)庫(kù)的話,使用pip的方式安裝一下就OK了。
pip install pillow -i https://pypi.tuna./simple/
開(kāi)發(fā)一個(gè)函數(shù)colour_trans_single,以圖片的輸入輸出路徑為參數(shù)實(shí)現(xiàn)一個(gè)單張圖片的轉(zhuǎn)換過(guò)程。
# 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) # 打開(kāi)輸入的圖片返回Image對(duì)象
image = image.convert('L') # 實(shí)現(xiàn)圖片灰度轉(zhuǎn)換
image.save(image_path_out) # 保存轉(zhuǎn)換完成的圖片對(duì)象
使用上述函數(shù)colour_trans_single,其實(shí)就已經(jīng)完成了單張圖片轉(zhuǎn)換為黑白圖片的轉(zhuǎn)換過(guò)程。
若是需要批量轉(zhuǎn)換操作的,再開(kāi)發(fā)一個(gè)路徑處理函數(shù)batch_trans然后使用循環(huán)的方式去調(diào)用單張圖片轉(zhuǎn)換函數(shù)colour_trans_single即可實(shí)現(xiàn)批量轉(zhuǎn)換。
# 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('當(dāng)前文件名稱:{0}'.format(file_name))
logger.info('當(dāng)前文件屬性校驗(yàn)為圖片,可以進(jìn)行轉(zhuǎn)換操作!')
colour_trans_single(os.path.join(dir_in, file_name), os.path.join(dir_out, file_name))
batch_trans(dir_in='./', dir_out='./')
最后的測(cè)試過(guò)程就是在百度上面隨便找一張看起來(lái)順眼的彩色照片來(lái)測(cè)試一下效果。

