Android 摄像头高斯模糊的示例代码
程序员文章站
2022-08-03 18:11:28
好久没写文章了,之前项目中有过这个需求但是时间紧就在上面盖了个半透明的白色图片,效果.....
好了,不废话,先看一下效果吧
注意了,这不是对单纯的图片进行高斯模糊...
好久没写文章了,之前项目中有过这个需求但是时间紧就在上面盖了个半透明的白色图片,效果.....
好了,不废话,先看一下效果吧
注意了,这不是对单纯的图片进行高斯模糊,而是对摄像头实时处理
原理:
大体讲一下实现原理,摄像头回调的每一帧通过renderscript将字节数组转换为bitmap,再对bitmap进行高斯模糊处理。流畅度还是不错的。毕竟renderscript使用的是gpu去计算,速度比普通的用cpu计算的方法快的多
核心代码:
/** * 转换数据并进行模糊处理 */ public bitmap blur(byte[] data, camera camera,float blurvaule){ camera.size previewsize = camera.getparameters().getpreviewsize(); if (yuvtype == null) { yuvtype = new type.builder(rs, element.u8(rs)).setx(data.length); in = allocation.createtyped(rs, yuvtype.create(), allocation.usage_script); rgbatype = new type.builder(rs, element.rgba_8888(rs)).setx(previewsize.width).sety(previewsize.height); out = allocation.createtyped(rs, rgbatype.create(), allocation.usage_script); } in.copyfrom(data); yuvtorgbintrinsic.setinput(in); yuvtorgbintrinsic.foreach(out); bitmap bmpout = bitmap.createbitmap(previewsize.width, previewsize.height, bitmap.config.argb_8888); out.copyto(bmpout); //return adjustphotorotation(blurbitmap(bmpout,blurvaule),90); return blurbitmap(bmpout,blurvaule); } /** * 模糊处理bitmap * @param bitmap * @return */ private bitmap blurbitmap(bitmap bitmap,float vaule) { // 用需要创建高斯模糊bitmap创建一个空的bitmap bitmap outbitmap = bitmap.createbitmap(bitmap.getwidth(), bitmap.getheight(), bitmap.config.argb_8888); // 初始化renderscript,这个类提供了renderscript context, // 在创建其他rs类之前必须要先创建这个类,他控制renderscript的初始化,资源管理,释放 // 创建高斯模糊对象 // 创建allocations,此类是将数据传递给renderscript内核的主要方法, // 并制定一个后备类型存储给定类型 allocation allin = allocation.createfrombitmap(rs, bitmap); allocation allout = allocation.createfrombitmap(rs, outbitmap); // 设定模糊度 blurscript.setradius(vaule); // perform the renderscript blurscript.setinput(allin); blurscript.foreach(allout); // copy the final bitmap created by the out allocation to the outbitmap allout.copyto(outbitmap); // recycle the original bitmap bitmap.recycle(); // after finishing everything, we destroy the renderscript. rs.destroy(); return outbitmap; }
ok,这两个方法就够了,将返回的bitmap给imageview就可以了,之前一直以为是用jni实现的,试了一下才发现java也可以,效果也不错,网上也没类似教程就写出来给需要的人。对了,还需要在项目的build.gradle中加入
defaultconfig { ....... renderscripttargetapi 21 renderscriptsupportmodeenabled true }
具体使用方法和代码可以参考我github的cameraview,这个控件也可以快速帮你实现摄像头的预览,拍照,加水印,高斯模糊的效果, https://github.com/bertsir/cameraview
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
下一篇: 山药的药用价值是什么,它有什么药用价值