均值平滑

#均值平滑
#先积分,上,左边界补0,省去判断边界的问题
import numpy as np
from scipy import signal
import cv2
def integral(image):
    rows,cols = image.shape
    #行积分运算
    inteImagec = np.zeros((rows,cols),np.float32)
    for r in range(rows):
        for c in range(cols):
            if c == 0:
                inteImagec[r][c] = image[r][c]
            else:
                inteImagec[r][c] = inteImagec[r][c-1]+image[r][c]
    #列积分运算
    inteImage = np.zeros(image.shape,np.float32)
    for c in range(cols):
        for r in range(rows):
            if r == 0:
                inteImage[r][c] = inteImagec[r][c]
            else:
                inteImage[r][c] = inteImage[r-1][c]+inteImagec[r][c]
    #上边左边补0
    inteImage_0 = np.zeros((rows+1,cols+1),np.float32)
    inteImage_0[1:rows+1,1:cols+1] = inteImage
    return inteImage_0
def fastMeanBlur(image,winSize,borderType = cv2.BORDER_DEFAULT):
    halfH = (winSize[0] - 1)/2
    halfW = (winSize[1] - 1)/2
    ratio = 1.0/(winSize[0]*winSize[1])
    #边界扩充
    paddImage = cv2.copyMakeBorder(image,halfH,halfH,halfW,halfW,borderType)
    #图像积分
    paddIntegral = integral(paddImage)
    #图像的高、宽
    rows,cols = image.shape
    #均值滤波后的结果
    meanBlurImage = np.zeros(image.shape,np.float32)
    r,c = 0,0
    for h in range(halfH,halfH+rows,1):
        for w in range(halfW,halfW+cols,1):
            meanBlurImage[r][c]=(paddIntegral[h+halfH+1][w+halfW+1]+paddIntegral[h-halfH][w-halfW]-
                    paddIntegral[h+halfH+1][w-halfW]-paddIntegral[h-halfH][w+halfW+1])*ratio
            c+=1
        r+=1
        c=0
    return meanBlurImage

需要astype(numpy.uint8)
opencv提供积分函数integral()
integral()
opencv提供快速均值平滑boxFilter和blur两个函数
boxFilter和blur添加链接描述

猜你喜欢

转载自blog.csdn.net/qq_41950131/article/details/94742858