import numpy as np
import skimage
import numpy as np
import cv2 as cv


def DESI_find_Contour(image):
    
    '''takes in image of size (npix, npix,nchannel)'''

    #data = np.transpose(image,(2,1,0))
    print(np.shape(image))
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
    s = gray.shape[1]
    
    # normalzation
    gray = np.uint8((gray-np.min(gray))*100/(np.max(gray)-np.min(gray)))
    
    _, thresh = cv.threshold(gray, 10, 255, cv.THRESH_BINARY_INV + cv.THRESH_OTSU)

    # 找到中心位置的框
    contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)

    for contour in contours:
        x, y, w, h = cv.boundingRect(contour)
        if x <= 0 or y <= 0:
            pass
        elif x + w > s or y + h > s:
            pass
        else:
            if  x<s/2 and x+w > s/2 and  y<s/2 and y+h > s/2 :
                # 确定 crop_size，因为沿着边，所以+10
                crop_size = max(int(x+w-s/2),int(y+h-s/2),int(s/2-x),int(s/2-y)) + 10
                if crop_size > int(s/2):
                    crop_size = int(s/2)
                return int(s/2)-crop_size,int(s/2) + crop_size,int(s/2)-crop_size,int(s/2) + crop_size

    return 0,s,0,s
