Upload scripts/repair_dataset_folder.py with huggingface_hub
Browse files
scripts/repair_dataset_folder.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
from PIL import Image
|
| 3 |
+
from PIL.ImageOps import exif_transpose
|
| 4 |
+
from tqdm import tqdm
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
parser = argparse.ArgumentParser(description='Process some images.')
|
| 8 |
+
parser.add_argument("input_folder", type=str, help="Path to folder containing images")
|
| 9 |
+
|
| 10 |
+
args = parser.parse_args()
|
| 11 |
+
|
| 12 |
+
img_types = ['.jpg', '.jpeg', '.png', '.webp']
|
| 13 |
+
|
| 14 |
+
# find all images in the input folder
|
| 15 |
+
images = []
|
| 16 |
+
for root, _, files in os.walk(args.input_folder):
|
| 17 |
+
for file in files:
|
| 18 |
+
if file.lower().endswith(tuple(img_types)):
|
| 19 |
+
images.append(os.path.join(root, file))
|
| 20 |
+
print(f"Found {len(images)} images")
|
| 21 |
+
|
| 22 |
+
num_skipped = 0
|
| 23 |
+
num_repaired = 0
|
| 24 |
+
num_deleted = 0
|
| 25 |
+
|
| 26 |
+
pbar = tqdm(total=len(images), desc=f"Repaired {num_repaired} images", unit="image")
|
| 27 |
+
for img_path in images:
|
| 28 |
+
filename = os.path.basename(img_path)
|
| 29 |
+
filename_no_ext, file_extension = os.path.splitext(filename)
|
| 30 |
+
# if it is jpg, ignore
|
| 31 |
+
if file_extension.lower() == '.jpg':
|
| 32 |
+
num_skipped += 1
|
| 33 |
+
pbar.update(1)
|
| 34 |
+
|
| 35 |
+
continue
|
| 36 |
+
|
| 37 |
+
try:
|
| 38 |
+
img = Image.open(img_path)
|
| 39 |
+
except Exception as e:
|
| 40 |
+
print(f"Error opening {img_path}: {e}")
|
| 41 |
+
# delete it
|
| 42 |
+
os.remove(img_path)
|
| 43 |
+
num_deleted += 1
|
| 44 |
+
pbar.update(1)
|
| 45 |
+
pbar.set_description(f"Repaired {num_repaired} images, Skipped {num_skipped}, Deleted {num_deleted}")
|
| 46 |
+
continue
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
try:
|
| 50 |
+
img = exif_transpose(img)
|
| 51 |
+
except Exception as e:
|
| 52 |
+
print(f"Error rotating {img_path}: {e}")
|
| 53 |
+
|
| 54 |
+
new_path = os.path.join(os.path.dirname(img_path), filename_no_ext + '.jpg')
|
| 55 |
+
|
| 56 |
+
img = img.convert("RGB")
|
| 57 |
+
img.save(new_path, quality=95)
|
| 58 |
+
# remove the old file
|
| 59 |
+
os.remove(img_path)
|
| 60 |
+
num_repaired += 1
|
| 61 |
+
pbar.update(1)
|
| 62 |
+
# update pbar
|
| 63 |
+
pbar.set_description(f"Repaired {num_repaired} images, Skipped {num_skipped}, Deleted {num_deleted}")
|
| 64 |
+
|
| 65 |
+
print("Done")
|