from PIL import Image
import numpy as np
import cv2
import base64
import io
import requests


def test():
    image_path='test/P0017.png'
    image_array=cv2.imread(image_path)
    print(image_array.shape)
    
    image_encode=base64.b64encode(image_array).decode('utf-8')  
    image_bytes=bytes(image_encode,encoding='utf-8')
    image_decode=np.frombuffer(base64.decodebytes(image_bytes),dtype=np.uint8) 
    print(image_decode.shape)
    
    request_url='http://192.168.109.49:5000/'
   
    headers={'content-type':'application/json'}
    data={'image':image_encode}
    
    #response=requests.post(request_url,data=data,headers=headers)
    response=requests.post(request_url,"POST",files=data)
    print(response)
    #image=open(image_path,'rb').read()
    #image=Image.open(io.BytesIO(image))
    #image=image.resize((224,224))
    #image=np.asarray(image
def test2():
    image_path='test/P0017.png'
    image_ori=cv2.imread(image_path)
    api = 'http://192.168.109.49:8000/detector'
    #img = cv2.imencode('.jpg', img_ori)[-1]
    
    image_encode=base64.b64encode(image_ori).decode('utf-8')  
    img=bytes(image_encode,encoding='utf-8')
    h,w,c=image_ori.shape
    
    files = {'file': img}
    files = {'file': img,'name':'P0017',
            'img_width':w,
            'img_height':h,
            'img_chs':c
    }
    res = requests.request("POST", api, files=files).json()

    if res['msg'] == 'success':
        bboxes = res['data']['bboxes']
        print(bboxes)
        #bboxes = np.asarray(bboxes, dtype=np.int32)
def test3():
    image_path='test/P0017.png'
    image_ori=cv2.imread(image_path)
    api = 'http://192.168.109.49:8000/detector'
    #img = cv2.imencode('.jpg', img_ori)[-1]
    
    input_ ={
        'img_data':'',
        'img_width':512,
        'img_height':512,
        'img_chs':3
    }
    
    with open(image_path,'rb') as f:
        input_['img_data']=base64.b64encode(f.read()).decode()
        
    image_encode=base64.b64encode(image_ori).decode('utf-8')  
    image_bytes=bytes(image_encode,encoding='utf-8')
    input_['img_data']=image_bytes:
    
    response=requests.post(api,json=input_)
    print(response.text)    
      
    
    
if __name__=='__main__':
    test2()