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 .

This blog is about

  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__":
src = cv.imread("./1.jpg")
blur_demo(src)
cv.waitKey()
cv.destroyAllWindows()

Python OpenCV Image blur operation blur And medianBlur

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
img = cv2.imread("./1.jpg")
# Add salt and pepper noise , Noise ratio 0.02
out = sp_noise(img, prob=0.02)
cv2.imshow("img", out)
cv2.waitKey()

Python OpenCV Image blur operation blur And medianBlur

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)

Python OpenCV Image blur operation blur And medianBlur

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 :
Python OpenCV Image blur operation blur And medianBlur
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 .
Python OpenCV Image blur operation blur And medianBlur

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 .

Recommended reading

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 have ideas you want to communicate 、 technology , Feel free to leave a comment in the comments section .


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

版权声明
本文为[Dream eraser]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/01/20210121103519008z.html

  1. Python批量 png转ico
  2. 使用line_profiler对python代码性能进行评估优化
  3. 使用line_profiler对python代码性能进行评估优化
  4. Getting started with Python 3 flash in win environment
  5. Common ways to write configuration files in Python
  6. Python会在2021年死去吗? Python 3.9最终版本的回顾
  7. Python batch PNG to ICO
  8. Using line_ Profiler evaluates and optimizes the performance of Python code
  9. Using line_ Profiler evaluates and optimizes the performance of Python code
  10. Will Python die in 2021? A review of the final version of Python 3.9
  11. Python3 SMTP send mail
  12. Understanding closures in Python: getting started with closures
  13. Python日志实践
  14. Python logging practice
  15. [python opencv 计算机视觉零基础到实战] 十、图片效果毛玻璃
  16. [python opencv 计算机视觉零基础到实战] 九、模糊
  17. 10. Picture effect ground glass
  18. [Python opencv computer vision zero basis to actual combat] 9. Fuzzy
  19. 使用line_profiler對python程式碼效能進行評估優化
  20. Using line_ Profiler to evaluate and optimize the performance of Python code
  21. LeetCode | 0508. 出现次数最多的子树元素和【Python】
  22. Leetcode | 0508
  23. LeetCode | 0530. 二叉搜索树的最小绝对差【Python】
  24. LeetCode | 0515. 在每个树行中找最大值【Python】
  25. Leetcode | 0530. Minimum absolute difference of binary search tree [Python]
  26. Leetcode | 0515. Find the maximum value in each tree row [Python]
  27. 我来记笔记啦-搭建python虚拟环境
  28. Let me take notes - building a python virtual environment
  29. LeetCode | 0513. 找树左下角的值【Python】
  30. Leetcode | 0513. Find the value in the lower left corner of the tree [Python]
  31. Python OpenCV 泛洪填充,取经之旅第 21 天
  32. Python opencv flood fill, day 21
  33. Python爬虫自学系列(二)
  34. Python crawler self study series (2)
  35. 【python】身份证号码有效性检验
  36. [Python] validity test of ID number
  37. Python ORM - pymysql&sqlalchemy
  38. Python ORM - pymysql&sqlalchemy
  39. centos7 安装python3.8
  40. centos7 安装python3.8
  41. Centos7 installing Python 3.8
  42. Centos7 installing Python 3.8
  43. Django——图书管理系统(六)
  44. Django——图书管理系统(五)
  45. Django -- library management system (6)
  46. Django -- library management system (5)
  47. python批量插入数据小脚本
  48. Python batch insert data script
  49. ZoomEye-python 使用指南
  50. Zoomeye Python User's Guide
  51. 用Python写代码,一分钟搞定一天工作量,同事直呼:好家伙 - 知乎
  52. Using Python to write code, one minute to complete a day's workload, colleagues call: good guy - Zhihu
  53. Python 上的可视化库——PyG2Plot
  54. Pyg2plot: a visualization library on Python
  55. Python 上的可视化库——PyG2Plot
  56. Python实用代码-无限级分类树状结构生成算法
  57. Pyg2plot: a visualization library on Python
  58. Python utility code - infinite classification tree structure generation algorithm
  59. 奇技淫巧,还是正统功夫?Python推导式最全用法
  60. Pandas 的这个知识点,估计 80% 的人都得挂!