溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

使用Python-OpenCV向圖片添加噪聲的實(shí)現(xiàn)(高斯噪聲、椒鹽噪聲)

發(fā)布時(shí)間:2020-09-20 07:32:25 來(lái)源:腳本之家 閱讀:240 作者:Rogn 欄目:開發(fā)技術(shù)

在matlab中,存在執(zhí)行直接得函數(shù)來(lái)添加高斯噪聲和椒鹽噪聲。Python-OpenCV中雖然不存在直接得函數(shù),但是很容易使用相關(guān)的函數(shù)來(lái)實(shí)現(xiàn)。

代碼:

import numpy as np
import random
import cv2

def sp_noise(image,prob):
  '''
  添加椒鹽噪聲
  prob:噪聲比例 
  '''
  output = np.zeros(image.shape,np.uint8)
  thres = 1 - prob 
  for i in range(image.shape[0]):
    for j in range(image.shape[1]):
      rdn = random.random()
      if rdn < prob:
        output[i][j] = 0
      elif rdn > thres:
        output[i][j] = 255
      else:
        output[i][j] = image[i][j]
  return output


def gasuss_noise(image, mean=0, var=0.001):
  ''' 
    添加高斯噪聲
    mean : 均值 
    var : 方差
  '''
  image = np.array(image/255, dtype=float)
  noise = np.random.normal(mean, var ** 0.5, image.shape)
  out = image + noise
  if out.min() < 0:
    low_clip = -1.
  else:
    low_clip = 0.
  out = np.clip(out, low_clip, 1.0)
  out = np.uint8(out*255)
  #cv.imshow("gasuss", out)
  return out

可見,只要我們得到滿足某個(gè)分布的多維數(shù)組,就能作為噪聲添加到圖片中。

例如:

import cv2
import numpy as np

>>> im = np.empty((5,5), np.uint8) # needs preallocated input image
>>> im
array([[248, 168, 58,  2,  1], # uninitialized memory counts as random, too ? fun ;) 
    [ 0, 100,  2,  0, 101],
    [ 0,  0, 106,  2,  0],
    [131,  2,  0, 90,  3],
    [ 0, 100,  1,  0, 83]], dtype=uint8)
>>> im = np.zeros((5,5), np.uint8) # seriously now.
>>> im
array([[0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0]], dtype=uint8)
>>> cv2.randn(im,(0),(99))     # normal
array([[ 0, 76,  0, 129,  0],
    [ 0,  0,  0, 188, 27],
    [ 0, 152,  0,  0,  0],
    [ 0,  0, 134, 79,  0],
    [ 0, 181, 36, 128,  0]], dtype=uint8)
>>> cv2.randu(im,(0),(99))     # uniform
array([[19, 53, 2, 86, 82],
    [86, 73, 40, 64, 78],
    [34, 20, 62, 80, 7],
    [24, 92, 37, 60, 72],
    [40, 12, 27, 33, 18]], dtype=uint8)

然后再:

img = ...
noise = ...

image = img + noise

參考鏈接:

1、https://stackoverflow.com/questions/22937589/how-to-add-noise-gaussian-salt-and-pepper-etc-to-image-in-python-with-opencv#

2、https://stackoverflow.com/questions/14435632/impulse-gaussian-and-salt-and-pepper-noise-with-opencv#

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI