图片中添加噪声

高斯噪声

img_ = cv2.GaussianBlur(img, ksize=(9, 9), sigmaX=0, sigmaY=0)

椒盐噪声

添加噪声
import numpy as np
import cv2
def cv_show(name,img):
    cv2.imshow(name,img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
def add_sp_noise(img,sp_number):
    new_image=img
    row,col,channel=img.shape#获取行列,通道信息
    s=int(sp_number*img.size/channel)#根据sp_number确定椒盐噪声
    #确定要扫椒盐的像素值
    change=np.concatenate((np.random.randint(0,row,size=(s,1)),np.random.randint(0,col,size=(s,1))),axis=1)
    for i in range(s):
        r=np.random.randint(0,2)#确定撒椒(0)还是盐(1)
        for j in range(channel):
            new_image[change[i,0],change[i,1],j]=r
    return new_image
def salt_pepper_noise(image, prob):
    """
    添加椒盐噪声
    :param image: 输入图像
    :param prob: 噪声比
    :return: 带有椒盐噪声的图像
    """
    salt = np.zeros(image.shape, np.uint8)
    thres = 1 - prob
    for i in range(image.shape[0]):
        for j in range(image.shape[1]):
            rdn = np.random.rand()
            if rdn < prob:
                salt[i][j] = 0
            elif rdn > thres:
                salt[i][j] = 255
            else:
                salt[i][j] = image[i][j]
    return salt
测试
im=add_sp_noise(im,0.05)
im2=add_sp_noise(im2,0.1)
im3=add_sp_noise(im3,0.3)

运动模糊

def motion_blur(image, degree=12, angle=45):
  image = np.array(image)
  # 这里生成任意角度的运动模糊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(image, -1, motion_blur_kernel)
  # convert to uint8
  cv2.normalize(blurred, blurred, 0, 255, cv2.NORM_MINMAX)
  blurred = np.array(blurred, dtype=np.uint8)
  return blurred
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值