Grounded-Segment-Anything / api_client.py
liuyizhang
support gradio & api
82b6069
raw
history blame
2.15 kB
import requests, json
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
import base64
import io
def request_post(url, data, timeout=600, headers = None):
if headers is None:
headers = {
# 'content-type': 'application/json'
# 'Connection': 'keep-alive',
'Accept': '*/*', # 接受任何类型的返回数据
'Content-Type': 'application/json;charset=UTF-8', # 发送数据为json
# 'Content-Length': '156',
# 'Accept-Encoding': 'gzip, deflate',
# 'Accept-Language': 'zh-CN,zh;q=0.9',
# 'User-Agent': 'SamClub/5.0.45 (iPhone; iOS 15.4; Scale/3.00)',
# 'device-name': 'iPhone14,3',
# 'device-os-version': '15.4',
# 'device-type': 'ios',
# 'auth-token': authtoken,
# 'app-version': '5.0.45.1'
}
try:
response = requests.post(url=url, headers=headers, data=json.dumps(data), timeout=timeout)
response_data = response.json()
return response_data
except Exception as e:
print(f'request_post[Error]:' + str(e))
print(f'url: {url}')
print(f'data: {data}')
print(f'response: {response}')
return None
url = "http://127.0.0.1:7860/imgCLeaner"
def imgFile_to_base64(image_file):
with open(image_file, "rb") as f:
im_bytes = f.read()
im_b64_encode = base64.b64encode(im_bytes)
im_b64 = im_b64_encode.decode("utf8")
return im_b64
def base64_to_bytes(im_b64):
im_b64_encode = im_b64.encode("utf-8")
im_bytes = base64.b64decode(im_b64_encode)
return im_bytes
def base64_to_PILImage(im_b64):
im_bytes = base64_to_bytes(im_b64)
pil_img = Image.open(io.BytesIO(im_bytes))
return pil_img
image_file = 'dog.png'
data = {'remove_texts': "小狗 . 椅子",
'extend': 20,
'img': imgFile_to_base64(image_file),
}
ret = request_post(url, data, timeout=600, headers = None)
print(len(ret['result']['imgs']))
for img in ret['result']['imgs']:
pilImage = base64_to_PILImage(img)
plt.imshow(pilImage)
plt.show()
plt.clf()