图像阈值化处理

#Author C
import cv2
import os
#腐蚀
# kernel=np.ones((5,5),np.uint8)
# erosion=cv2.erode(img,kernel,iterations=1)
list=[]
for filename in os.listdir(r"C:\Users\Uaena\Desktop\crack"):
route=r"C:\Users\Uaena\Desktop\crack\\"+filename
list.append(route)
# print(list)
for i in range(len(list)):
img=cv2.imread(list[i])

img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)#转换为灰度图像
blurred=cv2.GaussianBlur(img,(5,5),0)#高斯滤波 https://baike.so.com/doc/1781738-1884180.html
# print(blurred)

(T,thresh)=cv2.threshold(blurred,11,100,cv2.THRESH_BINARY )#二值化处理,阈值为11,低于阈值的像素点灰度值置为0;高于阈值的值置为参数3
#(T, thresh)=cv2.threshold(blurred,11,100,cv2.THRESH_TRUNC)#小于阈值的像素点灰度值不变,大于阈值的像素点置为0
(T, threshInv) = cv2.threshold(blurred, 10, 100, cv2.THRESH_BINARY_INV)#反阈值化,大于阈值的像素点灰度值置为0,小于阈值的值置为参数3
    #小于阈值的像素点灰度值不变,大于阈值的像素点置为0,其中参数3任取
    ret,thresh4 = cv2.threshold(grayImage,127,255,cv2.THRESH_TOZERO)
    cv2.imshow('BINARY_TOZERO',thresh4)


    #大于阈值的像素点灰度值不变,小于阈值的像素点置为0,其中参数3任取
    ret,thresh5 = cv2.threshold(grayImage,127,255,cv2.THRESH_TOZERO_INV)
    cv2.imshow('BINARY_TOZERO_INV',thresh5)

cv2.imwrite(r"C:\Users\Uaena\Desktop\output\%s.jpg"%(i),threshInv)
# cv2.imshow("3",threshInv)
posted @ 2018-07-21 20:29  mrc736  阅读(284)  评论(0编辑  收藏  举报