Last active
January 24, 2022 08:34
-
-
Save victory-sokolov/4c8b664946fe14341e46c74bf32d551d to your computer and use it in GitHub Desktop.
Image utils for Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import io | |
import cv2 | |
import base64 | |
import numpy as np | |
from PIL import Image | |
# Take in base64 string and return PIL image | |
def string_to_image(base64_string): | |
imgdata = base64.b64decode(base64_string) | |
return Image.open(io.BytesIO(imgdata)) | |
# convert PIL Image to an RGB image( technically a numpy array ) that's compatible with opencv | |
def to_RGB(image): | |
return cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB) | |
def base64_data_to_image(image: str) -> str: | |
"""Convert Base64 to image and return its name""" | |
target = settings.UPLOAD_FOLDER | |
date = datetime.datetime.utcnow().strftime('%Y-%m-%d-%H-%M-%S') | |
base64_to_image = Image.open(BytesIO(base64.b64decode(image))) | |
image_path = f'{target}/{date}.jpg' | |
base64_to_image.save(image_path) | |
return image_path | |
def cv_to_pil(image): | |
"""Convert cv2 to PIL image""" | |
img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) | |
im_pil = Image.fromarray(img) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment