当前位置:网站首页>[opencv learning] [image filtering]
[opencv learning] [image filtering]
2022-07-02 12:51:00 【A sea of stars】
The original image is :
One : Add noise to the image
import numpy as np
import random
import cv2
import matplotlib.pyplot as plt
# Show the image , Encapsulate as a function
def cv_show_image(name, img):
cv2.imshow(name, img)
cv2.waitKey(0) # Waiting time , In milliseconds ,0 Represents any key termination
cv2.destroyAllWindows()
def sp_noise(image,prob):
''' Add salt and pepper noise prob: Noise ratio '''
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() # Take random value every time , Judge whether the pixel at this position should be replaced by noise ?
if rdn < prob:
output[i][j] = 255 # The setting less than a certain threshold is 255, This is the highlight noise
# elif rdn > thres:
# output[i][j] = 255 # The setting greater than a certain threshold is 0, This is dark noise
else:
output[i][j] = image[i][j]
return output
def gasuss_noise(image, mean=0, var=0.001):
''' Add Gaussian noise mean : mean value var : variance '''
image = np.array(image/255.0, dtype=float) # Change the value of the image to 0 ~ 1
noise = np.random.normal(mean, var ** 0.5, image.shape) # Get a normal distribution of data ,shape The value is consistent with the image
out = image + noise # The sum of the two is the noise with image
# clip Function interpretation , Truncate the data ,a: Input matrix ;a_min: Limited minimum , All than a_min Small numbers are forced to a_min;
# a_max: The maximum value that is limited , All than a_max Large numbers are forced to a_max;
# out: You can specify the object of the output matrix ,shape And a identical
out = np.clip(out, 0, 1.0)
out = np.uint8(out*255) # The image value is restored to 0 ~ 255
return out
def normal_noise(img):
noise = np.zeros(img.shape, np.int8)
cv2.randn(noise, (0, 0, 0), (100, 100, 100)) # Image is (H, W, C), There are three channels , Set the mean and variance for each channel
img_noise = cv2.add(img, noise, dtype=cv2.CV_8UC3)
return img_noise
def uniform_noise(img):
noise = np.zeros(img.shape, np.int8)
cv2.randu(noise, (0, 0, 0), (100, 100, 100)) # Image is (H, W, C), There are three channels , Set the mean and variance for each channel
img_noise = cv2.add(img, noise, dtype=cv2.CV_8UC3)
return img_noise
img = cv2.imread('images/naruto.jpg') # Read the original image
cv_show_image('img_src', img)
# Increase noise
img_noise = sp_noise(img, 0.1) # Increase salt and pepper noise
cv_show_image('img_noise', img_noise)
# Increase noise
img_noise = gasuss_noise(img, 0, 0.1) # Increase the noise of normal distribution
cv_show_image('img_noise', img_noise)
# Increase noise
img_noise = normal_noise(img) # Increase the noise of normal distribution
cv_show_image('img_noise', img_noise)
# Increase noise
img_noise = uniform_noise(img) # Increase the noise of normal distribution
cv_show_image('img_noise', img_noise)
Take salt and pepper noise as an example 
Two : All kinds of filtering
The code accepts the above function
1: Mean filtering
# Do the filtering operation , Smoothing
# Mean filtering : # In the range of convolution kernel size around each pixel , Take the average value of all pixels in this range .
img = cv2.imread('images/naruto.jpg') # Read the original image
img_noise = sp_noise(img, 0.1) # Increase salt and pepper noise
cv_show_image('img_noise', img_noise)
blur = cv2.blur(img_noise, (3, 3))
cv_show_image('blur', blur)

2: Box filtering
# Do the filtering operation , Smoothing
# Box filtering : It is basically consistent with mean filtering , That is, you can choose whether there is normalization operation at last , Averaging is the operation of normalization
img = cv2.imread('images/naruto.jpg') # Read the original image
img_noise = sp_noise(img, 0.1) # Increase salt and pepper noise
cv_show_image('img_noise', img_noise)
boxblur = cv2.boxFilter(img_noise, -1, (3, 3), normalize=True) # -1 Represents the depth of the original image , namely src.depth().
cv_show_image('boxblur', boxblur)
boxblur = cv2.boxFilter(img_noise, -1, (3, 3), normalize=False) # -1 Represents the depth of the original image , namely src.depth().
cv_show_image('boxblur', boxblur)


