import socket
import cv2
import numpy as np
import time
#本代码配套的发送代码是 depth_frame_compress.py配套



def depth_back(imgremake):
    imgremake=np.array(imgremake)
    img_depth2 = np.zeros((720, 1280),dtype=np.uint16)
    h = np.array(imgremake[:, :, 0], dtype=np.uint16)
    l = np.array(imgremake[:, :, 1], dtype=np.uint16)
    img_depth2 = (h << 8) + l
    return img_depth2


s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 绑定端口:
s.bind(('127.0.0.1', 9999))
print('Bind UDP on 9999...')
depth_img = np.zeros((720,1280,3),dtype=np.uint8)
i=0
flag=0
while True:

    if flag==0:
        data, addr = s.recvfrom(400000)
        h=np.fromstring(data, np.uint8)
        h_decode=cv2.imdecode(h,cv2.IMREAD_COLOR)
        shape=h_decode.shape
        #print(h)
        print(h_decode.shape)

        if (shape[0]==2)&(shape[1]==2):

            flag=1
            print('begin to receive frame...')

    if flag==1:
        t=time.time()

        data, addr = s.recvfrom(100000)
        nparr = np.fromstring(data, np.uint8)

        img_decode = cv2.imdecode(nparr, cv2.IMREAD_COLOR)

        #print(img_decode.shape)
        shape=img_decode.shape
        if (shape[0]==2)&(shape[1]==2):
            continue
        # print(data_decode) # 打印接收到的数据
        kuai=i*36
        depth_img[kuai:kuai+36,:,:]=img_decode
        i=i+1
        # print('i=:',i)

        if (i%20==0) & (i!=0):  # 假设不丢任何帧  则收到开始指令后的720则为一个frame
            i=0
            flag=0
            print('time:',time.time() - t)
            depth_img_array=depth_back(depth_img)
            depth_colormap = cv2.applyColorMap(cv2.convertScaleAbs(depth_img_array, alpha=0.03), cv2.COLORMAP_JET)
            # print(depth_img_array.shape)
            cv2.imshow('jieshou',depth_colormap)
            cv2.waitKey(1)
            depth_img = np.zeros((720,1280,3),dtype=np.uint8)
            flag=0
            print('received one frame')
            print('receive——client:', depth_img_array[360, 640])