python读取图片并修改格式与大小的方法

yipeiwu_com6年前Python基础

本文实例为大家分享了python读取图片并修改文件大小的具体代码,供大家参考,具体内容如下

# Author:NDK
# -*- coding:utf-8 -*-

from PIL import Image
import os
import cv2
import numpy as np
import glob
# old_dir = './test/'
# def read_image(cwd, newpath):
#   for roots, dirs, files in os.walk(cwd):
#     print(dirs)
#     for i in dirs:
#       print(i)
#       os.chdir(cwd + i)
#       for pic in glob.glob('*.png'):
#         _, image = pic.split('_')
#         img = image.split('.')[0]
#         print(img)
#         if len(img) != 0:
#           if int(img) % 2 != 0:
#             im = Image.open(pic)
#             im.save(newpath + i + '/' + pic)
# read_image('./num/','./new_img/')
# for i in range(10):
root_path = r"/test/9/"  #操作文件路径
print(root_path)
# dir = root_path+"images"+"/"
dir = root_path
count = 0
for root,dir,files in os.walk(dir):
  for file in files:
    srcImg = cv2.imread(root_path+"/"+str(file))
    img = Image.open(root_path+"/"+str(file))
    print(root_path+str(file))
    newImg = img.resize((50, 50), Image.BILINEAR)  #想调整的大小
    cv2.imwrite(r'./img2/'+str(file),newImg)    # 写入文件地址

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python3 unicode列表转换为中文的实例

python3 unicode列表转换为中文的实例

查了很多很多的资料无果,果然知乎牛逼,完美解决。 爬取网站时,最终得到list内容,编码为unicode,想让其转换为汉字并输出。 需要提取的为下图中unicode部分: 保存为列表...

快速了解Python相对导入

1、绝对导入和相对导入 绝对导入:按照sys.path顺序搜索,先主目录(sys.path中第一项''),然后PYTHONPATH环境变量、标准库路径、pth指定路径等。 相对导入:...

Python输出\u编码将其转换成中文的实例

Python输出\u编码将其转换成中文的实例

爬取了下小猪短租的网站出租房信息但是输出的时候是这种: 百度了下。python2.7在window上的编码确实是个坑 解决如下 如果是个字典的话要先将其转成字符串 导入json库 然后...

python3.6 tkinter实现屏保小程序

本文实例为大家分享了python3.6 tkinter实现屏保小程序,供大家参考,具体内容如下 该小程序是在闲着没事的时候,随便写的,就当打发无聊了。 该程序是用python3.6写的,...

python 常见字符串与函数的用法详解

strip去除空格 s = ' abcd efg ' print(s.strip()) #去除所有空格 print(s.lstrip()) #去除左边空格 print(s.rs...