原创

在OpenCV里实现均值平滑3

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://mysoft.blog.csdn.net/article/details/100896675

有了前面的积分图像之后,就可以采用下面的公式来快速地计算均值平滑:

这个公式就是前面计算面积的公式,因此可以把均值平滑的算法写成这样:

#python 3.7.4,opencv4.1
#蔡军生 https://blog.csdn.net/caimouse/article/details/51749579
#
import cv2
import numpy as np

#计算积分图像Integral(i,j) = Integral(i,j-1) + ColumnSum(j);
def integral(img,h,w):
    integ_graph = np.zeros((h+1,w+1),dtype = np.int32)
    for x in range(h):
        sum_clo = 0
        for y in range(w):
            sum_clo +=  img[x][y]
            #print('y={},{},sum={}'.format(y,img[x][y],sum_clo))
            integ_graph[x+1][y+1] = integ_graph[x][y+1] + sum_clo;
    return integ_graph

#均值平滑
def MeanBlur(image,WinSize):
    wH = (WinSize[0]-1)//2
    wW = (WinSize[1]-1)//2

    imagepad = cv2.copyMakeBorder(image,wH,wH,wW,wW, borderType = cv2.BORDER_DEFAULT)
    hp, wp = imagepad.shape[:2]
    imgIt = integral(imagepad, hp, wp)#积分图像

    h,w = image.shape[:2]
    out = np.zeros(image.shape, np.float32)
    r,c = 0,0
    for y in range(wH, wH+h, 1):
        for x in range(wW, wW+w, 1):
            out[r][c] = (imgIt[y+wH+1][x+wW+1] + imgIt[y-wH][x-wW] -
            imgIt[y+wH+1][x-wW] - imgIt[y-wH][x+wW+1])/(WinSize[0]*WinSize[1])
            c += 1
        r += 1
        c = 0
    return out


#图片的路径
imgname = "gauss1.jpg"

#读取图片
image = cv2.imread(imgname, cv2.IMREAD_GRAYSCALE)

#图片的高度和宽度
h,w = image.shape[:2]
print('imagesize={}-{}'.format(w,h))

#显示原图
cv2.imshow("Image",image)

#平滑
out = MeanBlur(image,(5,5))
out = out.astype(np.uint8)
cv2.imshow("out",out)


cv2.waitKey(0)
cv2.destroyAllWindows()

结果输出如下:

 

输入图片

输出图像

https://blog.csdn.net/caimouse/article/details/51749579

 

文章最后发布于: 2019-09-16 18:17:35
展开阅读全文
0 个人打赏
私信求帮助

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览