时间:2020-09-18 python教程 查看: 845
本文实例为大家分享了python批量转换图片为黑白的具体代码,供大家参考,具体内容如下
用到的库:OpenCV、os
import cv2
import os
def re_name(path):
files = os.listdir(path)
for i, file in enumerate(files):
try:
new_file_name = os.path.join(path, str(i) + '.jpg')
old_file_name = os.path.join(path, file)
os.rename(old_file_name, new_file_name)
except:
continue
def gray_pic(path):
files = os.listdir(path)
for file in enumerate(files):
try:
pic = path + "\\" + str(file[1])
original_img = cv2.imread(pic)
gray = cv2.cvtColor(original_img, cv2.COLOR_BGR2GRAY)
cv2.imwrite(path + "\\" + str(file[1]), gray)
except:
continue
path = r'C:\Users\94090\Desktop\gray'
#re_name(path)
gray_pic(path)
注意:
小编再为大家分享一段很实用的代码:python批量处理图片颜色反转
#coding:utf-8
import os
from PIL import Image
import numpy as np
def resize(imgPath,savePath):
files = os.listdir(imgPath)
files.sort()
print('****************')
print('input :',imgPath)
print('start...')
for file in files:
fileType = os.path.splitext(file)
if fileType[1] == '.jpg':
new_png = Image.open(imgPath+'/'+file) #打开图片
#new_png = new_png.resize((20, 20),Image.ANTIALIAS) #改变图片大小
matrix = 255-np.asarray(new_png) #图像转矩阵 并反色
new_png = Image.fromarray(matrix) #矩阵转图像
new_png.save(savePath+'/'+file) #保存图片
print('down!')
print('****************')
if __name__ == '__main__':
# 待处理图片地址
dataPath = 'F:\\clean_images\\profiles\\'
#保存图片的地址
savePath = 'F:\\clean_images\\new_mask\\'
resize(dataPath,savePath)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持python博客。