一、背景
源其一個想法,在爬取微信公眾號文章圖片之后,過濾一些圖標類文件。
二、實操
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'
經查找發現,不管是 PIL
、opencv
等庫在打開圖片的時候,圖片都處於被打開狀態,無法進行刪除,因此需要添加 close
代碼。
img.close() # 關閉圖片
一般 open
函數之后,就需要 close()
進行關閉。
參考鏈接:python 獲取圖片分辨率的方法
參考鏈接:錯誤:PermissionError: WinError 32 另一個程序正在使用此文件,進程無法訪問。"+文件路徑"的解決方案