Upload extensions_built_in/dataset_tools/tools/image_tools.py with huggingface_hub
Browse files
extensions_built_in/dataset_tools/tools/image_tools.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Literal, Type, TYPE_CHECKING, Union
|
| 2 |
+
|
| 3 |
+
import cv2
|
| 4 |
+
import numpy as np
|
| 5 |
+
from PIL import Image, ImageOps
|
| 6 |
+
|
| 7 |
+
Step: Type = Literal['caption', 'caption_short', 'create_mask', 'contrast_stretch']
|
| 8 |
+
|
| 9 |
+
img_manipulation_steps = ['contrast_stretch']
|
| 10 |
+
|
| 11 |
+
img_ext = ['.jpg', '.jpeg', '.png', '.webp']
|
| 12 |
+
|
| 13 |
+
if TYPE_CHECKING:
|
| 14 |
+
from .llava_utils import LLaVAImageProcessor
|
| 15 |
+
from .fuyu_utils import FuyuImageProcessor
|
| 16 |
+
|
| 17 |
+
ImageProcessor = Union['LLaVAImageProcessor', 'FuyuImageProcessor']
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def pil_to_cv2(image):
|
| 21 |
+
"""Convert a PIL image to a cv2 image."""
|
| 22 |
+
return cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def cv2_to_pil(image):
|
| 26 |
+
"""Convert a cv2 image to a PIL image."""
|
| 27 |
+
return Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def load_image(img_path: str):
|
| 31 |
+
image = Image.open(img_path).convert('RGB')
|
| 32 |
+
try:
|
| 33 |
+
# transpose with exif data
|
| 34 |
+
image = ImageOps.exif_transpose(image)
|
| 35 |
+
except Exception as e:
|
| 36 |
+
pass
|
| 37 |
+
return image
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def resize_to_max(image, max_width=1024, max_height=1024):
|
| 41 |
+
width, height = image.size
|
| 42 |
+
if width <= max_width and height <= max_height:
|
| 43 |
+
return image
|
| 44 |
+
|
| 45 |
+
scale = min(max_width / width, max_height / height)
|
| 46 |
+
width = int(width * scale)
|
| 47 |
+
height = int(height * scale)
|
| 48 |
+
|
| 49 |
+
return image.resize((width, height), Image.LANCZOS)
|