用Python玩转图片处理,并导出文件列表到Excel文件

1、用Python玩转图片处理

class ImageUtils:
    """ 图片处理工具 """
    def __init__(self, source_dir, target_dir):
        self.source_dir = source_dir
        self.target_dir = target_dir

    def thumbnail(self, filename, percent=0.5):
        ‘缩略图‘
        im = Image.open(os.path.join(self.source_dir, filename))
        w, h = im.size
        print(‘Original image size: %sx%s‘ % (w, h))
        im.thumbnail((int(w*percent), int(h*percent)))
        print(‘Thumbnail image to: %sx%s‘ % (int(w*percent), int(h*percent)))
        output = os.path.join(self.target_dir, filename.split(‘.‘)[0]+‘-thumbnail.jpg‘)
        im.save(output, ‘jpeg‘)

    def resize(self, filename, horizontal_ratio=0.5, vertical_ratio=0.5):
        ‘调整大小‘
        im = Image.open(os.path.join(self.source_dir, filename))
        w, h = im.size
        print(‘Original image size: %sx%s‘ % (w, h))
        im_size = im.resize((int(w*horizontal_ratio), int(h*vertical_ratio)))
        print(‘Resize image to: %sx%s‘ % (int(w*horizontal_ratio), int(h*vertical_ratio)))
        output = os.path.join(self.target_dir, filename.split(‘.‘)[0]+‘-resize.jpg‘)
        im_size.save(output, ‘jpeg‘)

    def enhance(self, filename, enhance_ratio=1.3):
        ‘图片对比度增强‘
        im = Image.open(os.path.join(self.source_dir, filename))
        enh = ImageEnhance.Contrast(im)
        print(f‘图像对比度增强: {enhance_ratio}倍‘)
        output = os.path.join(self.target_dir, filename.split(‘.‘)[0]+‘-enhance.jpg‘)
        enh.enhance(enhance_ratio).save(output, ‘jpeg‘)

    def region(self, filename, snap=(0.1, 0.1, 0.9, 0.9)):
        ‘截取一块区域‘
        im = Image.open(os.path.join(self.source_dir, filename))
        w, h = im.size
        box = (int(w*snap[0]), int(h*snap[1]), int(w*snap[2]), int(h*snap[3]))
        print(f‘图像截取区域: {box}‘)
        region = im.crop(box)
        output = os.path.join(self.target_dir, filename.split(‘.‘)[0]+‘-region.jpg‘)
        region.save(output, ‘jpeg‘)

    def rotate(self, filename, angle=0):
        ‘旋转图片,翻转‘
        im = Image.open(os.path.join(self.source_dir, filename))
        print(f‘图像旋转: {angle}°‘)
        output = os.path.join(self.target_dir, filename.split(‘.‘)[0]+‘-rotate.jpg‘)
        im.rotate(angle).save(output, ‘jpeg‘)

    def flip(self, filename, horizontal=False, vertical=False):
        ‘翻转‘
        im = Image.open(os.path.join(self.source_dir, filename))
        if horizontal:
            print(‘图像水平翻转‘)
            im = im.transpose(Image.FLIP_LEFT_RIGHT)
        if vertical:
            print(‘图像上下翻转‘)
            im = im.transpose(Image.FLIP_TOP_BOTTOM)
        output = os.path.join(self.target_dir, filename.split(‘.‘)[0]+‘-flip.jpg‘)
        im.save(output, ‘jpeg‘)

    def add_logo(self, filename, logo_file):
        ‘添加水印‘
        im_logo = Image.open(os.path.join(self.source_dir, logo_file))
        logo_width, logo_height = im_logo.size
        im_target = Image.open(os.path.join(self.source_dir, filename))
        target_width, target_height = im_target.size
        im_copy = im_target.copy()
        print(‘图像添加水印‘)
        im_copy.paste(im_logo, (target_width-logo_width, target_height-logo_height), im_logo)
        output = os.path.join(self.target_dir, filename.split(‘.‘)[0]+‘-add_logo.jpg‘)
        im_copy.save(output, ‘jpeg‘)

    def new_image(self, text=‘Text‘):
        ‘创建新图片‘
        im_new = Image.new(‘RGBA‘, (400, 400), ‘white‘)
        print(‘创建新图片‘)
        pic = ImageDraw.Draw(im_new)
        print(‘图片添加文字‘)
        pic.text((50, 50), text, fill=‘blue‘)
        output = os.path.join(self.target_dir, ‘new_image.png‘)
        im_new.save(output)

    def msyh_font(self, text=‘文字‘):
        ‘设置字体‘
        im_new = Image.new(‘RGBA‘, (400, 400), ‘white‘)
        pic = ImageDraw.Draw(im_new)
        fonts_path = r‘D:\VSCode\xuan_demo_v0302\fonts\msyh.ttf‘
        msyh = ImageFont.truetype(fonts_path, 40)
        print(‘文字格式为微软雅黑‘)
        pic.text((50, 50), text, fill=‘blue‘, font=msyh)
        output = os.path.join(self.target_dir, ‘new_image_msyh.png‘)
        im_new.save(output)

