Python tries to do the Gaussian blur of the image under the algorithm

Source: Internet
Author: User

What is Gaussian blur?

(Take a look at Wikipedia's definition of it)

Gaussian Blur is the result of a blurred image. It is a widely used graphic software effect that typically reduces image noise and reduces detail. The visual effect of this blur technique is a smooth blur similar to the effect of viewing a picture through a translucent screen, from distinctly different bokeh in the usual illumination of the focus lens or the shadow of the object. Gaussian smoothing is also used as a preprocessing stage of computer vision algorithm to improve the structure of the image at different scales to see the scale of space representation and scale space implementation.

Mathematically, applying a Gaussian blur image is the same as convolution an image of a Gaussian function. This is also referred to as a two-dimensional-dimensional Tesla transformation. By contrast, the cyclic convolution can more accurately reproduce the bokeh effect from Fourier transform one gauss is another Gauss, the application of Gaussian blur has the effect of reducing the high frequency component of the image; Gaussian Blur is a low-pass filter.

Application of Gaussian Blur
    • In the background design of the program, we always want to use some pictures to beautify the program, but directly with the image will be found with the word, the control is not very harmonious, this time, in the place we need or the entire background of the appropriate Gaussian blur, we can improve the value of our program.
    • Gaussian blur is also used for edge detection, which is used to smooth the image to remove details. and apply to picture noise reduction.
Results of Gaussian blur (example)

Here I will take the class icon of the 102 lab in our Blog park and use PS Gaussian blur to give an example. (The actual operation of the later also took it to give examples)

Gaussian Fuzzy noun interpretation

Gaussian blur applies the normal distribution to the aspect of image processing. " Gaussian blur "algorithm, is a data smoothing technology, suitable for a lot of occasions and scenarios, but here, image processing is a very intuitive application example.

Gaussian fuzzy process and data smoothing technology

The essence of fuzziness is actually the average value of the pixels in each picture. As shown in:

Figure one (original pixel) Figure II (smoothing)

The value of the point at the center takes the average value of all nearby points, and it becomes the value 1. This can be seen as a smoothing in numerical values. Then in the two-dimensional image can also be seen as a "fuzzy" effect, the center point loses its own pixel value, Equivalent to the loss of detail. The blur of the image is entirely dependent on the blur radius of the image. From the point of view of the value, the values tend to be smoother.

Summarize:

The core of Gaussian Blur is to take the mean value of all the pixels around the center point as its own pixel value, in order to achieve the smoothing effect, in the algorithm, involves a lot of problems, from these problems are also affecting the Gaussian fuzzy speed (fuzzy efficiency) Important factors

Time required for Gaussian Blur

Due to the calculation of all points, Gaussian Blur is a relatively time-consuming role, and the need for ambiguity is a lot of times, such as the algorithm, as well as the properties of the picture itself, as well as human requirements, machine performance is affecting the Gaussian blur time.
The two factors which influence the time of Gaussian Blur are as follows:

    • Blur radius
    • Number of pixel points (picture size)

Pixel point (image) This factor is well understood, the larger the picture means that the more points are calculated, and the fuzzy radius can be broadly understood such as:

Figure I (r=1) Figure II (r=2)

We can see that the radius of the figure one is 1, the center point refers to only the surrounding 8 squares of the pixel values, and the figure of the two radius of 2 to refer to the pixel value of 24 squares, and so on can be obtained: (where n is the radius)

Pixel point calculation Formula two times function image

Growth rate is increasing (online to see some said that the number of pixels to deal with is an exponential rise, for this problem may I understand is not very in place, but the conclusion is the larger the radius of the more processing points, good time is more.)
In summary: The fuzzy radius and the size of the image is the biggest factor affecting the Gaussian blur speed, and the general procedure requires the Gaussian blur speed in the MS class (like PS almost imperceptible time, is the importance of the algorithm), otherwise it will affect the user experience. Here we will do some experiment in this article.

Gaussian Blur formula and understanding

First, Gaussian blur requires a normal distribution formula in the mathematical probability, which is also the origin of the Gaussian fuzzy name, because the alias of the normal distribution is "Gaussian distribution".

    • Normal
      Formula (one-dimensional) images and parameter meanings:

The normal distribution image is as follows:

    • Two parameters of a normal distribution:

That is, the mean μ. &. The standard deviation σ,σ^2 is the variance

The relationship between image & Normal distribution:

As we all know, the image is two-dimensional, and the upper normal distribution is one-dimensional, this time we first introduce a one-dimensional Gaussian function:

Derivation process (Baidu Encyclopedia):

Ivigos Distribution Image:

(Pictures from Baidu Pictures)

Ivigos function

N Gaussian formula for the function:

In the parameters, R is the fuzzy radius, and in the two-dimensional coordinate system, the fuzzy radius is the standard deviation of the normal distribution, so we can get the two-dimensional Gaussian function formula in the X^2+y^2,σ equation, as follows:

The High line of the surface generated by the Ivigos function formula is a concentric circle that starts with a normal distribution radially from the center. A matrix of non-zero pixels (convolution) is transformed in the original image matrix pixel, and each pixel value is a weighted average of the pixel values of the adjacent circle.

weights Matrix and example of Gaussian function
    • We have to calculate the weight matrix first (so we have to get the coordinates of the matrix first, we are here to set the coordinates of the lattice in the middle point to the (0,0) origin).

    • We want to calculate the weight matrix of the image by Gauss function (we define a radius of 1)

    • Since we're going to make all the data of this matrix and 1, so we're going to figure out the data and

    • By dividing the nine-digit data in the matrix by the sum of all the data, the final weight matrix is obtained, and the final result is as follows:

    • We have obtained the weight matrix, it can be used to calculate the gray value of each pixel or RGB three-channel value.
Calculation of gray scale matrix of gray image
    • Suppose we arbitrarily create a matrix of any gray value (0-255)

    • Now the new matrix is calculated simply by multiplying the pixel of each point by its corresponding weight value, such as:

    • The final step: adding the values of these nine points is the Gaussian blur value of the center point, and then the Gaussian blur image can be obtained by repeating this process for all points. as follows:

Extended to color images

If the original picture is a color image, then the RGB three channels of color images can be Gaussian blur, so that the color image will be Gaussian blurred image.

code Example
#The relevant code for the Gaussian blur method explained above-xlxw fromPILImportImage as PImportNumPy as NP fromTimeImportClockImportMath#DefineSizepic =[0,0]timer=[0,0,0,0]pi= 3.1415926defgetRGB (PATH):#get RGB Three-channel values for each point pixel in the imagetimer[0]=clock () PD=p.open (path) sizepic[0]=Pd.size[0] sizepic[1] = pd.size[1] Nr= Np.empty ((sizepic[0],sizepic[1]) ng= Np.empty ((sizepic[0],sizepic[1]) NB= Np.empty ((sizepic[0],sizepic[1]))     forIinchRange (0,sizepic[0]): forJinchRange (0,sizepic[1]): Nr[i][j]=Pd.getpixel ((i,j)) [0] ng[i][j]= Pd.getpixel ((i,j)) [1] Nb[i][j]= Pd.getpixel ((i,j)) [2]    Print("The r,g,b value of all pixels has been obtained, taking the time {:. 3f}s". Format (Clock ()-timer[0])) returnNR,NG,NBdefMatrixmaker (R):#calculate the Gaussian function matrix by radius and coordinatesSummat =0 timer[1] =clock () Ma= Np.empty ((2*r+1,2*r+1))     forIinchRange (0,2*r+1):         forJinchRange (0,2*r+1): Gaussp= (1/(2*pi* (R**2))) * math.e** (-((I-r) **2+ (j-r) **2)/(r**2)) ) Ma[i][j]=GAUSSP Summat+=GAUSSPPrint(MA)Print(Summat) forIinchRange (0,2*r+1):         forJinchRange (0,2*r+1): Ma[i][j]= ma[i][j]/SummatPrint("The Gaussian function matrix has been computed and takes the time {:. 3f}s". Format (Clock ()-timer[1]))    Print("The matrix is as follows:")    returnMadefNewrgb (MA,NR,NG,NB,R):#generate a new pixel RGB matrixTIMER[2] =clock () NEWR= Np.empty ((sizepic[0],sizepic[1])) NEWG= Np.empty ((sizepic[0],sizepic[1])) Newb= Np.empty ((sizepic[0],sizepic[1]))     forIinchRange (r+1,sizepic[0]-r): forJinchRange (r+1,sizepic[1]-r): o=0 forXinchRange (i-r,i+r+1): P=0 forYinchRange (j-r,j+r+1):                    #print ("x{},y{},o{},p{}". Format (x,y,o,p))NEWR[I][J] + = nr[x][y]*Ma[o][p] Newg[i][j]+ = ng[x][y]*Ma[o][p] Newb[i][j]+ = nb[x][y]*Ma[o][p] P+ = 1o+ = 1Print("A new three-channel matrix has been calculated, taking the time {:. 3f}s". Format (timer[2]))    returnNEWR,NEWG,NEWBdefcpic (R,G,B,PATH,RD): timer[3] =clock () PD=p.open (path) forIinchRange (rd+1,sizepic[0]-rd+1):         forJinchRange (rd+1,sizepic[1]-rd+1): Pd.putpixel ((I,J), (int (r[i][j]), int (g[i][j]), int (b[i][j] ))Print("The build has been completed and takes the time {:. 3f}s". Format (timer[3]))    Print("Exporting Picture ...") Pd.save ("blurred.jpg")    defMain (): Rd= eval (Input ("Please enter the radius of the blur:")) path= Input ("Please enter the address of the picture (including suffix):") NR,NG,NB=getRGB (path) mATX=Matrixmaker (RD)Print(MATX)Print("Converting:") Newr,newg,newb=Newrgb (MATX,NR,NG,NB,RD)Print("Preparing output :") cpic (NEWR,NEWG,NEWB,PATH,RD)Print("{}->> {}". Format (Path.split ('/') [-1],"Blurred.png"))    Print("Total time: {:. 3f}s, thank you for your use.". Format (timer[0]+timer[1]+timer[2]+timer[3])) Main ()

The program runs:

Results of program operation

(Bt.png is the blog Park 102 Lab icon Gaussian Blur) This test has a fuzzy radius of 3

The Disadvantage & optimization scheme of Gaussian Blur

There are several drawbacks to Gaussian blur of a picture in this way:

    • First: The whole process of Gaussian blur from the previous chapter of the program spent a total of 2.82s, although this time is because in order to show the Gaussian blur process is not optimized, but with our above mentioned in the 200ms difference is very far, here is because some areas need to improve.
    • Second: This fuzzy approach can not effectively solve the problem of marginalization, so when the fuzzy radius is too large, there will be a clear dividing line, which is also needed to improve the place

Optimization scenarios:

    • 1. In terms of speed, mainly used to improve the algorithm, but we can also consider from the image angle, because the image is blurred after the loss of detail, this time and we directly to the image scaling has similarities, so if we reduce the image half, in the blur, then the method to the original, We will find that the blurred effect of the image is not much different from the direct blur. We can use this method to optimize this time.
    • 2. In addition to the speed, we can find that the solid color blur is not changed, then we can find a large block of solid color area of the blur when skipping them, this can also be optimized for time.
    • 3. Optimization algorithm. (using the calculation of one pixel point weight can simplify the product of two one Gaussian integral), this is an optimization scheme given in the foreign forum. and so on.

Python tries to do the Gaussian blur of the image under the algorithm

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.