近期因?yàn)檠芯縯ensorflow,需要bmp位圖轉(zhuǎn)jpg格式研乒,并且原圖為灰度圖,要轉(zhuǎn)為RGB圖像酵紫,在網(wǎng)上搜告嘲,發(fā)現(xiàn)灰度轉(zhuǎn)RGB的python文章幾乎沒(méi)有,其實(shí)就一句代碼奖地,很簡(jiǎn)單橄唬,現(xiàn)貼出原代碼。
# coding:utf-8
import os
from PIL import Image
# bmp 轉(zhuǎn)換為jpg参歹,灰度圖轉(zhuǎn)RGB
def bmpToJpg_grayToRGB(file_path):
for fileName in os.listdir(file_path):
print(fileName)
newFileName = fileName[0:fileName.find(".bmp")]+".jpg"
print(newFileName)
im = Image.open(file_path+"\\"+fileName)
rgb = im.convert('RGB') #灰度轉(zhuǎn)RGB
rgb.save(file_path+"\\"+newFileName)
# 刪除原來(lái)的位圖
def deleteImages(file_path, imageFormat):
command = "del "+file_path+"\\*."+imageFormat
os.system(command)
def main():
file_path = "D:\\models-master\\research\\object_detection\\images"
bmpToJpg_grayToRGB(file_path)
deleteImages(file_path, "bmp")
if __name__ == '__main__':
main()
文件路徑可自行修改仰楚。