2、导出文件列表到Excel文件

class ImageSystem:
    """ 图片列表生成excel文件系统"""
    def __init__(self, dirname):
        self.dirpath = dirname

    def listfile(self, img_type=‘.jpg‘):
        ‘获取指定路径下所有的图片文件, 返回列表‘
        img_File_List = os.listdir(self.dirpath)  # 图片列表
        image_list = []
        for filename in img_File_List:
            filepath = os.path.join(self.dirpath, filename)  # 图片的绝对路径
            if os.path.isdir(filepath):
                self.listfile(filepath)
                print(filepath)
            else:
                if os.path.isfile(filepath) and filename.lower().endswith(img_type):
                    print(os.path.join(self.dirpath, filename))
                    image_list.append(os.path.join(self.dirpath, filename))
        return image_list

    def xlsx_create(self, image_list, filename=‘Workbook.xlsx‘):
        ‘创建excel表格‘
        wb = Workbook()
        ws = wb.active
        ws[‘A1‘] = ‘文件名:‘
        for s in image_list:
            ws.append([s, self.get_FileSize(s)])
        ws.append([datetime.datetime.now()])
        output = os.path.join(r‘D:\VSCode\xuan_demo_v0302\test‘, filename)
        print(‘创建excel表格‘)
        wb.save(output)

    def get_FileSize(self, filename):
        ‘获取文件的大小,结果保留两位小数,单位为kb‘
        fsize = os.path.getsize(filename)
        fsize = fsize/float(1024)
        return f‘{round(fsize, 2)} kb‘

3、运行

def main():
    source_dir = r‘D:\VSCode\xuan_demo_v0302\image‘
    target_dir = r‘D:\VSCode\xuan_demo_v0302\test‘
    test_image = ImageUtils(source_dir, target_dir)
    test_image.thumbnail(‘scenery.jpg‘, 0.9)
    test_image.resize(‘scenery.jpg‘, 0.9, 0.5)
    test_image.enhance(‘scenery.jpg‘, 1.5)
    test_image.region(‘scenery.jpg‘, snap=(0.2, 0.2, 0.55, 0.5555))
    test_image.rotate(‘scenery.jpg‘, angle=10)
    test_image.flip(‘scenery.jpg‘, horizontal=True, vertical=True)
    test_image.add_logo(‘scenery.jpg‘, ‘logo.png‘)
    test_image.new_image()
    test_image.msyh_font()
    image_file = ImageSystem(source_dir)
    image_list = image_file.listfile()
    image_file.xlsx_create(image_list, ‘image_list.xlsx‘)

if __name__ == "__main__":
    main()

原文地址:https://blog.51cto.com/14265713/2414144

时间: 2024-08-23 01:39:39

用Python玩转图片处理,并导出文件列表到Excel文件的相关文章

Python xlrd、xlwt、xlutils读取、修改Excel文件

Python xlrd.xlwt.xlutils读取.修改Excel文件 一.xlrd读取excel 这里介绍一个不错的包xlrs,可以工作在任何平台.这也就意味着你可以在Linux下读取Excel文件. 首先,打开workbook:    import xlrdwb = xlrd.open_workbook('myworkbook.xls') 检查表单名字:    wb.sheet_names() 得到第一张表单,两种方式:索引和名字    sh = wb.sheet_by_index(0)s

python 玩转字符串,字典,列表排序,查找,去重

问题1.list去重 1.方法1:利用集合的去重特性. a=[1,2,1] b=list(set(a)) 缺点:集合是无序的,可能改变数据顺序 b.sort(key=a.index) 2.方法2:利用numpy中的unique()函数可以保持数据的唯一性 a=[1,2,1] b=list(np.unique(np.array(a))) 3.方法3:利用字典键的唯一性 a=[1,2,1] b={}.fromkeys(i for i in a).keys() 4.方法4: 原文地址:https://

python通过xlwt模块直接在网页上生成excel文件并下载

import xlwt import StringIO import web urls = ( '/rim_request','rim_request', '/rim_export','rim_export', '/(.*)', 'index' ) class rim_export: #render = web.template.render('adsl') def GET(self): web.header('Content-type','application/vnd.ms-excel')

【python】解析Excel中使用xlrd库、xlwt库操作,读取Excel文件详解(一)

上文提供了Excel文件读写操作的基本模板,本文进一步详解这两个模块的功能. 一.Book(class) 由xlrd.open_work("example.xls")返回 nsheets: sheets数 sheet_names: sheet名称列表 sheets: sheet列表 sheet_by_index(sheetx): 按序号提取sheet sheet_by_name(sheet_name): 按名称提取sheet 二.Sheet(class) 由Book object相关方

用python玩微信

Python玩转微信 大家每天都在用微信,有没有想过用python来控制我们的微信,不多说,直接上干货!  这个是在 itchat上做的封装  http://itchat.readthedocs.io/zh/latest/ 安装模块 pip3 install wxpy pip install wxpy -i "https://pypi.doubanio.com/simple/" #豆瓣源 1.生成微信对象 bot = Bot() #初始化一个对象,就相当于拿到了这个人的微信,后续的一些

程序员带你十天快速入门Python,玩转电脑软件开发(二)

关注今日头条-做全栈攻城狮,学代码也要读书,爱全栈,更爱生活.提供程序员技术及生活指导干货. 如果你真想学习,请评论学过的每篇文章,记录学习的痕迹. 请把所有教程文章中所提及的代码,最少敲写三遍,达到熟悉的效果. 声明:本次教程主要适用于已经习得一门编程语言的程序员.想要学习第二门语言.有梦想,立志做全栈攻城狮的你 如果是小白,也可以学习本教程.不过可能有些困难.如有问题在文章下方进行讨论.或者添加QQ群538742639.群马上就满了,名额不多. 上节课主要讲解了以下内容: 为什么学习Pyth

程序员带你十天快速入门Python,玩转电脑软件开发(三)

声明:本次教程主要适用于已经习得一门编程语言的程序员.想要学习第二门语言.有梦想,立志做全栈攻城狮的你 . 如果是小白,也可以学习本教程.不过可能有些困难.如有问题在文章下方进行讨论.或者添加QQ群538742639.群马上就满了,名额不多. 这是高级程序员快速入门Python语言课程.助你快速学习Python语言.这是第三课. 程序员带你十天快速入门Python,玩转电脑软件开发(一) 程序员带你十天快速入门Python,玩转电脑软件开发(二) 因技术知识连贯性,还没有学习前两课的同学,建议点

python生成测试图片

直接代码 1 import cv2.cv as cv 2 saveImagePath = 'E:/ScreenTestImages/' 3 4 colorRed = [0,0,255] 5 colorGreen = [0,255,0] 6 colorBlue = [255,0,0] 7 colorWhite = [255,255,255] 8 colorBlack = [0,0,0] 9 colorAqua = [255,255,0] 10 colorFuchsia = [255,0,255]

程序员带你十天快速入门Python,玩转电脑软件开发(一)

关注今日头条-做全栈攻城狮,学代码也要读书,爱全栈,更爱生活.提供程序员技术及生活指导干货. 如果你真想学习,请评论学过的每篇文章,记录学习的痕迹. 请把所有教程文章中所提及的代码,最少敲写三遍,达到熟悉的效果. 声明:本次教程主要适用于已经习得一门编程语言的程序员.想要学习第二门语言的你.有梦想的你,立志做全栈攻城狮. 如果是小白,也可以学习本教程.不过可能有些困难.如有问题在文章下方进行讨论.或者添加QQ群538742639.群马上就满了,名额不多. 目录: 为什么学习Python? Pyt