Spaces:
Running
Running
| import cv2 | |
| import numpy as np | |
| from PIL import Image as PILImage | |
| def _image_to_numpy(image): | |
| if image is None: | |
| return None | |
| if isinstance(image, np.ndarray): | |
| return image | |
| if isinstance(image, PILImage.Image): | |
| return np.array(image.convert("RGB")) | |
| if isinstance(image, dict): | |
| path = image.get("path") or image.get("name") | |
| if path: | |
| with PILImage.open(path) as img: | |
| return np.array(img.convert("RGB")) | |
| if isinstance(image, str): | |
| with PILImage.open(image) as img: | |
| return np.array(img.convert("RGB")) | |
| return np.array(image) | |
| def _rotate_image(image, rotate_code, direction): | |
| if image is None: | |
| return None | |
| try: | |
| image_array = _image_to_numpy(image) | |
| return cv2.rotate(image_array, rotate_code) | |
| except Exception as e: | |
| print(f"Error rotating image {direction}: {e}") | |
| return image | |
| def rotate_image_90_left(image): | |
| """Rotate image 90 degrees counter-clockwise.""" | |
| return _rotate_image(image, cv2.ROTATE_90_COUNTERCLOCKWISE, "left") | |
| def rotate_image_90_right(image): | |
| """Rotate image 90 degrees clockwise.""" | |
| return _rotate_image(image, cv2.ROTATE_90_CLOCKWISE, "right") | |
| def rotate_image_180(image): | |
| """Rotate image 180 degrees.""" | |
| return _rotate_image(image, cv2.ROTATE_180, "180 degrees") | |
| def reset_image_to_original(current_image, original_image): | |
| """Reset image to the stored original image when available.""" | |
| if original_image is None: | |
| return current_image | |
| return original_image | |