溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Java怎樣實(shí)現(xiàn)高斯模糊和圖像的空間卷積

發(fā)布時(shí)間:2021-11-24 14:09:06 來(lái)源:億速云 閱讀:224 作者:柒染 欄目:編程語(yǔ)言

這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)?lái)有關(guān)Java怎樣實(shí)現(xiàn)高斯模糊和圖像的空間卷積,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

高斯模糊

高斯模糊(英語(yǔ):Gaussian Blur),也叫高斯平滑,是在Adobe  Photoshop、GIMP以及Paint.NET等圖像處理軟件中廣泛使用的處理效果,通常用它來(lái)減少圖像雜訊以及降低細(xì)節(jié)層次。這種模糊技術(shù)生成的圖像,其視覺(jué)效果就像是經(jīng)過(guò)一個(gè)半透明屏幕在觀察圖像,這與鏡頭焦外成像效果散景以及普通照明陰影中的效果都明顯不同。高斯平滑也用于計(jì)算機(jī)視覺(jué)算法中的預(yù)先處理階段,以增強(qiáng)圖像在不同比例大小下的圖像效果。  從數(shù)學(xué)的角度來(lái)看,圖像的高斯模糊過(guò)程就是圖像與正態(tài)分布做卷積。由于正態(tài)分布又叫作高斯分布,所以這項(xiàng)技術(shù)就叫作高斯模糊。圖像與圓形方框模糊做卷積將會(huì)生成更加精確的焦外成像效果。由于高斯函數(shù)的傅立葉變換是另外一個(gè)高斯函數(shù),所以高斯模糊對(duì)于圖像來(lái)說(shuō)就是一個(gè)低通濾波器。

高斯模糊運(yùn)用了高斯的正態(tài)分布的密度函數(shù),計(jì)算圖像中每個(gè)像素的變換。

Java怎樣實(shí)現(xiàn)高斯模糊和圖像的空間卷積

根據(jù)一維高斯函數(shù),可以推導(dǎo)得到二維高斯函數(shù):

Java怎樣實(shí)現(xiàn)高斯模糊和圖像的空間卷積

Java怎樣實(shí)現(xiàn)高斯模糊和圖像的空間卷積

其中r是模糊半徑,r^2 = x^2 +  y^2,σ是正態(tài)分布的標(biāo)準(zhǔn)偏差。在二維空間中,這個(gè)公式生成的曲面的等高線是從中心開始呈正態(tài)分布的同心圓。分布不為零的像素組成的卷積矩陣與原始圖像做變換。每個(gè)像素的值都是周圍相鄰像素值的加權(quán)平均。原始像素的值有***的高斯分布值,所以有***的權(quán)重,相鄰像素隨著距離原始像素越來(lái)越遠(yuǎn),其權(quán)重也越來(lái)越小。這樣進(jìn)行模糊處理比其它的均衡模糊濾波器更高地保留了邊緣效果。

其實(shí),在iOS上實(shí)現(xiàn)高斯模糊是件很容易的事兒。早在iOS 5.0就有了Core Image的API,而且在CoreImage.framework庫(kù)中,提供了大量的濾鏡實(shí)現(xiàn)。

+(UIImage *)coreBlurImage:(UIImage *)image withBlurNumber:(CGFloat)blur 
{ CIContext *context = [CIContext contextWithOptions:nil]; CIImage *inputImage= [CIImage imageWithCGImage:image.CGImage]; //設(shè)置filterCIFilter *filter = [CIFilter filterWithName:@"CIGaussianBlur"]; 
    [filter setValue:inputImage forKey:kCIInputImageKey]; [filter setValue:@(blur) forKey: @"inputRadius"]; //模糊圖片CIImage *result=[filter valueForKey:kCIOutputImageKey]; CGImageRef outImage=[context createCGImage:result fromRect:[result extent]];       UIImage *blurImage=[UIImage imageWithCGImage:outImage];           CGImageRelease(outImage); return blurImage;
}

在Android上實(shí)現(xiàn)高斯模糊也可以使用原生的API—–RenderScript,不過(guò)需要Android的API是17以上,也就是Android 4.2版本。

/**      * 使用RenderScript實(shí)現(xiàn)高斯模糊的算法      * @param bitmap      * @return      */public Bitmap blur(Bitmap bitmap){//Let's create an empty bitmap with the same size of the bitmap we want to blurBitmap outBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);//Instantiate a new RenderscriptRenderScript rs = RenderScript.create(getApplicationContext());//Create an Intrinsic Blur Script using the RenderscriptScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));//Create the Allocations (in/out) with the Renderscript and the in/out bitmapsAllocation allIn = Allocation.createFromBitmap(rs, bitmap);
        Allocation allOut = Allocation.createFromBitmap(rs, outBitmap);//Set the radius of the blur: 0 < radius <= 25blurScript.setRadius(20.0f);//Perform the RenderscriptblurScript.setInput(allIn);
        blurScript.forEach(allOut);//Copy the final bitmap created by the out Allocation to the outBitmapallOut.copyTo(outBitmap);//recycle the original bitmapbitmap.recycle();//After finishing everything, we destroy the Renderscript.rs.destroy();return outBitmap;

    }

我們開發(fā)的圖像框架cv4j也提供了一個(gè)濾鏡來(lái)實(shí)現(xiàn)高斯模糊。

