zoukankan      html  css  js  c++  java
  • Python学习笔记:获取图片分辨率

    一、背景

    源其一个想法,在爬取微信公众号文章图片之后,过滤一些图标类文件。

    二、实操

    1.利用 PIL 包 Image 实现

    from PIL import Image
    filename = r'C:\Users\Hider\Desktop\we\2.gif'
    img = Image.open(filename)
    imgSize = img.size
    imgSize[0], imgSize[1]
    #  (370, 274)
    

    2.利用 opencv 实现

    # 首先安装 cv2 库
    # pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple opencv-python
    # cv2 无法识别中文路径!!!
    # 无法读取gif 只能读取jpg、png
    import cv2
    filename = r'C:\Users\Hider\Desktop\we\20190520143707462.png'
    
    img = cv2.imread(filename)
    img.shape
    # (335, 875, 3)
    

    三、遍历文件后删除不满足条件

    import os
    from PIL import Image
    path = r'C:\Users\Hider\Desktop\we'
    
    file_list = os.listdir(path)
    
    for file in file_list:
        filename = path + '\\' + file
        img = Image.open(filename)
        imgSize = img.size
        img.close()
        # print(imgSize)
        if imgSize[0] < 100 and imgSize[1] < 100:
            print(imgSize)
            os.remove(filename) # 删除文件
    

    哈哈哈!!!查故障过程中发现一篇文章的想法跟我一模一样,遂修改代码!!!

    真是开心!!!

    import os
    from PIL import Image
    path = r'C:\Users\Hider\Desktop\we'
    
    file_list = os.listdir(path)
    
    for file in file_list:
        if file.split('.')[-1] == 'gif':
            filename = os.path.join(path, file)
            img = Image.open(filename)
            imgSize = img.size
            img.close()
            # print(imgSize)
            if imgSize[0] > 200 or imgSize[1] > 200:
                pass
                # print(imgSize)
            else:
                os.remove(filename) # 删除文件
                print(file)
    

    四、其他问题

    遍历删除不满足条件的图片时出现以下错误:

    PermissionError: [WinError 32] 另一个程序正在使用此文件,进程无法访问。: 'C:\\Users\\Hider\\Desktop\\we2\\22.gif'
    

    经查找发现,不管是 PILopencv 等库在打开图片的时候,图片都处于被打开状态,无法进行删除,因此需要添加 close 代码。

    img.close() # 关闭图片
    

    一般 open 函数之后,就需要 close() 进行关闭。

    参考链接:python 获取图片分辨率的方法

    参考链接:错误:PermissionError: WinError 32 另一个程序正在使用此文件,进程无法访问。"+文件路径"的解决方案

  • 相关阅读:
    Difference between ClassNotFoundException and NoClassDefFoundError 规格严格
    RPM包。。。 规格严格
    Cygwin sshd Apache sshd 规格严格
    查看真实物理CPU个数 规格严格
    工具类网页 规格严格
    探测无线网卡。 规格严格
    DB2 Error 规格严格
    AIX 安装SSH 规格严格
    美国GIS研究的19个方向
    史上最有趣的Readme
  • 原文地址:https://www.cnblogs.com/hider/p/15758856.html
Copyright © 2011-2022 走看看