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 另一个程序正在使用此文件,进程无法访问。"+文件路径"的解决方案

原文地址:https://www.cnblogs.com/hider/p/15758856.html