OpenCV 4.阈值处理&图像平滑处理

4.阈值处理&图像平滑处理

#加载OpenCV
import cv2
import numpy as np
def imgShow(title,img):
    cv2.imshow(title,img)
    cv2.waitKey()
    cv2.destroyAllWindows()

#1.阈值处理 ret,dst = cv2.threshold(imgData,阈值,最大值,处理类型)  处理类型{thresh_binary:大于阈值取255,小于阈值取0,thresh_binary_inv:大于阈值取0,小于阈值取255,thresh_tozero:小于阈值取0,thresh_tozero_inv:大于阈值取0,thresh_trunc:大于阈值取阈值}


img = cv2.imread(r"C:\Users\Administrator\Pictures\Camera Roll\lenna.jpg") #读取
# img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# ret,dst = cv2.threshold(img,127,255,cv2.THRESH_BINARY) #大于阈值取255,小于阈值取0
# ret,dst = cv2.threshold(img,127,255,cv2.THRESH_BINARY_INV) #大于阈值取0,小于阈值取255
# ret,dst = cv2.threshold(img,127,255,cv2.THRESH_TRUNC) #大于阈值取阈值
# ret,dst = cv2.threshold(img,127,255,cv2.THRESH_TOZERO) #小于阈值取0
# ret,dst = cv2.threshold(img,127,255,cv2.THRESH_TOZERO_INV) #大于阈值取0


# imgShow(r"lenna",dst)


#添加噪声
img_notice = np.random.normal(0,0.001**0.5,img.shape)
img_data = img.copy()
img_data = np.array(img_data/255, dtype=float)

img_data = img_data+img_notice
img_data = np.uint8(img_data*255)

#2.图像平滑处理 #均值滤波 #方框滤波  #高斯滤波  #中值滤波

#均值滤波  cv2.blur(imgData,(3,3))  3*3滤镜   (1+2+...+9)/9
imgAvg = cv2.blur(img_data,(3,3))
#方框滤波  cv2.boxFilter(imgData,-1,(3,3),normalize=True|False) 
imgBoxFilter1 = cv2.boxFilter(img,-1,(3,3),normalize=True)  #归一化
imgBoxFilter2 = cv2.boxFilter(img,-1,(3,3),normalize=False)  #未作归一化[未除以3*3]

#高斯滤波 cv2.GaussianBlur(imgData,(3,3),1) 距离中间的权重越高
glussian = cv2.GaussianBlur(img,(3,3),1)

#中值滤波  取中间值作为结果
media = cv2.medianBlur(img,5)

#合并展示  np.hstack((...)) 横向   np.vstack((...))纵向展示  
result = np.hstack((imgAvg,imgBoxFilter1,imgBoxFilter2,glussian,media))

imgShow(r"均值滤波>方框滤波1,2>高斯滤波>中值滤波",result)

你可能感兴趣的:(#,Python,视频图像处理,opencv,python)