GaussianBlurFilter filter = new GaussianBlurFilter();filter.setSigma(10);RxImageData.bitmap(bitmap).addFilter(filter).into(image2);

Java怎樣實(shí)現(xiàn)高斯模糊和圖像的空間卷積

Java怎樣實(shí)現(xiàn)高斯模糊和圖像的空間卷積

可以看出,cv4j實(shí)現(xiàn)的高斯模糊跟RenderScript實(shí)現(xiàn)的效果一致。

其中,GaussianBlurFilter的代碼如下:

public class GaussianBlurFilter implements CommonFilter {private float[] kernel;private double sigma = 2;
    ExecutorService mExecutor;
    CompletionService<Void> service;public GaussianBlurFilter() {
        kernel = new float[0];
    }public void setSigma(double a) {this.sigma = a;
    }@Overridepublic ImageProcessor filter(final ImageProcessor src){final int width = src.getWidth();final int height = src.getHeight();final int size = width*height;int dims = src.getChannels();
        makeGaussianKernel(sigma, 0.002, (int)Math.min(width, height));

        mExecutor = TaskUtils.newFixedThreadPool("cv4j",dims);
        service = new ExecutorCompletionService<>(mExecutor);// save resultfor(int i=0; i<dims; i++) {final int temp = i;
            service.submit(new Callable<Void>() {public Void call() throws Exception {byte[] inPixels = src.toByte(temp);byte[] temp = new byte[size];
                    blur(inPixels, temp, width, height); // H Gaussianblur(temp, inPixels, height, width); // V Gaussainreturn null;
                }
            });
        }for (int i = 0; i < dims; i++) {try {
                service.take();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        mExecutor.shutdown();return src;
    }/**      * <p> here is 1D Gaussian        , </p>      *      * @param inPixels      * @param outPixels      * @param width      * @param height      */private void blur(byte[] inPixels, byte[] outPixels, int width, int height)     {int subCol = 0;int index = 0, index2 = 0;float sum = 0;int k = kernel.length-1;for(int row=0; row<height; row++) {int c = 0;
            index = row;for(int col=0; col<width; col++) {
                sum = 0;for(int m = -k; m< kernel.length; m++) {
                    subCol = col + m;if(subCol < 0 || subCol >= width) {
                        subCol = 0;
                    }
                    index2 = row * width + subCol;
                    c = inPixels[index2] & 0xff;
                    sum += c * kernel[Math.abs(m)];
                }
                outPixels[index] = (byte)Tools.clamp(sum);
                index += height;
            }
        }
    }public void makeGaussianKernel(final double sigma, final double accuracy, int maxRadius) {int kRadius = (int)Math.ceil(sigma*Math.sqrt(-2*Math.log(accuracy)))+1;if (maxRadius < 50) maxRadius = 50;         // too small maxRadius would result in inaccurate sum.if (kRadius > maxRadius) kRadius = maxRadius;
        kernel = new float[kRadius];for (int i=0; i<kRadius; i++)               // Gaussian functionkernel[i] = (float)(Math.exp(-0.5*i*i/sigma/sigma));double sum;                                 // sum over all kernel elements for normalizationif (kRadius < maxRadius) {
            sum = kernel[0];for (int i=1; i<kRadius; i++)
                sum += 2*kernel[i];
        } elsesum = sigma * Math.sqrt(2*Math.PI);for (int i=0; i<kRadius; i++) {double v = (kernel[i]/sum);
            kernel[i] = (float)v;
        }return;
    }
}

空間卷積

二維卷積在圖像處理中會(huì)經(jīng)常遇到,圖像處理中用到的大多是二維卷積的離散形式。

Java怎樣實(shí)現(xiàn)高斯模糊和圖像的空間卷積

以下是cv4j實(shí)現(xiàn)的各種卷積效果。

Java怎樣實(shí)現(xiàn)高斯模糊和圖像的空間卷積

Java怎樣實(shí)現(xiàn)高斯模糊和圖像的空間卷積

cv4j 目前支持如下的空間卷積濾鏡

filter名稱作用
ConvolutionHVFilter卷積模糊或者降噪
MinMaxFilter***最小值濾波去噪聲
SAPNoiseFilter椒鹽噪聲增加噪聲
SharpFilter銳化增強(qiáng)
MedimaFilter中值濾波去噪聲
LaplasFilter拉普拉斯提取邊緣
FindEdgeFilter尋找邊緣梯度提取
SobelFilter梯度獲取x、y方向的梯度提取
VarianceFilter方差濾波高通濾波
MaerOperatorFilter馬爾操作高通濾波
USMFilterUSM增強(qiáng)

cv4j 是gloomyfish和我一起開發(fā)的圖像處理庫(kù),目前還處于早期的版本。

目前已經(jīng)實(shí)現(xiàn)的功能:

Java怎樣實(shí)現(xiàn)高斯模糊和圖像的空間卷積

我們對(duì) cv4j 做了較大的調(diào)整,對(duì)整體架構(gòu)進(jìn)行了優(yōu)化。還加上了空間卷積功能(圖片增強(qiáng)、銳化、模糊等等)。

上述就是小編為大家分享的Java怎樣實(shí)現(xiàn)高斯模糊和圖像的空間卷積了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI