OpenCV+Python 图像模糊

高斯模糊

高斯模糊本质上是低通滤波器,输出图像的每个像素点是原图像上对应像素点与周围像素点的加权。

高斯分布权重矩阵,就是对二维正态分布的密度函数(也就是高斯函数)采样再做归一化的产物。

使用opencv做高斯模糊,调用GaussianBlur函数,给出高斯矩阵的尺寸和标准差即可:

blur = cv2.GaussianBlur(img,(5,5),0)

其中,(5, 5)表示高斯矩阵的长与宽都是5,标准差取0时OpenCV会根据高斯矩阵的尺寸自己计算。通常,高斯矩阵的尺寸越大,标准差越大,处理过的图像模糊程度越大。

def img_blur(path):
    files = os.listdir(path)
    count = 0
    for file in files:
        count += 1
        imgs = os.listdir(os.path.join(path,file))
        for img in imgs:
            filename = os.path.basename(os.path.join(path,file,img))
            img = cv2.imread(os.path.join(path,file,img))
            dst = cv2.GaussianBlur(img,(5,5),0)
            cv2.imwrite(os.path.join(path,file,filename),dst)
        print(count)
    print('Done')

运动模糊

由于相机和物体之间的相对运动造成的模糊,又称为动态模糊。

使用opencv实现运动模糊,主要用到的函数是cv2.filter2D()。

def motion_blur(path,degree=12,angle=45):
    files = os.listdir(path)
    count = 0
    for file in files:
        count += 1
        imgs = os.listdir(os.path.join(path,file))
        for img in imgs:
            filename = os.path.basename(os.path.join(path,file,img))
            img = cv2.imread(os.path.join(path,file,img))
            img = np.array(img)
            
            #生成任意角度的运动模糊kernel的矩阵, degree越大,模糊程度越高
            M = cv2.getRotationMatrix2D((degree/2, degree/2), angle, 1)
            motion_blur_kernel = np.diag(np.ones(degree))
            motion_blur_kernel = cv2.warpAffine(motion_blur_kernel,M,(degree,degree))
            
            motion_blur_kernel = motion_blur_kernel / degree
            blurred = cv2.filter2D(img,-1,motion_blur_kernel)
            cv2.normalize(blurred,blurred,0,255,cv2.NORM_MINMAX)
            blurred = np.array(blurred,dtype=np.uint8)
            cv2.imwrite(os.path.join(path,file,filename),blurred)
        print(count)
print('Done')

resize模糊

使用opencv中resize()实现图像下采样、上采样,可以使图像模糊。

def img_down_up(path):
    files = os.listdir(path)
    for file in files:
        imgs = os.listdir(os.path.join(path,file))
        for img in imgs:
            filename = os.path.basename(os.path.join(path,file,img))
            img = cv2.imread(os.path.join(path,file,img))
            down_img = cv2.resize(img,(64,64),interpolation=cv2.INTER_CUBIC)
            up_img = cv2.resize(down_img,(128,128),interpolation=cv2.INTER_CUBIC)
            cv2.imwrite(os.path.join(path,file,filename),up_img)
    print('Done')
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值