二值化

1.自适应阈值二值化

def threshold_demo(image):

    gray = cv.cvtColor(image,cv.COLOR_BGR2GRAY)

    ret, binary = cv.threshold(gray, 0,255,cv.THRESH_BINARY | cv.THRESH_OTSU) 


    print("thresholdvalue:%s"%ret)

    cv.imshow("binary",binary)   

直方图只有一个波峰的时候,cv.THRESH_TRIANGLE效果最好

2.给定阈值二值化

def threshold_demo(image):

    gray = cv.cvtColor(image,cv.COLOR_BGR2GRAY) 
       
    ret, binary = cv.threshold(gray,127,255,cv.THRESH_BINARY) 
    
    print("thresholdvalue:%s"%ret)    
    
    cv.imshow("binary",binary)   

3.局部二值化


def local_threshold(image):  

    gray = cv.cvtColor(image,cv.COLOR_BGR2GRAY)

    dst = cv.adaptiveThreshold(gray,255,cv.ADAPTIVE_THRESH_MEAN_C,cv.THRESH_BINARY,25,10)

    cv.imshow("local_threshold",dst)

可以有效的获得目标物体的轮廓

4.均值二值化


def custom_threshold(image):

    gray = cv.cvtColor(image,cv.COLOR_BGR2GRAY)

    h, w = gray.shape[:2]

    m = np.reshape(gray,[1,w+h])

    mean = m.sum()/(w+h)

    print("mean:",mean)

    ret, binary = cv.threshold(gray,mean,255,cv.THRESH_BINARY) 

    cv.imshow("custom_threshold",binary)

5.超大图像二值化

你可能感兴趣的:(语法基础)