美文网首页UIAndroid开发程序员
高斯模糊全解:从低效到高效、从静态到动态

高斯模糊全解:从低效到高效、从静态到动态

作者: 奔跑吧李博 | 来源:发表于2017-11-14 22:10 被阅读154次

    github代码直通车

    先上效果图:

    动态调节高斯模糊 模糊dialog 相机弹框实时高斯模糊

    原理:

    在我们洗澡的时候,透过厕所雾蒙蒙的玻璃看过去,是不是很漂亮。这就是现实中的毛玻璃效果。原理很简单,你把眼镜儿取了,你看到到处都是高斯模糊。就是做算法,将原本清晰的图像加入放大镜,让你的眼镜不能聚焦。

    做法原理:
    将每一个正在处理的像素,取周围若干个像素的RGB值的平均数,来作为该点的RGB。用正太分布函数,越靠近中心,计算的权重越大,处理强度越大。

    正太分布图

    实现高斯模糊的途径:

    • RenderScript
    • Java算法
    • NDK算法
    • openGL

    Java实现的高斯模糊

    通过设置模糊半径得到一个RGB矩阵,每个color分别右移24,16,8位按位与0xff,然后截取低8位,分别计算平均值。

    public class BlurImageView {
        /**
         * 水平方向模糊度
         */
        private static float hRadius = 8;
        /**
         * 竖直方向模糊度
         */
        private static float vRadius = 8;
        /**
         * 模糊迭代度
         */
        private static int iterations = 8;
    
        /**
         * 图片高斯模糊处理 �
         */
        public static Bitmap BlurImages(Bitmap bmp) {
    
            int width = bmp.getWidth();
            int height = bmp.getHeight();
            int[] inPixels = new int[width * height];
            int[] outPixels = new int[width * height];
            Bitmap bitmap = Bitmap.createBitmap(width, height,
                    Bitmap.Config.ARGB_8888);
            bmp.getPixels(inPixels, 0, width, 0, 0, width, height);
            for (int i = 0; i < iterations; i++) {
                blur(inPixels, outPixels, width, height, hRadius);
                blur(outPixels, inPixels, height, width, vRadius);
            }
            blurFractional(inPixels, outPixels, width, height, hRadius);
            blurFractional(outPixels, inPixels, height, width, vRadius);
            bitmap.setPixels(inPixels, 0, width, 0, 0, width, height);
            return bitmap;
        }
    
        /**
         * 图片高斯模糊算法�
         */
        public static void blur(int[] in, int[] out, int width, int height,
                                float radius) {
            int widthMinus1 = width - 1;
            int r = (int) radius;
            int tableSize = 2 * r + 1;
            int divide[] = new int[256 * tableSize];
    
            for (int i = 0; i < 256 * tableSize; i++)
                divide[i] = i / tableSize;
    
            int inIndex = 0;
    
            for (int y = 0; y < height; y++) {
                int outIndex = y;
                int ta = 0, tr = 0, tg = 0, tb = 0;
    
                for (int i = -r; i <= r; i++) {
                    int rgb = in[inIndex + clamp(i, 0, width - 1)];
                    ta += (rgb >> 24) & 0xff;
                    tr += (rgb >> 16) & 0xff;
                    tg += (rgb >> 8) & 0xff;
                    tb += rgb & 0xff;
                }
    
                for (int x = 0; x < width; x++) {
                    out[outIndex] = (divide[ta] << 24) | (divide[tr] << 16)
                            | (divide[tg] << 8) | divide[tb];
    
                    int i1 = x + r + 1;
                    if (i1 > widthMinus1)
                        i1 = widthMinus1;
                    int i2 = x - r;
                    if (i2 < 0)
                        i2 = 0;
                    int rgb1 = in[inIndex + i1];
                    int rgb2 = in[inIndex + i2];
    
                    ta += ((rgb1 >> 24) & 0xff) - ((rgb2 >> 24) & 0xff);
                    tr += ((rgb1 & 0xff0000) - (rgb2 & 0xff0000)) >> 16;
                    tg += ((rgb1 & 0xff00) - (rgb2 & 0xff00)) >> 8;
                    tb += (rgb1 & 0xff) - (rgb2 & 0xff);
                    outIndex += height;
                }
                inIndex += width;
            }
        }
    
        /**
         * 图片高斯模糊算法 �
         */
        public static void blurFractional(int[] in, int[] out, int width,
                                          int height, float radius) {
            radius -= (int) radius;
            float f = 1.0f / (1 + 2 * radius);
            int inIndex = 0;
    
            for (int y = 0; y < height; y++) {
                int outIndex = y;
    
                out[outIndex] = in[0];
                outIndex += height;
                for (int x = 1; x < width - 1; x++) {
                    int i = inIndex + x;
                    int rgb1 = in[i - 1];
                    int rgb2 = in[i];
                    int rgb3 = in[i + 1];
    
                    int a1 = (rgb1 >> 24) & 0xff;
                    int r1 = (rgb1 >> 16) & 0xff;
                    int g1 = (rgb1 >> 8) & 0xff;
                    int b1 = rgb1 & 0xff;
                    int a2 = (rgb2 >> 24) & 0xff;
                    int r2 = (rgb2 >> 16) & 0xff;
                    int g2 = (rgb2 >> 8) & 0xff;
                    int b2 = rgb2 & 0xff;
                    int a3 = (rgb3 >> 24) & 0xff;
                    int r3 = (rgb3 >> 16) & 0xff;
                    int g3 = (rgb3 >> 8) & 0xff;
                    int b3 = rgb3 & 0xff;
                    a1 = a2 + (int) ((a1 + a3) * radius);
                    r1 = r2 + (int) ((r1 + r3) * radius);
                    g1 = g2 + (int) ((g1 + g3) * radius);
                    b1 = b2 + (int) ((b1 + b3) * radius);
                    a1 *= f;
                    r1 *= f;
                    g1 *= f;
                    b1 *= f;
                    out[outIndex] = (a1 << 24) | (r1 << 16) | (g1 << 8) | b1;
                    outIndex += height;
                }
                out[outIndex] = in[width - 1];
                inIndex += width;
            }
        }
    
        public static int clamp(int x, int a, int b) {
            return (x < a) ? a : (x > b) ? b : x;
        }
    
    }
    

    RenderScript算法

    详情见我另一篇博客:(http://www.jianshu.com/p/bc5df96c8e4f)
    引入方式:

        defaultConfig {
            applicationId "com.example.renderscript.renderscriptuse"
            minSdkVersion 17
            targetSdkVersion 26
            versionCode 1
            versionName "1.0"
            testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    
            renderscriptTargetApi 18
            renderscriptSupportModeEnabled true
        }
    

    调用方法:

        public static Bitmap handleGlassblur(Context context,Bitmap originBitmap,int radius){
            RenderScript renderScript = RenderScript.create(context);
            Allocation input = Allocation.createFromBitmap(renderScript,originBitmap);
            Allocation output = Allocation.createTyped(renderScript,input.getType());
            ScriptIntrinsicBlur scriptIntrinsicBlur = ScriptIntrinsicBlur.create(renderScript, Element.U8_4(renderScript));
            scriptIntrinsicBlur.setRadius(radius);
            scriptIntrinsicBlur.setInput(input);
            scriptIntrinsicBlur.forEach(output);
            output.copyTo(originBitmap);
    
            return originBitmap;
        }
    

    功能1:动态调节高斯模糊

        private void init() {
            imageView = (ImageView) findViewById(R.id.imageview);
            seekBar = (SeekBar) findViewById(R.id.seekbar);
            seekBar.setMax(25);
            seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.mipmap.test10);
                    if(progress < 1){
                        progress = 1;
                    }
                    Bitmap blurBitmap = RenderScriptGlassBlur.handleGlassblur(getApplicationContext(),bitmap,progress);
                    imageView.setImageBitmap(blurBitmap);
                }
    
                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {}
    
                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {}
            });
        }
    

    因为该方法模糊范围是1-25,所以seekbar范围也控制在1-25;

    功能2:全屏高斯模糊dialog

    1. 将activity的上层decorview通过getDrawingCache()获取bitmap,创建dialog,将bitmap传递给dialog作为dialog的全屏背景;
        public void dialog(View view){
            View rootView = getWindow().getDecorView();
            rootView.setDrawingCacheEnabled(true);
            rootView.buildDrawingCache();
            Bitmap mBitmap = rootView.getDrawingCache();
    
            new BlurDialog(this,mBitmap);
        }
    

    2.在dialog中调用RenderScriptGlassBlur.bitmapBlur(context,ivBg,bitmap,3)将传递过来的背景图进行高斯模糊,所以才能得到下层activity的样子。实际上就是在dialog下层加了一层activity显示图片。

    public class BlurDialog {
        private Dialog dialog;
        private ImageView ivBg;
    
        public BlurDialog(Context context,Bitmap bitmap){
            dialog = new Dialog(context, R.style.BottomDialog);
            dialog.setContentView(R.layout.dialog_bgblur);
            dialog.show();
    
            ivBg = dialog.findViewById(R.id.imageview_bg);
    
            fullScreen();
    
            RenderScriptGlassBlur.bitmapBlur(context,ivBg,bitmap,3);
        }
    
        private void fullScreen(){
            //dialog全屏设置
            WindowManager.LayoutParams layoutParams = dialog.getWindow().getAttributes();
            layoutParams.gravity= Gravity.BOTTOM;
            layoutParams.width= WindowManager.LayoutParams.MATCH_PARENT;
            layoutParams.height= WindowManager.LayoutParams.MATCH_PARENT;
            dialog.getWindow().getDecorView().setPadding(0, 0, 0, 0);
            dialog.getWindow().setAttributes(layoutParams);
        }
    }
    

    dialog全屏style设置

        <style name="BottomDialog" parent="@android:style/Theme.NoTitleBar.Fullscreen">
            <item name="android:windowNoTitle">true</item>
            <item name="android:windowBackground">@color/transparent</item>
            <!-- 是否有边框 -->
            <item name="android:windowFrame">@null</item>
            <!--是否在悬浮Activity之上  -->
            <item name="android:windowIsFloating">true</item>
        </style>
    

    dialog的xml布局

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <ImageView
            android:id="@+id/imageview_bg"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    
        <android.support.v7.widget.CardView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            app:cardElevation="0dp"
            app:cardCornerRadius="5dp">
    
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">
    
                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textColor="#000"
                    android:textSize="16sp"
                    android:padding="12dp"
                    android:background="#fff"
                    android:text="我是网红程熙媛"/>
    
                <ImageView
                    android:layout_width="270dp"
                    android:layout_height="400dp"
                    android:background="@mipmap/test10"
                    android:scaleType="centerCrop"/>
    
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="#fff"
                    android:padding="10dp">
    
                    <ImageView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:background="@mipmap/attention_btn_good"
                        android:layout_marginRight="20dp"/>
    
                    <ImageView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:background="@mipmap/find_btn_comment"
                        android:layout_marginRight="20dp"/>
    
                    <ImageView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:background="@mipmap/dynamic_more"
                        android:layout_marginRight="20dp"/>
                </LinearLayout>
            </LinearLayout>
        </android.support.v7.widget.CardView>
    
    </RelativeLayout>
    

    功能3:在摄像头上调用diaolog,实时高斯模糊

    handler.sendEmptyMessageDelayed(0,40);用handler每过40毫秒发送命令,从相机显示view中获取一帧bitmap进行高斯模糊,每秒就会有25帧图切换。25帧/s的图片播放就会是连续的视频。但是需要在dialog的
    setOnDismissListener中调用handler.removeCallbacksAndMessages(null)停止截取帧

    public class CameraSetupDialog {
        private Dialog dialog;
        private Context context;
        private RadioGroup rgSpeed,rgFocus,rgSkin,rgDelay;
        private ImageView ivBg;
        private View viewClose;
        private Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                RenderScriptGlassBlur.bitmapBlur(context,ivBg, DialogBgActivity.textureView.getBitmap(),8);
                handler.sendEmptyMessageDelayed(0,40);
            }
        };
    
        public CameraSetupDialog(Context context) {
            this.context = context;
    
            dialog = new Dialog(context, R.style.BottomDialog);
            dialog.setContentView(R.layout.camera_setup);
            dialog.show();
    
            initView();
    
            init();
            event();
        }
    
        private void initView() {
            rgSpeed = dialog.findViewById(R.id.rg_camera_speed);
            rgFocus = dialog.findViewById(R.id.rg_camera_focus);
            rgSkin = dialog.findViewById(R.id.rg_camera_skin);
            rgDelay = dialog.findViewById(R.id.rg_camera_delay);
            viewClose = dialog.findViewById(R.id.view_close);
            ivBg = dialog.findViewById(R.id.iv_bg);
            dialog.setCanceledOnTouchOutside(true);
    
            ((RadioButton)rgSpeed.getChildAt(0)).setChecked(true);
            ((RadioButton)rgFocus.getChildAt(0)).setChecked(true);
            ((RadioButton)rgSkin.getChildAt(0)).setChecked(true);
            ((RadioButton)rgDelay.getChildAt(0)).setChecked(true);
    
            handler.sendEmptyMessageDelayed(0,40);
        }
    
        private void event(){
    
            dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    handler.removeCallbacksAndMessages(null);
                }
            });
        }
    
        private void init() {
            //显示对话框时,后面的Activity不变暗,可选操作。
            Window win = dialog.getWindow();
            win.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    
            //对话框全屏
            WindowManager windowManager = dialog.getWindow().getWindowManager();
            Display display = windowManager.getDefaultDisplay();
            WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
            lp.width = display.getWidth(); //设置宽度
            lp.height = display.getHeight();
            dialog.getWindow().setAttributes(lp);
        }
    
    }
    

    好了,还有什么思维不连贯的,有疑惑的就在github上下载demo来看吧。

    相关文章

      网友评论

      • 奔跑吧李博:通过bitmap的裁剪得到新的局部bitmap,再进行高斯模糊
      • 执着的小虫子:作者你好,有没有做过局部高斯模糊,Glide加载图片。

      本文标题:高斯模糊全解:从低效到高效、从静态到动态

      本文链接:https://www.haomeiwen.com/subject/xmrwmxtx.html