3: Gauss filtering
# Do the filtering operation , Smoothing
# Gauss filtering : # In the range of convolution kernel size around each pixel , According to the characteristics of Gaussian distribution , The closer the distance, the greater the weight , If the distance is far, take the smaller weight .
# The above mean filtering and block filtering , The weight of each pixel is the same ,
# The Gaussian distribution is artificially closer to the core pixel , The closer the relationship , Pay more attention to . The farther away , The smaller the relationship , The less attention should be paid to .
img = cv2.imread('images/naruto.jpg') # Read the original image
img_noise = sp_noise(img, 0.1) # Increase salt and pepper noise
cv_show_image('img_noise', img_noise)
gauss_blur = cv2.GaussianBlur(img_noise, (3, 3), 1) # 1 yes sigmaX, Denotes that the Gaussian kernel function is in X The standard deviation of the direction
cv_show_image('gauss_blur', gauss_blur)

4: median filtering
# Do the filtering operation , Smoothing
# median filtering : # In the range of convolution kernel size around each pixel , Take the median value of all pixels in this range .
# In the mean filter , Because the noise component is put into the average calculation , So the output is affected by noise , But in median filter , Because the noise component is difficult to choose , So it hardly affects the output . So use the same 3x3 Area for processing , The ability of median filter to eliminate noise is better . Median filtering is a good method both in eliminating noise and preserving edges .
img = cv2.imread('images/naruto.jpg') # Read the original image
img_noise = sp_noise(img, 0.1) # Increase salt and pepper noise
cv_show_image('img_noise', img_noise)
med_blur = cv2.medianBlur(img_noise, 5) # 5 yes 5x5 The size of the nucleus means
cv_show_image('med_blur', med_blur)

5: Bilateral filtering
# Do the filtering operation , Smoothing
# Bilateral filtering (Bilateral filter) It's a nonlinear filtering method , It is a compromise processing that combines the spatial proximity of the image and the similarity of pixel values , At the same time, spatial information and gray similarity are considered , To achieve the purpose of edge preserving denoising . Simple 、 Non iterative 、 Local characteristics
img = cv2.imread('images/naruto.jpg') # Read the original image
img_noise = sp_noise(img, 0.1) # Increase salt and pepper noise
cv_show_image('img_noise', img_noise)
bi_blur = cv2.bilateralFilter(src=img_noise, d=0, sigmaColor=100, sigmaSpace=15)
cv_show_image('bi_blur', bi_blur)

边栏推荐
- 百款拿来就能用的网页特效,不来看看吗?
- Lekao.com: experience sharing of junior economists and previous candidates in customs clearance
- Mongodb redis differences
- Counting class DP acwing 900 Integer partition
- 架构师必须了解的 5 种最佳软件架构模式
- bellman-ford AcWing 853. Shortest path with side limit
- Redis transaction mechanism implementation process and principle, and use transaction mechanism to prevent inventory oversold
- Bom Dom
- Five best software architecture patterns that architects must understand
- js3day(数组操作,js冒泡排序,函数,调试窗口,作用域及作用域链,匿名函数,对象,Math对象)
猜你喜欢

线性DP AcWing 897. 最长公共子序列

Js7day (event object, event flow, event capture and bubble, prevent event flow, event delegation, student information table cases)

Interval DP acwing 282 Stone merging

Analog to digital converter (ADC) ade7913ariz is specially designed for three-phase energy metering applications
![1380. Lucky numbers in the matrix [two-dimensional array, matrix]](/img/8c/c050af5672268bc7e0df3250f7ff1d.jpg)
1380. Lucky numbers in the matrix [two-dimensional array, matrix]

Get started REPORT | today, talk about the microservice architecture currently used by Tencent

spfa AcWing 852. SPFA judgement negative ring

Openssh remote enumeration username vulnerability (cve-2018-15473)

深拷貝 事件總線

Js1day (input / output syntax, data type, data type conversion, VaR and let differences)
随机推荐
Analog to digital converter (ADC) ade7913ariz is specially designed for three-phase energy metering applications
腾讯三面:进程写文件过程中,进程崩溃了,文件数据会丢吗?
Lekao: 22 year first-class fire engineer "technical practice" knowledge points
浏览器存储方案
线性DP AcWing 896. 最长上升子序列 II
Fluent fluent library encapsulation
线性DP AcWing 895. 最长上升子序列
H5 to app
阿里发布的Redis开发文档,涵盖了所有的redis操作
深拷貝 事件總線
LTC3307AHV 符合EMI标准,降压转换器 QCA7005-AL33 PHY
计数类DP AcWing 900. 整数划分
Js1day (input / output syntax, data type, data type conversion, VaR and let differences)
ArrayList与LinkedList效率的对比
js1day(輸入輸出語法,數據類型,數據類型轉換,var和let區別)
浏览器node事件循环
Heap acwing 838 Heap sort
[ybtoj advanced training guide] similar string [string] [simulation]
传感器 ADXL335BCPZ-RL7 3轴 加速度计 符合 RoHS/WEEE
Js5day (event monitoring, function assignment to variables, callback function, environment object this, select all, invert selection cases, tab column cases)