亲宝软件园·资讯

展开

python批量转换图片为黑白 python实现批量转换图片为黑白

Alex山南水北 人气:0

用到的库: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)

加载全部内容

相关教程
猜你喜欢
用户评论