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

