日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

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

系統(tǒng) 2009 0

在matlab中,存在執(zhí)行直接得函數(shù)來添加高斯噪聲和椒鹽噪聲。Python-OpenCV中雖然不存在直接得函數(shù),但是很容易使用相關的函數(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


          

可見,只要我們得到滿足某個分布的多維數(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#

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。


更多文章、技術交流、商務合作、聯(lián)系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號聯(lián)系: 360901061

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對您有幫助就好】

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦!!!

發(fā)表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 施秉县| 驻马店市| 轮台县| 拜泉县| 余姚市| 休宁县| 安新县| 上饶县| 洪湖市| 介休市| 克拉玛依市| 沁水县| 油尖旺区| 昌黎县| 榆树市| 陆丰市| 玉溪市| 定南县| 靖宇县| 景泰县| 旬邑县| 恩施市| 肇东市| 红原县| 石棉县| 鄱阳县| 海口市| 远安县| 雷山县| 饶河县| 宜兰市| 噶尔县| 中牟县| 樟树市| 南丰县| 惠州市| 临夏市| 怀来县| 双辽市| 盐城市| 无极县|