第十一天 二值化

注:二值化 cv.threshold类型参考地址

https://blog.csdn.net/u012566751/article/details/77046445

import cv2 as cv
import numpy as np

def custom_threshold(image):
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
    ret, binary = cv.threshold(gray, 127,255, cv.THRESH_BINARY)      #整体二值化大于127是黑色 小于127的是白色
    #ret, binary = cv.threshold(gray, 127, 255,cv.WINDOW_AUTOSIZE)      #小于127是黑色 大于127的是白色
    print ("ret%s"%ret)
    cv.imshow("binary",binary)


def local_threshold(image):
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
    binary = cv.adaptiveThreshold(gray, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 25, 10)   ##局部二值化高斯取出均值    像素块均值大10就是白色其它是黑色
    #ADAPTIVE_THRESH_MEAN_C的计算方法是计算出领域的平均值再减去第七个参数double
    #C的值

   #ADAPTIVE_THRESH_GAUSSIAN_C的计算方法是计算出领域的高斯均值再减去第七个参数double
   # C的值
    cv.imshow("binary", binary)

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)     #数组全部加和/w*h  q去平均值
    print("mean:",mean)
    ret,binary = cv.threshold(gray,mean,255,cv.THRESH_BINARY)
    cv.imshow("binary", binary)



print("--------- Python OpenCV Tutorial ---------")
src = cv.imread("C:/Users/weiqiangwen/Desktop/sest/data/lena.jpg")
# cv.namedWindow("input contours",cv.WINDOW_AUTOSIZE)
cv.imshow("contours", src)
#custom_threshold(src)
#local_threshold(src)
custom_threshold(src)
cv.waitKey(0)

cv.destroyAllWindows()

猜你喜欢

转载自blog.csdn.net/qq_32340685/article/details/83502965