使用Python-OpenCV向圖片添加噪聲的實現(xiàn)(高斯噪聲、椒鹽噪聲)
在matlab中,存在執(zhí)行直接得函數(shù)來添加高斯噪聲和椒鹽噪聲。Python-OpenCV中雖然不存在直接得函數(shù),但是很容易使用相關(guān)的函數(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
參考鏈接:
2、https://stackoverflow.com/questions/14435632/impulse-gaussian-and-salt-and-pepper-noise-with-opencv#
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python通用數(shù)據(jù)庫操作工具 pydbclib的使用簡介
這篇文章主要介紹了python通用數(shù)據(jù)庫操作工具 pydbclib的使用簡介,幫助大家更好的理解和使用python,感興趣的朋友可以了解下2020-12-12Python實現(xiàn)在Linux系統(tǒng)下更改當前進程運行用戶
這篇文章主要介紹了Python實現(xiàn)在Linux系統(tǒng)下更改當前進程運行用戶,本文直接給出實現(xiàn)代碼,需要的朋友可以參考下2015-02-02Python獲取和設(shè)置代理的動態(tài)IP的方式
在網(wǎng)絡(luò)世界中,代理和動態(tài)IP是非常常見的概念,尤其對于需要大規(guī)模訪問網(wǎng)站或者需要隱藏真實IP地址的應用程序來說,更是必不可少的工具,本文將給大家介紹如何使用編程技術(shù)來實現(xiàn)動態(tài)IP的設(shè)置和管理,需要的朋友可以參考下2024-05-05Python+selenium 自動化快手短視頻發(fā)布的實現(xiàn)過程
這篇文章主要介紹了Python+selenium 自動化快手短視頻發(fā)布,通過調(diào)用已啟用的瀏覽器,可以實現(xiàn)直接跳過每次的登錄過程,上傳功能的使用方法通過代碼給大家介紹的也非常詳細,需要的朋友可以參考下2021-10-10python中copy()與deepcopy()的區(qū)別小結(jié)
接觸python有一段時間了,一直沒有系統(tǒng)的學習過,也對copy,deepcoy傻傻的分不清,故抽出時間來理一下。 下面這篇文章主要給大家介紹了關(guān)于python中copy()與deepcopy()的區(qū)別的相關(guān)資料,需要的朋友可以參考下2018-08-08pytest解讀fixture有效性及跨文件共享fixtures
這篇文章主要為大家介紹了pytest官方文檔fixture有效性及跨文件共享fixtures的解讀,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-06-06對python3 Serial 串口助手的接收讀取數(shù)據(jù)方法詳解
今天小編就為大家分享一篇對python3 Serial 串口助手的接收讀取數(shù)據(jù)方法詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-06-06