6.python opencv 中值滤波平滑--去噪点

 

import random
import cv2
import numpy as np
from datetime import datetime
 
import math
def printWithdate(str):
    time2 = datetime.now()
    time2a = time2.strftime("%Y-%m-%d %H:%M:%S")
    print(time2a+' '+str)
#python opencv均值平滑
   
#添加椒盐噪声 
def salt(image,number):
   #图像的高、宽
   rows,cols = image.shape
   #加入椒盐噪声后的图像
   saltImage = np.copy(image)
   for i in range (number):
      randR = random.randint(0,rows-1)
      randC = random.randint(0,cols -1)
      saltImage[randR][randC]=255
   return saltImage
def medianBlur(image,winSize):

   '''
   中值平滑,消除椒盐噪声
   '''
   rows,cols = image.shape
   winH,winW = winSize
   halfWinH = int((winH-1)/2)
   halfWinW = int((winW-1)/2)
   #中值滤波后的输出图像
   medianBlurImage= np.zeros(image.shape,image.dtype)
   for r in range(rows):
      for c in range(cols):
         #判断边界
         rTop = 0 if r-halfWinH<0 else r-halfWinH #满足条件:rTop=0, 否则rTop=r-halfWinH
         rBottom = rows-1 if r+halfWinH>rows-1 else int(r+halfWinH)
         cLeft =0 if c-halfWinW<0 else c-halfWinW
         cRight = cols-1 if c+halfWinW>cols-1 else int(c+halfWinW)
         #取邻域
         region = image[rTop:rBottom+1,cLeft:cRight+1]
         #求中值
         medianBlurImage[r][c] = np.median(region)
   return medianBlurImage


if __name__=="__main__":
    printWithdate("hello")
     
    try: #异常捕捉 ,python 捕捉 imread路径错误
       img = cv2.imread(r'dayan.png',cv2.IMREAD_GRAYSCALE) #不会抛出异常,返回none
    except FileNotFoundError:
       print('没有找到文件')
    except IOError as e:
       print('img read error')
    except Exception as e:
       print('未知错误 error')
    if img is None:
       print("img is None,程序结束")
      # quit() #程序直接退出不执行后续代码
    saltImg = salt(img,500)
    cv2.imshow('jiaoyan',saltImg)
    #cv2.waitKey(0)
    medianImg = medianBlur(img,(3,3))
    cv2.imshow("medianBlur",medianImg)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
   
    

 

posted @ 2024-03-29 16:43  txwtech  阅读(42)  评论(0编辑  收藏  举报