Spaces:
Runtime error
Runtime error
jhj0517
commited on
Commit
·
4e46389
1
Parent(s):
7ab19f6
Add save_image
Browse files- modules/utils.py +34 -3
modules/utils.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
import os
|
| 2 |
from PIL import Image
|
|
|
|
| 3 |
import numpy as np
|
| 4 |
|
| 5 |
|
|
@@ -10,6 +11,36 @@ def open_folder(folder_path: str):
|
|
| 10 |
print(f"The folder '{folder_path}' does not exist.")
|
| 11 |
|
| 12 |
|
| 13 |
-
def
|
| 14 |
-
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
from PIL import Image
|
| 3 |
+
from typing import Optional, Union
|
| 4 |
import numpy as np
|
| 5 |
|
| 6 |
|
|
|
|
| 11 |
print(f"The folder '{folder_path}' does not exist.")
|
| 12 |
|
| 13 |
|
| 14 |
+
def is_image_file(filename):
|
| 15 |
+
image_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.webp'}
|
| 16 |
+
return os.path.splitext(filename.lower())[1] in image_extensions
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def get_image_files(image_dir: str):
|
| 20 |
+
image_files = []
|
| 21 |
+
for filename in os.listdir(image_dir):
|
| 22 |
+
if is_image_file(filename):
|
| 23 |
+
image_files.append(os.path.join(image_dir, filename))
|
| 24 |
+
return image_files
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def save_image(image: Union[np.ndarray, str],
|
| 28 |
+
output_path: Optional[str] = None,
|
| 29 |
+
output_dir: Optional[str] = None):
|
| 30 |
+
|
| 31 |
+
if output_dir is None and output_path is None:
|
| 32 |
+
raise "Either output_path or output_dir should be provided"
|
| 33 |
+
|
| 34 |
+
if isinstance(image, str):
|
| 35 |
+
image = Image.open(image)
|
| 36 |
+
elif isinstance(image, np.ndarray):
|
| 37 |
+
image = Image.fromarray(image)
|
| 38 |
+
|
| 39 |
+
if output_path is not None:
|
| 40 |
+
image.save(output_path, "JPEG")
|
| 41 |
+
return
|
| 42 |
+
|
| 43 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 44 |
+
num_images = len(get_image_files(output_dir))
|
| 45 |
+
output_path = os.path.join(output_dir, f"{num_images:05d}.jpg")
|
| 46 |
+
image.save(output_path)
|