## Python OpenCV image blur operation blur and mediablur

Dream eraser 2021-01-21 10:37:32
python opencv image blur operation

Python OpenCV 365 Day study plan , Go into the field of image with the eraser .

## Basic knowledge

Python OpenCV The principle of fuzzy operation in is ：

Based on discrete convolution 、 Define each convolution kernel 、 Different convolution kernels get different convolution effects 、 Fuzziness is a representation of convolution . The eraser says I don't understand , Just have a general impression in your mind , After all, it's learning 20 Many days .

1. The mean of fuzzy ： It is generally used to deal with the random noise of the image ;
2. The median fuzzy ： Generally used to deal with the salt and pepper noise of the image ;
3. Custom blur ： Enhance the image , Sharpening and other operations .

## Function prototype Introduction

### The mean of fuzzy

Concept ：

Mean filtering is a typical linear filtering algorithm , It means to give a template to the target pixel on the image , The template includes neighboring pixels around it （ Around the target pixel 8 Pixel , Form a filter template , That is, remove the target pixel itself ）, Then the average value of all pixels in the template is used to replace the original pixel value .

wow , Do not understand , Take a look at the prototype , First use it. , In the second round theory .

``````cv2.blur(src, ksize[, dst[, anchor[, borderType]]]) -> dst
``````

Parameter description ：

• src： The image to be processed , Be familiar with the parameters ;
• ksize： Represents the size of the fuzzy kernel . such as (5,5) Indicates that the generated fuzzy kernel is a 5*5 Matrix ;
• dst： Represents the output and src Images of the same size and type ;
• anchor： Optional parameters
• borderType： Optional parameters

The test code is as follows ：

``````import cv2 as cv
import numpy as np
def blur_demo(src):
dst = cv.blur(src, (5, 5))
cv.imshow("blur_demo", dst)
if __name__ == "__main__":
blur_demo(src)
cv.waitKey()
cv.destroyAllWindows()
``````

### The median fuzzy

Concept （ Just read it ）：

Median filtering is a nonlinear smoothing technique , It sets the gray value of each pixel point to the middle value of the gray value of all pixels in a neighborhood window of that point .

The function prototype is as follows ：

``````cv2.medianBlur(src, ksize[, dst]) -> dst
``````

Parameter description ：

• src： The input image to be processed ;
• ksize： The parameter represents the size of the filter window , It must be odd and greater than 1. For example, here is 5, The median filter will use 5×5 To calculate , That is, the center value of the pixel and its 5×5 Neighborhoods make up a numerical set , It is processed and calculated , The current pixel is replaced by its value ;
• dst： The parameter represents the output and src Images of the same size and type .

Median blur is generally used in images with some noise points , For example, white noise , Can be removed .

First, create a salt and pepper picture with the following code .

``````import numpy as np
import random
import cv2
def sp_noise(image, 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
# Add salt and pepper noise , Noise ratio 0.02
out = sp_noise(img, prob=0.02)
cv2.imshow("img", out)
cv2.waitKey()
``````

The image generated by the above code is subject to median blur operation .

``````# The median fuzzy , Salt and pepper noise
def median_blur_demo(src):
dst = cv.medianBlur(src, 3)
cv.imshow("dst", dst)
``````

### 2D Convolution ( Image filtering ), Custom blur

Concept ：

Image as a one-dimensional signal , It can also pass through a variety of low-pass filters (low-pass filters, LPF) And high pass filters (high-pass filters, HPF) To filter . Low pass filters can remove noise , Or blur the image . High pass filters can help find boundaries in an image .

The function prototype is ：

``````cv2.filter2D(src, ddepth, kernel[, dst[, anchor[, delta[, borderType]]]]) -> dst
``````

Parameter description ：

• src： The input image to be processed ;
• ddepth： Represents the depth of the target image , The input value is -1 when , The depth of the target image is consistent with that of the original image ;
• kernel:： Convolution kernel （ Or related nuclei ）, A single channel floating point matrix . modify kernel The matrix can realize different fuzziness ;
• anchor： Optional parameters , The anchor of the kernel , Indicates the relative position of the filter points in the kernel ; The anchor should be in the kernel ; The default value is （-1,-1） Indicates that the anchor is in the center of the kernel ;
• detal ： Optional parameters , Store them in dst Before , Add optional values to the filtered pixels . It's like bias ;
• borderType： Optional parameters , Pixel extrapolation

The test code is as follows ：

``````# Fuzzy operation
def filter2D_demo(src):
# Divide 25 It's about preventing spillage
kernel = np.ones([5,5],np.float32)/25
dst = cv.filter2D(src,-1,kernel=kernel)
cv.imshow("dst",dst)
``````

Running effect ：

Use `filter2D` function , Sharpen .

``````def filter2D_demo(src):
# When kernel Sum to 1 when ： Enhance sharpening
# When kernel Sum to 0 when ： Edge gradient
kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]], np.float32)
dst = cv.filter2D(src, -1, kernel=kernel)
cv.imshow("dst", dst)
``````

Note that in the above code `kernel` In the corresponding array , Each value is odd , The sum must be equal to 1, It's sharpening .

## Eraser bars

This series of blogs is for the journey of learning , Some of the concepts I didn't learn , Or you have to master it thoroughly , No extended learning . Keep it up every day 1 An hour's study time is enough .

1 Two hours later , Yes Python OpenCV Related knowledge , Have you got it ？

As a beginner , There are still many places where learning is not in-depth , I hope you will stick with me .

In my spare time , You can subscribe to the 100 cases of crawler course of eraser to learn the knowledge of crawler .

` Want to learn Python Reptiles , You can subscribe to the eraser column ~` Click to find the surprise

Today is the first day of continuous writing 60 / 100 God .
If you want to build a close relationship with a blogger , You can follow bloggers , Or focus on Blogger official account “` Non undergraduate programmer `”, Learn how a non undergraduate programmer grows up .
Blogger ID：` Dream eraser `, I hope you like 、 Comment on 、 Collection