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设计】。

相关文章

用python实现百度翻译的示例代码

用python实现百度翻译的示例代码

用python实现百度翻译,分享给大家,具体如下: 首先,需要简单的了解一下爬虫,尽可能简单快速的上手,其次,需要了解的是百度的API的接口,搞定这个之后,最后,按照官方给出的demo...

Python 函数基础知识汇总

一、函数基础 简单地说,一个函数就是一组Python语句的组合,它们可以在程序中运行一次或多次运行。Python中的函数在其他语言中也叫做过程或子例程,那么这些被包装起来的语句通过一个函...

python的格式化输出(format,%)实例详解

皇城PK Python中格式化字符串目前有两种阵营:%和format,我们应该选择哪种呢? 自从Python2.6引入了format这个格式化字符串的方法之后,我认为%还是format这...

TensorFlow神经网络优化策略学习

TensorFlow神经网络优化策略学习

在神经网络模型优化的过程中,会遇到许多问题,比如如何设置学习率的问题,我们可通过指数衰减的方式让模型在训练初期快速接近较优解,在训练后期稳定进入最优解区域;针对过拟合问题,通过正则化的方...

Python Django 实现简单注册功能过程详解

Python Django 实现简单注册功能过程详解

项目创建略,可参考Python Django Vue 项目创建。 目录结构如下 编辑views.py from django.shortcuts import render #...