|
from PIL import Image |
|
import numpy as np |
|
import base64 |
|
import json |
|
from torchvision.transforms import Compose, Resize, CenterCrop |
|
|
|
|
|
|
|
def encode_numpy_array(image_np): |
|
|
|
image_bytes = image_np.tobytes() |
|
|
|
|
|
encoded_image = base64.b64encode(image_bytes).decode() |
|
payload = { |
|
"encoded_image": encoded_image, |
|
"width": image_np.shape[1], |
|
"height": image_np.shape[0], |
|
"channels": image_np.shape[2], |
|
} |
|
payload_json = json.dumps(payload) |
|
return payload_json |
|
|
|
def decode_numpy_array(payload): |
|
payload_json = json.loads(payload) |
|
|
|
encoded_image = payload_json["encoded_image"] |
|
width = payload_json["width"] |
|
height = payload_json["height"] |
|
channels = payload_json["channels"] |
|
|
|
decoded_image = base64.b64decode(encoded_image) |
|
|
|
|
|
image_np = np.frombuffer(decoded_image, dtype=np.uint8).reshape(height, width, channels) |
|
|
|
return image_np |
|
|
|
|
|
def preprocess_image(image_np, max_size=224): |
|
|
|
image = Image.fromarray(image_np) |
|
|
|
|
|
transforms = Compose([ |
|
Resize(max_size, interpolation=Image.BICUBIC), |
|
CenterCrop(max_size), |
|
]) |
|
|
|
|
|
image = transforms(image) |
|
|
|
|
|
image_np = np.array(image) |
|
|
|
return image_np |