Created
July 13, 2022 14:14
-
-
Save VisionOra/c15a434bfd13ee5c3914f0926c937eae to your computer and use it in GitHub Desktop.
Python - Send bytes Images to apis (Image to string) -> (String to image)
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
################################################################################### | |
# | |
# Decode Image and use in your API | |
# | |
# | |
################################################################################### | |
def string_to_ndarray(image_str: str) -> np.ndarray: | |
"""Convert string to nd-array | |
Args: | |
image_str (str): Image in string format | |
Returns: | |
np.ndarray: Numpy array image | |
""" | |
jpg_original = base64.b64decode(image_str) | |
jpg_as_np = np.frombuffer(jpg_original, dtype=np.uint8) | |
img = cv2.imdecode(jpg_as_np, flags=1) | |
return img | |
image1 = string_to_ndarray(image1) | |
image2 = string_to_ndarray(image2) |
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
################################################################################### | |
# | |
# Encode image to send through API | |
# | |
# | |
################################################################################### | |
import base64 | |
import numpy as np | |
import io | |
def numpy_to_str(image: np.asarary) -> str: | |
"""Convert Numpy to string | |
args: | |
image: (np.asarray) | |
Return | |
str: Image to string | |
""" | |
image_read = image.read() | |
image_64_encode = base64.b64encode(image_read) | |
base64_to_str = image_64_encode.decode('utf-8') | |
return base64_to_str | |
# Reading Image | |
image = open('/Users/sohaibanwar/Documents/Mzao/facematch-fastapi/image3.jpg', 'rb') #open binary file in read mode | |
# Converting to string | |
string = numpy_to_str(image) | |
# Making paylaod | |
pload = { | |
"image1Base64": string, | |
"image2Base64": string | |
} | |
# Sending to the api | |
headers = { | |
"accept": "application/json", | |
"Content-Type": "application/json" | |
} | |
# Dumping json | |
pload1 = json.dumps(pload, ensure_ascii=False, indent=4) | |
r = requests.get('http://localhost:7000/facematch/one-to-one-match', data=pload1, headers=headers) | |
print(r.text) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment