-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcleanImg.py
34 lines (29 loc) · 1.03 KB
/
cleanImg.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
from PIL import Image
import os
def check_images(directory):
for filename in os.listdir(directory):
filepath = os.path.join(directory, filename)
if os.path.isdir(filepath):
check_images(filepath)
else:
try:
with Image.open(filepath) as img:
img.verify()
except (IOError, SyntaxError) as e:
print(f"{filepath} cannot be opened: {e}")
os.remove(filepath)
def check_truncated_images(directory):
for filename in os.listdir(directory):
filepath = os.path.join(directory, filename)
if os.path.isdir(filepath):
check_truncated_images(filepath)
else:
try:
with Image.open(filepath) as img:
img.load()
except OSError as e:
print(f"{filepath} is truncated: {e}")
os.remove(filepath)
targetdir = "./data/kitchen"
check_images(targetdir)
check_truncated_images(targetdir)