Here are the examples of the java api android.renderscript.RenderScript taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
124 Examples
19
Source : HeifReader.java
with MIT License
from yohhoy
with MIT License
from yohhoy
/**
* HEIF(High Efficiency Image Format) reader
*
* Create Bitmap object from HEIF file, byte-array, stream, etc.
*/
public clreplaced HeifReader {
private static final String TAG = "HeifReader";
/**
* input data size limitation for safety.
*/
// 20[MB]
private static final long LIMIT_FILESIZE = 20 * 1024 * 1024;
private static RenderScript mRenderScript;
private static File mCacheDir;
private static String mDecoderName;
private static Size mDecoderSupportedSize;
/**
* Initialize HeifReader module.
*
* @param context Context.
*/
public static void initialize(Context context) {
mRenderScript = RenderScript.create(context);
mCacheDir = context.getCacheDir();
// find best HEVC decoder
mDecoderName = null;
mDecoderSupportedSize = new Size(0, 0);
int numCodecs = MediaCodecList.getCodecCount();
for (int i = 0; i < numCodecs; i++) {
MediaCodecInfo codecInfo = MediaCodecList.getCodecInfoAt(i);
if (codecInfo.isEncoder()) {
continue;
}
for (String type : codecInfo.getSupportedTypes()) {
if (type.equalsIgnoreCase(MediaFormat.MIMETYPE_VIDEO_HEVC)) {
MediaCodecInfo.CodecCapabilities cap = codecInfo.getCapabilitiesForType(MediaFormat.MIMETYPE_VIDEO_HEVC);
MediaCodecInfo.VideoCapabilities vcap = cap.getVideoCapabilities();
Size supportedSize = new Size(vcap.getSupportedWidths().getUpper(), vcap.getSupportedHeights().getUpper());
Log.d(TAG, "HEVC decoder=\"" + codecInfo.getName() + "\"" + " supported-size=" + supportedSize + " color-formats=" + Arrays.toString(cap.colorFormats));
if (mDecoderSupportedSize.getWidth() * mDecoderSupportedSize.getHeight() < supportedSize.getWidth() * supportedSize.getHeight()) {
mDecoderName = codecInfo.getName();
mDecoderSupportedSize = supportedSize;
}
}
}
}
if (mDecoderName == null) {
throw new RuntimeException("no HEVC decoding support");
}
Log.i(TAG, "HEVC decoder=\"" + mDecoderName + "\" supported-size=" + mDecoderSupportedSize);
}
/**
* Decode a bitmap from the specified byte array.
*
* @param data byte array of compressed image data.
* @return The decoded bitmap, or null if the image could not be decoded.
*/
public static Bitmap decodeByteArray(byte[] data) {
replacedertPrecondition();
try {
ByteArrayInputStream bais = new ByteArrayInputStream(data);
IsoFile isoFile = new IsoFile(Channels.newChannel(bais));
ImageInfo info = parseHeif(isoFile);
ByteBuffer bitstream = extractBitstream(data, info);
try {
return renderHevcImageWithFormat(bitstream, info, ImageFormat.YV12);
} catch (FormatFallbackException ex) {
Log.w(TAG, "rendering YV12 format failure; fallback to RGB565");
try {
bitstream.rewind();
return renderHevcImageWithFormat(bitstream, info, ImageFormat.RGB_565);
} catch (FormatFallbackException ex2) {
Log.e(TAG, "rendering RGB565 format failure", ex2);
return null;
}
}
} catch (IOException ex) {
Log.e(TAG, "decodeByteArray failure", ex);
return null;
}
}
/**
* Decode a file path into a bitmap.
*
* @param pathName complete path name for the file to be decoded.
* @return The decoded bitmap, or null if the image could not be decoded.
*/
public static Bitmap decodeFile(String pathName) {
replacedertPrecondition();
try {
File file = new File(pathName);
long fileSize = file.length();
if (LIMIT_FILESIZE < fileSize) {
Log.e(TAG, "file size exceeds limit(" + LIMIT_FILESIZE + ")");
return null;
}
byte[] data = new byte[(int) fileSize];
try (FileInputStream fis = new FileInputStream(file)) {
fis.read(data);
return decodeByteArray(data);
}
} catch (IOException ex) {
Log.e(TAG, "decodeFile failure", ex);
return null;
}
}
/**
* Decode a raw resource into a bitmap.
*
* @param res The resources object containing the image data.
* @param id The resource id of the image data.
* @return The decoded bitmap, or null if the image could not be decoded.
*/
public static Bitmap decodeResource(Resources res, int id) {
replacedertPrecondition();
try {
int length = (int) res.openRawResourceFd(id).getLength();
byte[] data = new byte[length];
res.openRawResource(id).read(data);
return decodeByteArray(data);
} catch (IOException ex) {
Log.e(TAG, "decodeResource failure", ex);
return null;
}
}
/**
* Decode an input stream into a bitmap.
*
* This method save input stream to temporary file on cache directory, because HEIF data
* structure requires multi-preplaced parsing.
*
* @param is The input stream that holds the raw data to be decoded into a bitmap.
* @return The decoded bitmap, or null if the image could not be decoded.
*/
public static Bitmap decodeStream(InputStream is) {
replacedertPrecondition();
try {
// write stream to temporary file
long beginTime = SystemClock.elapsedRealtimeNanos();
File heifFile = File.createTempFile("heifreader", "heif", mCacheDir);
try (FileOutputStream fos = new FileOutputStream(heifFile)) {
byte[] buf = new byte[4096];
int totalLength = 0;
int len;
while ((len = is.read(buf)) > 0) {
fos.write(buf, 0, len);
totalLength += len;
if (LIMIT_FILESIZE < totalLength) {
Log.e(TAG, "data size exceeds limit(" + LIMIT_FILESIZE + ")");
return null;
}
}
}
long endTime = SystemClock.elapsedRealtimeNanos();
Log.i(TAG, "HEIC caching elapsed=" + (endTime - beginTime) / 1000000.f + "[msec]");
return decodeFile(heifFile.getAbsolutePath());
} catch (IOException ex) {
Log.e(TAG, "decodeStream failure", ex);
return null;
}
}
private static void replacedertPrecondition() {
if (mRenderScript == null) {
throw new IllegalStateException("HeifReader is not initialized.");
}
}
private static ImageInfo parseHeif(IsoFile isoFile) throws IOException {
// validate brand compatibility ('ftyp' box)
List<FileTypeBox> ftypBoxes = isoFile.getBoxes(FileTypeBox.clreplaced);
if (ftypBoxes.size() != 1) {
throw new IOException("FileTypeBox('ftyp') shall be unique");
}
FileTypeBox ftypBox = ftypBoxes.get(0);
Log.d(TAG, "HEIC ftyp=" + ftypBox);
if (!("mif1".equals(ftypBox.getMajorBrand()) || "heic".equals(ftypBox.getMajorBrand()) || !ftypBox.getCompatibleBrands().contains("heic"))) {
throw new IOException("unsupported FileTypeBox('ftyp') brands");
}
// get primary item_ID
List<PrimaryItemBox> pitmBoxes = isoFile.getBoxes(PrimaryItemBox.clreplaced, true);
if (pitmBoxes.isEmpty()) {
throw new IOException("PrimaryItemBox('pitm') not found");
}
PrimaryItemBox pitmBox = pitmBoxes.get(0);
pitmBox.parseDetails();
Log.d(TAG, "HEIC primary item_ID=" + pitmBox.gereplacedemId());
// get replacedociative item properties
ItemPropertiesBox iprpBox = isoFile.getBoxes(ItemPropertiesBox.clreplaced, true).get(0);
ItemPropertyreplacedociation ipmaBox = iprpBox.getBoxes(ItemPropertyreplacedociation.clreplaced).get(0);
ItemPropertyContainerBox ipcoBox = iprpBox.getBoxes(ItemPropertyContainerBox.clreplaced).get(0);
List<Box> primaryPropBoxes = new ArrayList<>();
for (ItemPropertyreplacedociation.Item item : ipmaBox.gereplacedems()) {
if (item.item_ID == pitmBox.gereplacedemId()) {
for (ItemPropertyreplacedociation.replacedoc replacedoc : item.replacedociations) {
primaryPropBoxes.add(ipcoBox.getBoxes().get(replacedoc.property_index - 1));
}
}
}
// get image size
ImageInfo info = new ImageInfo();
ImageSpatialExtentsBox ispeBox = findBox(primaryPropBoxes, ImageSpatialExtentsBox.clreplaced);
if (ispeBox == null) {
throw new IOException("ImageSpatialExtentsBox('ispe') not found");
}
info.size = new Size((int) ispeBox.display_width, (int) ispeBox.display_height);
Log.i(TAG, "HEIC image size=" + ispeBox.display_width + "x" + ispeBox.display_height);
// get HEVC decoder configuration
HevcConfigurationBox hvccBox = findBox(primaryPropBoxes, HevcConfigurationBox.clreplaced);
if (hvccBox == null) {
throw new IOException("HevcConfigurationBox('hvcC') not found");
}
HevcDecoderConfigurationRecord hevcConfig = hvccBox.getHevcDecoderConfigurationRecord();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
final byte[] startCode = { 0x00, 0x00, 0x00, 0x01 };
for (HevcDecoderConfigurationRecord.Array params : hevcConfig.getArrays()) {
for (byte[] nalUnit : params.nalUnits) {
baos.write(startCode);
baos.write(nalUnit);
}
}
info.paramset = ByteBuffer.wrap(baos.toByteArray());
Log.d(TAG, "HEIC HEVC profile=" + hevcConfig.getGeneral_profile_idc() + " level=" + (hevcConfig.getGeneral_level_idc() / 30f) + " bitDepth=" + (hevcConfig.getBitDepthLumaMinus8() + 8));
if (hevcConfig.getLengthSizeMinusOne() + 1 != 4) {
throw new IOException("unsupported DecoderConfigurationRecord.LengthSizeMinusOne(" + hevcConfig.getLengthSizeMinusOne() + ")");
}
// get bitstream position
List<ItemLocationBox> ilocBoxes = isoFile.getBoxes(ItemLocationBox.clreplaced, true);
if (ilocBoxes.isEmpty()) {
throw new IOException("ItemLocationBox('iloc') not found");
}
ItemLocationBox ilocBox = ilocBoxes.get(0);
ilocBox.parseDetails();
for (ItemLocationBox.Item item : ilocBox.gereplacedems()) {
if (item.itemId == pitmBox.gereplacedemId()) {
info.offset = (int) item.baseOffset + (int) item.extents.get(0).extentOffset;
info.length = (int) item.extents.get(0).extentLength;
break;
}
}
Log.d(TAG, "HEIC bitstream offset=" + info.offset + " length=" + info.length);
return info;
}
private static ByteBuffer extractBitstream(byte[] heif, ImageInfo info) {
// extract HEVC bitstream
ByteBuffer bitstream = ByteBuffer.allocate(info.length).put(heif, info.offset, info.length).order(ByteOrder.BIG_ENDIAN);
bitstream.rewind();
// convert hvcC format to Annex.B format
do {
int pos = bitstream.position();
// hevcConfig.getLengthSizeMinusOne()==3
int size = bitstream.getInt();
bitstream.position(pos);
// start_code={0x00 0x00 0x00 0x01}
bitstream.putInt(1);
bitstream.position(bitstream.position() + size);
} while (bitstream.remaining() > 0);
bitstream.rewind();
return bitstream;
}
@SuppressWarnings("unchecked")
private static <T extends Box> T findBox(List<Box> container, Clreplaced<T> clazz) {
for (Box box : container) {
if (clazz.isInstance(box)) {
return (T) box;
}
}
return null;
}
private static MediaCodec configureDecoder(ImageInfo info, int maxInputSize, Surface surface) {
if (mDecoderSupportedSize.getWidth() < info.size.getWidth() || mDecoderSupportedSize.getHeight() < info.size.getHeight()) {
Log.w(TAG, "HEVC image may exceed decoder capability");
}
try {
MediaCodec decoder = MediaCodec.createByCodecName(mDecoderName);
MediaFormat inputFormat = MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_HEVC, info.size.getWidth(), info.size.getHeight());
inputFormat.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, maxInputSize);
inputFormat.setByteBuffer("csd-0", info.paramset);
Log.d(TAG, "HEVC input-format=" + inputFormat);
decoder.configure(inputFormat, surface, null, 0);
return decoder;
} catch (IOException ex) {
throw new RuntimeException("no HEVC decoding support");
}
}
private static Bitmap renderHevcImageWithFormat(ByteBuffer bitstream, ImageInfo info, int imageFormat) throws FormatFallbackException {
try (ImageReader reader = ImageReader.newInstance(info.size.getWidth(), info.size.getHeight(), imageFormat, 1)) {
renderHevcImage(bitstream, info, reader.getSurface());
Image image = null;
try {
try {
image = reader.acquireNextImage();
} catch (UnsupportedOperationException ex) {
throw new FormatFallbackException(ex);
}
switch(image.getFormat()) {
case ImageFormat.YUV_420_888:
case ImageFormat.YV12:
return convertYuv420ToBitmap(image);
case ImageFormat.RGB_565:
return convertRgb565ToBitmap(image);
default:
throw new RuntimeException("unsupported image format(" + image.getFormat() + ")");
}
} finally {
if (image != null) {
image.close();
}
}
}
}
private static void renderHevcImage(ByteBuffer bitstream, ImageInfo info, Surface surface) {
long beginTime = SystemClock.elapsedRealtimeNanos();
// configure HEVC decoder
MediaCodec decoder = configureDecoder(info, bitstream.limit(), surface);
MediaFormat outputFormat = decoder.getOutputFormat();
Log.d(TAG, "HEVC output-format=" + outputFormat);
decoder.start();
try {
// set bitstream to decoder
int inputBufferId = decoder.dequeueInputBuffer(-1);
if (inputBufferId < 0) {
throw new IllegalStateException("dequeueInputBuffer return " + inputBufferId);
}
ByteBuffer inBuffer = decoder.getInputBuffer(inputBufferId);
inBuffer.put(bitstream);
decoder.queueInputBuffer(inputBufferId, 0, bitstream.limit(), 0, 0);
// notify end of stream
inputBufferId = decoder.dequeueInputBuffer(-1);
if (inputBufferId < 0) {
throw new IllegalStateException("dequeueInputBuffer return " + inputBufferId);
}
decoder.queueInputBuffer(inputBufferId, 0, 0, 0, MediaCodec.BUFFER_FLAG_END_OF_STREAM);
// get decoded image
MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
while (true) {
int outputBufferId = decoder.dequeueOutputBuffer(bufferInfo, -1);
if (outputBufferId >= 0) {
decoder.releaseOutputBuffer(outputBufferId, true);
break;
} else if (outputBufferId == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
outputFormat = decoder.getOutputFormat();
Log.d(TAG, "HEVC output-format=" + outputFormat);
} else {
Log.d(TAG, "HEVC dequeueOutputBuffer return " + outputBufferId);
}
}
decoder.flush();
} finally {
decoder.stop();
decoder.release();
}
long endTime = SystemClock.elapsedRealtimeNanos();
Log.i(TAG, "HEVC decoding elapsed=" + (endTime - beginTime) / 1000000.f + "[msec]");
}
private static Bitmap convertYuv420ToBitmap(Image image) {
RenderScript rs = mRenderScript;
final int width = image.getWidth();
final int height = image.getHeight();
final int chromaWidth = width / 2;
final int chromaHeight = height / 2;
final int lumaSize = width * height;
final int chromaSize = chromaWidth * chromaHeight;
// prepare input Allocation for RenderScript
Type.Builder inType = new Type.Builder(rs, Element.U8(rs)).setX(width).setY(height).setYuvFormat(ImageFormat.YV12);
Allocation inAlloc = Allocation.createTyped(rs, inType.create(), Allocation.USAGE_SCRIPT);
byte[] rawBuffer = new byte[inAlloc.getBytesSize()];
Image.Plane[] planes = image.getPlanes();
final int lumaStride = planes[0].getRowStride();
final int chromaStride = planes[1].getRowStride();
if (lumaStride == width) {
// copy luma plane to rawBuffer (w/o padding)
planes[0].getBuffer().get(rawBuffer, 0, lumaSize);
} else {
// copy luma plane to rawBuffer
ByteBuffer planeBuf = planes[0].getBuffer();
for (int y = 0; y < height; y++) {
planeBuf.position(lumaStride * y);
planeBuf.get(rawBuffer, width * y, width);
}
}
if (chromaStride == chromaWidth) {
// copy chroma planes to rawBuffer (w/o padding)
planes[1].getBuffer().get(rawBuffer, lumaSize, chromaSize);
planes[2].getBuffer().get(rawBuffer, lumaSize + chromaSize, chromaSize);
} else {
// copy chroma planes to rawBuffer
ByteBuffer planeBuf = planes[1].getBuffer();
for (int y = 0; y < chromaHeight; y++) {
planeBuf.position(chromaStride * y);
planeBuf.get(rawBuffer, lumaSize + chromaWidth * y, chromaWidth);
}
planeBuf = planes[2].getBuffer();
for (int y = 0; y < chromaHeight; y++) {
planeBuf.position(chromaStride * y);
planeBuf.get(rawBuffer, lumaSize + chromaSize + chromaWidth * y, chromaWidth);
}
}
inAlloc.copyFromUnchecked(rawBuffer);
// prepare output Allocation for RenderScript
Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Allocation outAlloc = Allocation.createFromBitmap(rs, bmp, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT | Allocation.USAGE_SHARED);
// convert YUV to RGB colorspace
ScriptC_yuv2rgb converter = new ScriptC_yuv2rgb(rs);
converter.set_gYUV(inAlloc);
converter.forEach_convert(outAlloc);
outAlloc.copyTo(bmp);
return bmp;
}
private static Bitmap convertRgb565ToBitmap(Image image) {
Bitmap bmp = Bitmap.createBitmap(image.getWidth(), image.getHeight(), Bitmap.Config.RGB_565);
Image.Plane[] planes = image.getPlanes();
bmp.copyPixelsFromBuffer(planes[0].getBuffer());
return bmp;
}
private static clreplaced ImageInfo {
Size size;
ByteBuffer paramset;
int offset;
int length;
}
private static clreplaced FormatFallbackException extends Exception {
FormatFallbackException(Throwable ex) {
super(ex);
}
}
}
19
Source : RSBlur.java
with GNU General Public License v3.0
from timusus
with GNU General Public License v3.0
from timusus
/**
* Copyright (C) 2015 Wasabeef
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public clreplaced RSBlur {
private static RSBlur sInstance;
private RenderScript renderScript;
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public static RSBlur getInstance(Context context) {
if (sInstance == null) {
sInstance = new RSBlur(context);
}
return sInstance;
}
private RSBlur(Context context) {
renderScript = RenderScript.create(context);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public Bitmap blur(Bitmap bitmap, int radius) throws RSRuntimeException {
Allocation input = null;
Allocation output = null;
ScriptIntrinsicBlur blur = null;
try {
input = Allocation.createFromBitmap(renderScript, bitmap, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT);
output = Allocation.createTyped(renderScript, input.getType());
blur = ScriptIntrinsicBlur.create(renderScript, Element.U8_4(renderScript));
blur.setInput(input);
blur.setRadius(radius);
blur.forEach(output);
output.copyTo(bitmap);
} finally {
if (input != null) {
input.destroy();
}
if (output != null) {
output.destroy();
}
if (blur != null) {
blur.destroy();
}
}
return bitmap;
}
}
19
Source : XBitmapUtil.java
with Apache License 2.0
from starscryer
with Apache License 2.0
from starscryer
/**
* {@link Bitmap} specific helpers.
*
* @author Andrew Neal ([email protected])
*/
public final clreplaced XBitmapUtil {
public static final float BITMAP_SCALE = DefaultConfiguration.BITMAP_SCALE;
/* Initial blur radius. */
public static final int BLUR_RADIUS = DefaultConfiguration.BLUR_RADIUS;
public static final int BLUR_RADIUS_MAX = DefaultConfiguration.BLUR_RADIUS_MAX;
private static RenderScript sRs;
/**
* This clreplaced is never instantiated
*/
private XBitmapUtil() {
}
public static Bitmap createHWBitmap(final Bitmap bmpOriginal) {
int width, height;
height = bmpOriginal.getHeight();
width = bmpOriginal.getWidth();
Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Canvas c = new Canvas(bmpGrayscale);
Paint paint = new Paint();
c.drawBitmap(bmpOriginal, 0, 0, paint);
return bmpGrayscale;
}
/**
* Takes a bitmap and creates a new slightly blurry version of it.
*
* @param sentBitmap The {@link Bitmap} to blur.
* @return A blurred version of the given {@link Bitmap}.
*/
public static Bitmap createBlurredBitmap(final Bitmap sentBitmap) {
return createBlurredBitmap(sentBitmap, BLUR_RADIUS, BITMAP_SCALE);
}
/**
* Takes a bitmap and creates a new slightly blurry version of it.
*
* @param sentBitmap The {@link Bitmap} to blur.
* @param radius Radius of the blur effect.
* @return A blurred version of the given {@link Bitmap}.
*/
public static Bitmap createBlurredBitmap(final Bitmap sentBitmap, int radius, float scale) {
if (sentBitmap == null) {
return null;
}
// Stack Blur v1.0 init
// http://www.quasimondo.com/StackBlurForCanvas/StackBlurDemo.html
//
// Java Author: Mario Klingemann <mario at quasimondo.com>
// http://incubator.quasimondo.com
// created Feburary 29, 2004
// Android port : Yahel Bouaziz <yahel at kayenko.com>
// http://www.kayenko.com
// ported april 5th, 2012
// This is a compromise between Gaussian Blur and Box blur
// It creates much better looking blurs than Box Blur, but is
// 7x faster than my Gaussian Blur implementation.
//
// I called it Stack Blur because this describes best how this
// filter works internally: it creates a kind of moving stack
// of colors whilst scanning through the image. Thereby it
// just has to add one new block of color to the right side
// of the stack and remove the leftmost color. The remaining
// colors on the topmost layer of the stack are either added on
// or reduced by one, depending on if they are on the right or
// on the left side of the stack.
//
// If you are using this algorithm in your code please add
// the following line:
//
// Stack Blur Algorithm by Mario Klingemann <[email protected]>
int width = Math.round(sentBitmap.getWidth() * scale);
int height = Math.round(sentBitmap.getHeight() * scale);
Bitmap inputBitmap = Bitmap.createScaledBitmap(sentBitmap, width, height, false);
final Bitmap mBitmap = Bitmap.createBitmap(inputBitmap);
final int w = mBitmap.getWidth();
final int h = mBitmap.getHeight();
final int[] pix = new int[w * h];
mBitmap.getPixels(pix, 0, w, 0, 0, w, h);
final int wm = w - 1;
final int hm = h - 1;
final int wh = w * h;
final int div = radius + radius + 1;
final int[] r = new int[wh];
final int[] g = new int[wh];
final int[] b = new int[wh];
final int[] vmin = new int[Math.max(w, h)];
int rsum, gsum, bsum, x, y, i, p, yp, yi, yw;
int divsum = div + 1 >> 1;
divsum *= divsum;
final int[] dv = new int[256 * divsum];
for (i = 0; i < 256 * divsum; i++) {
dv[i] = i / divsum;
}
yw = yi = 0;
final int[][] stack = new int[div][3];
int stackpointer;
int stackstart;
int[] sir;
int rbs;
final int r1 = radius + 1;
int routsum, goutsum, boutsum;
int rinsum, ginsum, binsum;
for (y = 0; y < h; y++) {
rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
for (i = -radius; i <= radius; i++) {
p = pix[yi + Math.min(wm, Math.max(i, 0))];
sir = stack[i + radius];
sir[0] = (p & 0xff0000) >> 16;
sir[1] = (p & 0x00ff00) >> 8;
sir[2] = p & 0x0000ff;
rbs = r1 - Math.abs(i);
rsum += sir[0] * rbs;
gsum += sir[1] * rbs;
bsum += sir[2] * rbs;
if (i > 0) {
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
} else {
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
}
}
stackpointer = radius;
for (x = 0; x < w; x++) {
r[yi] = dv[rsum];
g[yi] = dv[gsum];
b[yi] = dv[bsum];
rsum -= routsum;
gsum -= goutsum;
bsum -= boutsum;
stackstart = stackpointer - radius + div;
sir = stack[stackstart % div];
routsum -= sir[0];
goutsum -= sir[1];
boutsum -= sir[2];
if (y == 0) {
vmin[x] = Math.min(x + radius + 1, wm);
}
p = pix[yw + vmin[x]];
sir[0] = (p & 0xff0000) >> 16;
sir[1] = (p & 0x00ff00) >> 8;
sir[2] = p & 0x0000ff;
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
rsum += rinsum;
gsum += ginsum;
bsum += binsum;
stackpointer = (stackpointer + 1) % div;
sir = stack[stackpointer % div];
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
rinsum -= sir[0];
ginsum -= sir[1];
binsum -= sir[2];
yi++;
}
yw += w;
}
for (x = 0; x < w; x++) {
rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
yp = -radius * w;
for (i = -radius; i <= radius; i++) {
yi = Math.max(0, yp) + x;
sir = stack[i + radius];
sir[0] = r[yi];
sir[1] = g[yi];
sir[2] = b[yi];
rbs = r1 - Math.abs(i);
rsum += r[yi] * rbs;
gsum += g[yi] * rbs;
bsum += b[yi] * rbs;
if (i > 0) {
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
} else {
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
}
if (i < hm) {
yp += w;
}
}
yi = x;
stackpointer = radius;
for (y = 0; y < h; y++) {
pix[yi] = 0xff000000 | dv[rsum] << 16 | dv[gsum] << 8 | dv[bsum];
rsum -= routsum;
gsum -= goutsum;
bsum -= boutsum;
stackstart = stackpointer - radius + div;
sir = stack[stackstart % div];
routsum -= sir[0];
goutsum -= sir[1];
boutsum -= sir[2];
if (x == 0) {
vmin[y] = Math.min(y + r1, hm) * w;
}
p = x + vmin[y];
sir[0] = r[p];
sir[1] = g[p];
sir[2] = b[p];
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
rsum += rinsum;
gsum += ginsum;
bsum += binsum;
stackpointer = (stackpointer + 1) % div;
sir = stack[stackpointer];
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
rinsum -= sir[0];
ginsum -= sir[1];
binsum -= sir[2];
yi += w;
}
}
mBitmap.setPixels(pix, 0, w, 0, 0, w, h);
return mBitmap;
}
public synchronized static Bitmap rsBlur(Context context, Bitmap inputBitmap, int radius) {
if (inputBitmap == null) {
return null;
}
// Define this only once if blurring multiple times
if (sRs == null) {
sRs = RenderScript.create(context);
}
// This will blur the bitmapOriginal with a radius of 8 and save it in bitmapOriginal
// use this constructor for best performance, because it uses USAGE_SHARED mode which reuses memory
final Allocation input = Allocation.createFromBitmap(sRs, inputBitmap);
final Allocation output = Allocation.createTyped(sRs, input.getType());
final ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(sRs, Element.U8_4(sRs));
script.setRadius(radius);
script.setInput(input);
script.forEach(output);
output.copyTo(inputBitmap);
return inputBitmap;
}
}
19
Source : BlurTransformation.java
with Apache License 2.0
from SkySeraph-XKnife
with Apache License 2.0
from SkySeraph-XKnife
/**
* Created by SkySeraph on 2016/8/8.
* 图像模糊
*/
public clreplaced BlurTransformation extends BitmapTransformation {
private RenderScript rs;
/**
* Instantiates a new Blur transformation.
*
* @param context the context
*/
public BlurTransformation(Context context) {
super(context);
rs = RenderScript.create(context);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
Bitmap blurredBitmap = toTransform.copy(Bitmap.Config.ARGB_8888, true);
// Allocate memory for Renderscript to work with
Allocation input = Allocation.createFromBitmap(rs, blurredBitmap, Allocation.MipmapControl.MIPMAP_FULL, Allocation.USAGE_SHARED);
Allocation output = Allocation.createTyped(rs, input.getType());
// Load up an instance of the specific script that we want to use.
ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
script.setInput(input);
// Set the blur radius
script.setRadius(10);
// Start the ScriptIntrinisicBlur
script.forEach(output);
// Copy the output to the blurred bitmap
output.copyTo(blurredBitmap);
toTransform.recycle();
return blurredBitmap;
}
@Override
public String getId() {
return "blur";
}
}
19
Source : BlurTransformation.java
with GNU General Public License v3.0
from qiusunshine
with GNU General Public License v3.0
from qiusunshine
public clreplaced BlurTransformation extends BitmapTransformation {
private RenderScript rs;
private int radius;
public BlurTransformation(Context context, int radius) {
super();
rs = RenderScript.create(context);
this.radius = radius;
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {
Bitmap blurredBitmap = toTransform.copy(Bitmap.Config.ARGB_8888, true);
// Allocate memory for Renderscript to work with
// 分配用于渲染脚本的内存
Allocation input = Allocation.createFromBitmap(rs, blurredBitmap, Allocation.MipmapControl.MIPMAP_FULL, Allocation.USAGE_SHARED);
Allocation output = Allocation.createTyped(rs, input.getType());
// Load up an instance of the specific script that we want to use.
// 加载我们想要使用的特定脚本的实例。
ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
script.setInput(input);
// Set the blur radius
// 设置模糊半径
script.setRadius(radius);
// Start the ScriptIntrinsicBlur
// 启动 ScriptIntrinsicBlur,
script.forEach(output);
// Copy the output to the blurred bitmap
// 将输出复制到模糊的位图
output.copyTo(blurredBitmap);
return blurredBitmap;
}
@Override
public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {
messageDigest.update("blur transformation".getBytes());
}
}
19
Source : BlurTransformation.java
with GNU General Public License v3.0
from mollyim
with GNU General Public License v3.0
from mollyim
public final clreplaced BlurTransformation extends BitmapTransformation {
public static final float MAX_RADIUS = 25f;
private final RenderScript rs;
private final float bitmapScaleFactor;
private final float blurRadius;
public BlurTransformation(@NonNull Context context, float bitmapScaleFactor, float blurRadius) {
rs = RenderScript.create(context);
Preconditions.checkArgument(blurRadius >= 0 && blurRadius <= 25, "Blur radius must be a non-negative value less than or equal to 25.");
Preconditions.checkArgument(bitmapScaleFactor > 0, "Bitmap scale factor must be a non-negative value");
this.bitmapScaleFactor = bitmapScaleFactor;
this.blurRadius = blurRadius;
}
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
Matrix scaleMatrix = new Matrix();
scaleMatrix.setScale(bitmapScaleFactor, bitmapScaleFactor);
Bitmap blurredBitmap = Bitmap.createBitmap(toTransform, 0, 0, outWidth, outHeight, scaleMatrix, true);
Allocation input = Allocation.createFromBitmap(rs, blurredBitmap, Allocation.MipmapControl.MIPMAP_FULL, Allocation.USAGE_SHARED);
Allocation output = Allocation.createTyped(rs, input.getType());
ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
script.setInput(input);
script.setRadius(blurRadius);
script.forEach(output);
output.copyTo(blurredBitmap);
return blurredBitmap;
}
@Override
public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {
messageDigest.update(String.format(Locale.US, "blur-%f-%f", bitmapScaleFactor, blurRadius).getBytes());
}
}
19
Source : BlurTask.java
with MIT License
from lvlrSajjad
with MIT License
from lvlrSajjad
static private Drawable screenShot(ReactApplicationContext reactContext, RenderScript rs, Bitmap b1, int radius, float factor, float brightness) {
try {
b1 = blur(rs, b1, radius, brightness, factor);
return new BitmapDrawable(reactContext.getResources(), b1);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
19
Source : MainActivity.java
with Mozilla Public License 2.0
from KernelErr
with Mozilla Public License 2.0
from KernelErr
public clreplaced MainActivity extends FlutterActivity {
private static final String CHANNEL = "paddlelite";
private static boolean modalLoaded = false;
protected static Predictor predictor = new Predictor();
private RenderScript rs;
// Model settings of object detection
protected String modelPath = "models/fruit";
protected String labelPath = "labels/fruit_label_list";
protected int cpuThreadNum = 8;
protected String cpuPowerMode = "LITE_POWER_FULL";
protected String inputColorFormat = "RGB";
protected long[] inputShape = new long[] { 1, 3, 608, 608 };
protected float[] inputMean = new float[] { 0.485f, 0.456f, 0.406f };
protected float[] inputStd = new float[] { 0.229f, 0.224f, 0.225f };
protected float scoreThreshold = 0.5f;
@Override
public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
rs = RenderScript.create(this);
super.configureFlutterEngine(flutterEngine);
new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL).setMethodCallHandler((call, result) -> {
if (call.method.equals("loadModel")) {
loadModel(result);
} else if (call.method.equals("detectObject")) {
HashMap image = call.arguments();
detectObject(image, result);
} else {
result.notImplemented();
}
});
}
protected void loadModel(final Result result) {
new Thread(new Runnable() {
public void run() {
try {
predictor.init(MainActivity.this, modelPath, labelPath, cpuThreadNum, cpuPowerMode, inputColorFormat, inputShape, inputMean, inputStd, scoreThreshold, rs);
modalLoaded = true;
MethodResultWrapper resultWrapper = new MethodResultWrapper(result);
resultWrapper.success("Modal Loaded Sucessfully");
} catch (Exception e) {
e.printStackTrace();
MethodResultWrapper resultWrapper = new MethodResultWrapper(result);
resultWrapper.error("Modal failed to loaded", e.getMessage(), null);
}
}
}).start();
}
public void detectObject(final HashMap image, final Result result) {
new Thread(new Runnable() {
public void run() {
MethodResultWrapper resultWrapper = new MethodResultWrapper(result);
if (!modalLoaded)
resultWrapper.error("Model is not loaded", null, null);
try {
predictor.setInputImage(image);
List<Object> prediction = predictor.runModel();
resultWrapper.success(prediction);
} catch (Exception e) {
e.printStackTrace();
resultWrapper.error("Running model failed", e.getMessage(), null);
}
}
}).start();
}
private static clreplaced MethodResultWrapper implements MethodChannel.Result {
private MethodChannel.Result methodResult;
private Handler handler;
MethodResultWrapper(MethodChannel.Result result) {
methodResult = result;
handler = new Handler(Looper.getMainLooper());
}
@Override
public void success(final Object result) {
handler.post(new Runnable() {
@Override
public void run() {
methodResult.success(result);
}
});
}
@Override
public void error(final String errorCode, final String errorMessage, final Object errorDetails) {
handler.post(new Runnable() {
@Override
public void run() {
methodResult.error(errorCode, errorMessage, errorDetails);
}
});
}
@Override
public void notImplemented() {
handler.post(new Runnable() {
@Override
public void run() {
methodResult.notImplemented();
}
});
}
}
}
19
Source : BlurTransformation.java
with MIT License
from Kashish-Sharma
with MIT License
from Kashish-Sharma
/**
* Created by Kashish on 09-06-2018.
*/
public clreplaced BlurTransformation extends BitmapTransformation {
private RenderScript rs;
public BlurTransformation(Context context) {
super();
rs = RenderScript.create(context);
}
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
Bitmap blurredBitmap = toTransform.copy(Bitmap.Config.ARGB_8888, true);
// Allocate memory for Renderscript to work with
Allocation input = Allocation.createFromBitmap(rs, blurredBitmap, Allocation.MipmapControl.MIPMAP_FULL, Allocation.USAGE_SHARED);
Allocation output = Allocation.createTyped(rs, input.getType());
// Load up an instance of the specific script that we want to use.
ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
script.setInput(input);
// Set the blur radius
script.setRadius(10);
// Start the ScriptIntrinisicBlur
script.forEach(output);
// Copy the output to the blurred bitmap
output.copyTo(blurredBitmap);
return blurredBitmap;
}
@Override
public void updateDiskCacheKey(MessageDigest messageDigest) {
messageDigest.update("blur transformation".getBytes());
}
}
19
Source : ImageSegmentationTransactor.java
with Apache License 2.0
from HMS-Core
with Apache License 2.0
from HMS-Core
public void setRenderScript(RenderScript renderScript) {
this.renderScript = renderScript;
}
19
Source : Region.java
with Apache License 2.0
from googlecodelabs
with Apache License 2.0
from googlecodelabs
/**
* This function only replacedumes mPointsXY, mPasteOffX, mPasteOffY
*
* @param healing
* @param rs
* @param image
*/
public void heal(ScriptC_healing healing, RenderScript rs, Bitmap image, Bitmap output) {
Healing h = new Healing(mFindRegion.getRoiBounds(), mPointsXY, mFindRegion.getCutOffsetX(), mFindRegion.getCutOffsetY());
h.heal(healing, rs, image, output);
mUndoBitmap = h.getmUndoBitmap();
}
19
Source : GpuModel.java
with MIT License
from csarron
with MIT License
from csarron
/**
* Created by qqcao on 5/11/17Thursday.
*
* LSTM model on GPU
*/
clreplaced GpuModel extends AbstractModel {
private RenderScript mRs;
private ScriptC_main scriptC_main;
GpuModel(Context context, int layerSize, int hiddenUnits) {
super(context, layerSize, hiddenUnits);
mRs = RenderScript.create(mContext, RenderScript.ContextType.NORMAL);
scriptC_main = new ScriptC_main(mRs);
// initialize model parameters(weights and biases) allocation
initializeParamsAllocation();
allocIntermediateVariables();
}
@Override
protected int predictLabel(float[] x) {
if (mRs == null) {
return -1;
}
scriptC_main.set_time_steps(mTimeSteps);
scriptC_main.set_in_dim(mInputDim);
scriptC_main.set_hidden_unites(mHiddenUnits);
scriptC_main.set_layer_size(mLayerSize);
// initialize input raw data allocation
Type inRawType = Type.createXY(mRs, Element.F32(mRs), mInputDim, mTimeSteps);
Allocation inputRawAlloc = Allocation.createTyped(mRs, inRawType);
inputRawAlloc.copyFrom(x);
scriptC_main.set_input_raw(inputRawAlloc);
// initialize activated input data allocation
Type cellDataType = Type.createXY(mRs, Element.F32(mRs), mHiddenUnits, mTimeSteps);
Allocation inputsAlloc = Allocation.createTyped(mRs, cellDataType);
scriptC_main.set_inputs(inputsAlloc);
// initialize label probability output allocation
Allocation labelProbAlloc = Allocation.createSized(mRs, Element.F32(mRs), mOutputDim);
scriptC_main.bind_label_prob(labelProbAlloc);
scriptC_main.set_out_dim(mOutputDim);
// begin model forward preplaced computation
long start = System.currentTimeMillis();
scriptC_main.invoke_all_in_one();
mRs.finish();
long end = System.currentTimeMillis();
// copy result back
float[] labelProb = new float[mOutputDim];
labelProbAlloc.copyTo(labelProb);
Logger.i("invoke time: %s", (end - start));
return DataUtil.argmax(labelProb) + 1;
}
private void initializeParamsAllocation() {
Type wInType = Type.createXY(mRs, Element.F32(mRs), mHiddenUnits, mInputDim);
Allocation wInAlloc = Allocation.createTyped(mRs, wInType);
wInAlloc.copyFrom(mWIn);
scriptC_main.set_w_in(wInAlloc);
Allocation bInAlloc = Allocation.createSized(mRs, Element.F32(mRs), mHiddenUnits);
bInAlloc.copyFrom(mBIn);
scriptC_main.set_b_in(bInAlloc);
Type wOutType = Type.createXY(mRs, Element.F32(mRs), mOutputDim, mHiddenUnits);
Allocation wOutAlloc = Allocation.createTyped(mRs, wOutType);
wOutAlloc.copyFrom(mWOut);
scriptC_main.set_w_out(wOutAlloc);
Allocation bOutAlloc = Allocation.createSized(mRs, Element.F32(mRs), mOutputDim);
bOutAlloc.copyFrom(mBOut);
scriptC_main.set_b_out(bOutAlloc);
Type weightType = Type.createXYZ(mRs, Element.F32(mRs), mHiddenUnits * 4, mHiddenUnits * 2, mLayerSize);
Allocation weightAlloc = Allocation.createTyped(mRs, weightType);
weightAlloc.copyFrom(alter2Dto1D(mRnnWeights));
scriptC_main.set_weights(weightAlloc);
Type biasType = Type.createXY(mRs, Element.F32(mRs), mHiddenUnits * 4, mLayerSize);
Allocation biasAlloc = Allocation.createTyped(mRs, biasType);
biasAlloc.copyFrom(alter2Dto1D(mRnnBiases));
scriptC_main.set_biases(biasAlloc);
}
private void allocIntermediateVariables() {
Allocation cAlloc = Allocation.createSized(mRs, Element.F32(mRs), mHiddenUnits);
scriptC_main.bind_c(cAlloc);
Allocation hAlloc = Allocation.createSized(mRs, Element.F32(mRs), mHiddenUnits);
scriptC_main.bind_h(hAlloc);
Allocation inputConcatAlloc = Allocation.createSized(mRs, Element.F32(mRs), mHiddenUnits * 2);
scriptC_main.bind_input_concat(inputConcatAlloc);
Allocation linearResultAlloc = Allocation.createSized(mRs, Element.F32(mRs), mHiddenUnits * 4);
scriptC_main.bind_linear_result(linearResultAlloc);
}
}
19
Source : Layer.java
with MIT License
from chuanqi305
with MIT License
from chuanqi305
public final void setRenderScript(RenderScript renderScript) {
this.renderScript = renderScript;
if (scriptIntrinsicBLAS == null) {
scriptIntrinsicBLAS = ScriptIntrinsicBLAS.create(renderScript);
}
}
19
Source : NMS.java
with MIT License
from chuanqi305
with MIT License
from chuanqi305
public clreplaced NMS {
private final static float INVALID_ANCHOR = -10000.0f;
private RenderScript renderScript;
public NMS(RenderScript renderScript) {
this.renderScript = renderScript;
}
private static void quickSortScore(float[][] anchors, float[] scores, int left, int right) {
int dp;
if (left < right) {
dp = parreplacedionScore(anchors, scores, left, right);
quickSortScore(anchors, scores, left, dp - 1);
quickSortScore(anchors, scores, dp + 1, right);
}
}
private static int parreplacedionScore(float[][] anchors, float[] scores, int left, int right) {
float pivot = scores[left];
float[] pivotA = anchors[left];
while (left < right) {
while (left < right && scores[right] <= pivot) right--;
if (left < right) {
anchors[left] = anchors[right];
scores[left++] = scores[right];
}
while (left < right && scores[left] >= pivot) left++;
if (left < right) {
anchors[right] = anchors[left];
scores[right--] = scores[left];
}
}
scores[left] = pivot;
anchors[left] = pivotA;
return left;
}
private static float computeOverlapAreaRate(float[] anchor1, float[] anchor2) {
float xx1 = anchor1[0] > anchor2[0] ? anchor1[0] : anchor2[0];
float yy1 = anchor1[1] > anchor2[1] ? anchor1[1] : anchor2[1];
float xx2 = anchor1[2] < anchor2[2] ? anchor1[2] : anchor2[2];
float yy2 = anchor1[3] < anchor2[3] ? anchor1[3] : anchor2[3];
float w = xx2 - xx1 + 1;
float h = yy2 - yy1 + 1;
if (w < 0 || h < 0) {
return 0;
}
float inter = w * h;
float anchor1_area1 = (anchor1[2] - anchor1[0] + 1) * (anchor1[3] - anchor1[1] + 1);
float anchor2_area1 = (anchor2[2] - anchor2[0] + 1) * (anchor2[3] - anchor2[1] + 1);
return inter / (anchor1_area1 + anchor2_area1 - inter);
}
public static int[] nmsScoreFilter(float[][] anchors, float[] score, int topN, float thresh) {
int length = anchors.length;
int count = 0;
for (int i = 0; i < length; i++) {
if (score[i] == INVALID_ANCHOR) {
continue;
}
if (++count >= topN) {
break;
}
for (int j = i + 1; j < length; j++) {
if (score[j] != INVALID_ANCHOR) {
if (computeOverlapAreaRate(anchors[i], anchors[j]) > thresh) {
score[j] = INVALID_ANCHOR;
}
}
}
}
int[] outputIndex = new int[count];
int j = 0;
for (int i = 0; i < length && count > 0; i++) {
if (score[i] != INVALID_ANCHOR) {
outputIndex[j++] = i;
count--;
}
}
return outputIndex;
}
public static void sortScores(float[][] anchors, float[] scores) {
quickSortScore(anchors, scores, 0, scores.length - 1);
}
}
19
Source : BlurKit.java
with MIT License
from CameraKit
with MIT License
from CameraKit
public clreplaced BlurKit {
private static final float FULL_SCALE = 1f;
private static BlurKit instance;
private static RenderScript rs;
public static void init(Context context) {
if (instance != null) {
return;
}
instance = new BlurKit();
rs = RenderScript.create(context.getApplicationContext());
}
public Bitmap blur(Bitmap src, int radius) {
final Allocation input = Allocation.createFromBitmap(rs, src);
final Allocation output = Allocation.createTyped(rs, input.getType());
final ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
script.setRadius(radius);
script.setInput(input);
script.forEach(output);
output.copyTo(src);
return src;
}
public Bitmap blur(View src, int radius) {
Bitmap bitmap = getBitmapForView(src);
return blur(bitmap, radius);
}
public Bitmap fastBlur(View src, int radius, float downscaleFactor) {
Bitmap bitmap = getBitmapForView(src, downscaleFactor);
return blur(bitmap, radius);
}
private Bitmap getBitmapForView(View src, float downscaleFactor) {
Bitmap bitmap = Bitmap.createBitmap((int) (src.getWidth() * downscaleFactor), (int) (src.getHeight() * downscaleFactor), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Matrix matrix = new Matrix();
matrix.preScale(downscaleFactor, downscaleFactor);
canvas.setMatrix(matrix);
src.draw(canvas);
return bitmap;
}
private Bitmap getBitmapForView(View src) {
Bitmap bitmap = Bitmap.createBitmap(src.getWidth(), src.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
src.draw(canvas);
return bitmap;
}
public static BlurKit getInstance() {
if (instance == null) {
throw new RuntimeException("BlurKit not initialized!");
}
return instance;
}
}
19
Source : BlurBitmap.java
with Apache License 2.0
from androidx
with Apache License 2.0
from androidx
/**
* Allows to run a blur script on a bitmap using {@link RenderScript}. After testing on a
* couple of devices (both low end and high end), it seems as though blurring an image typically
* takes a couple of frames, about 3-4.
*/
clreplaced BlurBitmap {
private static final int BLUR_RADIUS = 25;
private final RenderScript mRenderScript;
private final ScriptIntrinsicBlur mBlurScript;
BlurBitmap(@NonNull Context context) {
// Create renderScript
mRenderScript = RenderScript.create(context);
// Create blur script
mBlurScript = ScriptIntrinsicBlur.create(mRenderScript, Element.U8_4(mRenderScript));
mBlurScript.setRadius(BLUR_RADIUS);
}
void blur(@NonNull Bitmap bitmap) {
// Create input and output allocation
final Allocation allocation = Allocation.createFromBitmap(mRenderScript, bitmap);
// Perform blur effect, then copy script result to bitmap
mBlurScript.setInput(allocation);
mBlurScript.forEach(allocation);
allocation.copyTo(bitmap);
// clean up
allocation.destroy();
}
void clear() {
mBlurScript.destroy();
mRenderScript.destroy();
}
}
18
Source : CachingPipeline.java
with Apache License 2.0
from yuchuangu85
with Apache License 2.0
from yuchuangu85
private synchronized boolean updateOriginalAllocation(ImagePreset preset) {
if (preset == null) {
return false;
}
Bitmap originalBitmap = mOriginalBitmap;
if (originalBitmap == null) {
return false;
}
RenderScript RS = getRenderScriptContext();
Allocation filtersOnlyOriginalAllocation = mFiltersOnlyOriginalAllocation;
mFiltersOnlyOriginalAllocation = Allocation.createFromBitmap(RS, originalBitmap, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT);
if (filtersOnlyOriginalAllocation != null) {
filtersOnlyOriginalAllocation.destroy();
}
Allocation originalAllocation = mOriginalAllocation;
mResizedOriginalBitmap = preset.applyGeometry(originalBitmap, mEnvironment);
mOriginalAllocation = Allocation.createFromBitmap(RS, mResizedOriginalBitmap, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT);
if (originalAllocation != null) {
originalAllocation.destroy();
}
return true;
}
18
Source : CachingPipeline.java
with Apache License 2.0
from yuchuangu85
with Apache License 2.0
from yuchuangu85
public boolean prepareRenderscriptAllocations(Bitmap bitmap) {
RenderScript RS = getRenderScriptContext();
boolean needsUpdate = false;
if (mOutPixelsAllocation == null || mInPixelsAllocation == null || bitmap.getWidth() != mWidth || bitmap.getHeight() != mHeight) {
destroyPixelAllocations();
Bitmap bitmapBuffer = bitmap;
if (bitmap.getConfig() == null || bitmap.getConfig() != BITMAP_CONFIG) {
bitmapBuffer = bitmap.copy(BITMAP_CONFIG, true);
}
mOutPixelsAllocation = Allocation.createFromBitmap(RS, bitmapBuffer, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT);
mInPixelsAllocation = Allocation.createTyped(RS, mOutPixelsAllocation.getType());
needsUpdate = true;
}
if (RS != null) {
mInPixelsAllocation.copyFrom(bitmap);
}
if (bitmap.getWidth() != mWidth || bitmap.getHeight() != mHeight) {
mWidth = bitmap.getWidth();
mHeight = bitmap.getHeight();
needsUpdate = true;
}
if (DEBUG) {
Log.v(LOGTAG, "prepareRenderscriptAllocations: " + needsUpdate + " in " + getName());
}
return needsUpdate;
}
18
Source : ImageFilterVignette.java
with Apache License 2.0
from yuchuangu85
with Apache License 2.0
from yuchuangu85
@Override
protected void createFilter(Resources res, float scaleFactor, int quality) {
RenderScript rsCtx = getRenderScriptContext();
mScript = new ScriptC_vignette(rsCtx);
}
18
Source : ImageFilterGrad.java
with Apache License 2.0
from yuchuangu85
with Apache License 2.0
from yuchuangu85
private boolean checkStop() {
RenderScript rsCtx = getRenderScriptContext();
rsCtx.finish();
if (getEnvironment().needsStop()) {
return true;
}
return false;
}
18
Source : RenderscriptWrapper.java
with Apache License 2.0
from upost
with Apache License 2.0
from upost
private void createAllocations(RenderScript rs) {
mOutBufferInt = new int[mSizeVideoCall.getWidth() * mSizeVideoCall.getHeight()];
final int width = mSizeVideoCall.getWidth();
final int height = mSizeVideoCall.getHeight();
Type.Builder yuvTypeBuilder = new Type.Builder(rs, Element.YUV(rs));
yuvTypeBuilder.setX(width);
yuvTypeBuilder.setY(height);
yuvTypeBuilder.setYuvFormat(ImageFormat.YUV_420_888);
mInputAllocation = Allocation.createTyped(rs, yuvTypeBuilder.create(), Allocation.USAGE_IO_INPUT | Allocation.USAGE_SCRIPT);
Type rgbType = Type.createXY(rs, Element.RGBA_8888(rs), width, height);
Type intType = Type.createXY(rs, Element.U32(rs), width, height);
mScriptAllocation = Allocation.createTyped(rs, rgbType, Allocation.USAGE_SCRIPT);
// dummy allocation because it may not be null
mOutputAllocation = Allocation.createTyped(rs, rgbType, Allocation.USAGE_SCRIPT);
mFirstFrameAllocation = Allocation.createTyped(rs, intType, Allocation.USAGE_SCRIPT);
// actual output allocation
mOutputAllocationInt = Allocation.createTyped(rs, intType, Allocation.USAGE_SCRIPT);
}
18
Source : StackRenderScript.java
with Apache License 2.0
from robinxdroid
with Apache License 2.0
from robinxdroid
/**
* Created by Robin on 2016/7/23 17:13.
*/
public clreplaced StackRenderScript {
private static volatile StackRenderScript INSTANCE = null;
public static StackRenderScript getInstance(Context context) {
if (INSTANCE == null) {
synchronized (StackRenderScript.clreplaced) {
if (INSTANCE == null) {
INSTANCE = new StackRenderScript(context.getApplicationContext());
}
}
}
return INSTANCE;
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private StackRenderScript(Context context) {
mRenderScript = RenderScript.create(context);
mBlurScript = ScriptIntrinsicBlur.create(mRenderScript, Element.U8_4(mRenderScript));
}
private RenderScript mRenderScript;
private ScriptIntrinsicBlur mBlurScript;
private Allocation mBlurInput, mBlurOutput;
/**
* @param bitmap
* @param radius 0~25
* @return
*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public Bitmap blur(Bitmap bitmap, int radius) {
if (radius < 1) {
return (null);
}
// Return this none blur
if (radius == 1) {
return bitmap;
}
if (radius > 25) {
radius = 25;
}
mBlurScript.setRadius(radius);
mBlurInput = Allocation.createFromBitmap(mRenderScript, bitmap, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT);
mBlurOutput = Allocation.createTyped(mRenderScript, mBlurInput.getType());
// mBlurInput.copyFrom(bitmap);
mBlurScript.setInput(mBlurInput);
mBlurScript.forEach(mBlurOutput);
mBlurOutput.copyTo(bitmap);
return (bitmap);
}
}
18
Source : SajjadBlurOverlayManager.java
with MIT License
from lvlrSajjad
with MIT License
from lvlrSajjad
public clreplaced SajjadBlurOverlayManager extends ViewGroupManager<ReactViewGroup> {
private static final String REACT_CLreplaced = "RCTSajjadBlurOverlay";
private final ReactApplicationContext reactContext;
private int mRadius = 20;
private float mBrightness = 0;
private float mFactor = 1;
private RenderScript rs;
SajjadBlurOverlayManager(ReactApplicationContext reactContext) {
this.reactContext = reactContext;
this.rs = RenderScript.create(reactContext);
}
@Override
public String getName() {
return REACT_CLreplaced;
}
@Override
protected ReactViewGroup createViewInstance(ThemedReactContext reactContext) {
return new ReactViewGroup(reactContext);
}
@ReactProp(name = "radius")
public void setRadius(ReactViewGroup view, int Radius) {
mRadius = Radius;
}
@ReactProp(name = "downsampling")
public void setRadius(ReactViewGroup view, float factor) {
mFactor = factor;
}
private void setBlurred(final View view) {
final Activity activity = reactContext.getCurrentActivity();
if (activity == null)
return;
new BlurTask(view, reactContext, rs, activity, mRadius, mFactor, mBrightness).execute();
}
@ReactProp(name = "brightness")
public void setBrightness(ReactViewGroup view, float brightness) {
mBrightness = brightness;
setBlurred(view);
view.requestFocus();
}
}
18
Source : ImageUtils.java
with Apache License 2.0
from librahfacebook
with Apache License 2.0
from librahfacebook
/**
* 实现图片的高斯模糊
*/
public static Bitmap blur(Bitmap bitmap, float radius, Activity activity) {
// 创建输出图片
Bitmap output = Bitmap.createBitmap(bitmap);
// 构建该对象
RenderScript rs = RenderScript.create(activity);
// 创建高斯模糊脚本
ScriptIntrinsicBlur gaussianBlur = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
// 创建用于输入的脚本类型
Allocation allIn = Allocation.createFromBitmap(rs, bitmap);
// 创建用于输出的脚本类型
Allocation allOut = Allocation.createFromBitmap(rs, output);
// 设置模糊半径
gaussianBlur.setRadius(radius);
// 设置输入脚本类型
gaussianBlur.setInput(allIn);
// 执行高斯模糊算法
gaussianBlur.forEach(allOut);
// 输出内存编码
allOut.copyTo(output);
rs.destroy();
return output;
}
18
Source : Predictor.java
with Mozilla Public License 2.0
from KernelErr
with Mozilla Public License 2.0
from KernelErr
public boolean init(Context appCtx, String modelPath, String labelPath, int cpuThreadNum, String cpuPowerMode, String inputColorFormat, long[] inputShape, float[] inputMean, float[] inputStd, float scoreThreshold, RenderScript rs) {
this.rs = rs;
if (inputShape.length != 4) {
Log.i(TAG, "Size of input shape should be: 4");
return false;
}
if (inputMean.length != inputShape[1]) {
Log.i(TAG, "Size of input mean should be: " + Long.toString(inputShape[1]));
return false;
}
if (inputStd.length != inputShape[1]) {
Log.i(TAG, "Size of input std should be: " + Long.toString(inputShape[1]));
return false;
}
if (inputShape[0] != 1) {
Log.i(TAG, "Only one batch is supported in the image clreplacedification demo, you can use any batch size in " + "your Apps!");
return false;
}
if (inputShape[1] != 1 && inputShape[1] != 3) {
Log.i(TAG, "Only one/three channels are supported in the image clreplacedification demo, you can use any " + "channel size in your Apps!");
return false;
}
if (!inputColorFormat.equalsIgnoreCase("RGB") && !inputColorFormat.equalsIgnoreCase("BGR")) {
Log.i(TAG, "Only RGB and BGR color format is supported.");
return false;
}
isLoaded = loadModel(appCtx, modelPath, cpuThreadNum, cpuPowerMode);
if (!isLoaded) {
return false;
}
isLoaded = loadLabel(appCtx, labelPath);
if (!isLoaded) {
return false;
}
this.inputColorFormat = inputColorFormat;
this.inputShape = inputShape;
this.inputMean = inputMean;
this.inputStd = inputStd;
this.scoreThreshold = scoreThreshold;
return true;
}
18
Source : BitmapUtils.java
with Apache License 2.0
from jiangzhongbo
with Apache License 2.0
from jiangzhongbo
/**
* RenderScript局部模糊
*
* @param context
* 上下文
* @param bitmap
* 模糊位图
* @param view
* 模糊区域
* @param radius
* 模糊半径
*/
@SuppressLint("NewApi")
public static void blurByRender(Context context, Bitmap bitmap, View view, float radius) {
// 得到要处理的区域
Bitmap dstArea = getDstArea(bitmap, view);
dstArea = zoomImage(dstArea, 0.8f);
// 作模糊处理
RenderScript rs = RenderScript.create(context);
Allocation overlayAlloc = Allocation.createFromBitmap(rs, dstArea);
ScriptIntrinsicBlur blur = ScriptIntrinsicBlur.create(rs, overlayAlloc.getElement());
blur.setInput(overlayAlloc);
blur.setRadius(radius);
blur.forEach(overlayAlloc);
overlayAlloc.copyTo(dstArea);
// 设置背景
view.setBackground(new BitmapDrawable(context.getResources(), dstArea));
bitmap.recycle();
rs.destroy();
}
18
Source : FindRegion.java
with Apache License 2.0
from googlecodelabs
with Apache License 2.0
from googlecodelabs
Allocation allocFloat2(float[] p, RenderScript rs) {
Type.Builder builderF32_2 = new Type.Builder(rs, Element.F32_2(rs));
builderF32_2.setX(p.length / 2);
Allocation ret = Allocation.createTyped(rs, builderF32_2.create());
ret.copyFrom(p);
return ret;
}
18
Source : StackAvgOperator.java
with Apache License 2.0
from ConvergenceSoftware
with Apache License 2.0
from ConvergenceSoftware
/**
* 按照权重比例合成图像
*
* @param bitmap 当前获取的图像Bitmap
* @return 合成是否成功
*/
private boolean compoundImg(Bitmap bitmap) {
float beta = ((float) step - 1) / (float) step;
float alpha = 1.0f - beta;
RenderScript renderScript = RenderScript.create(context);
ScriptC_PixelOperation scaleScriptIn = new ScriptC_PixelOperation(renderScript);
ScriptC_PixelOperation scaleScriptOut = new ScriptC_PixelOperation(renderScript);
ScriptIntrinsicBlend blendScript = ScriptIntrinsicBlend.create(renderScript, Element.U8_4(renderScript));
Allocation inputAllocation = Allocation.createFromBitmap(renderScript, bitmap);
Allocation outputAllocation = Allocation.createFromBitmap(renderScript, tempBitmap);
scaleScriptIn.set_alpha(beta);
scaleScriptIn.forEach_scale(inputAllocation, inputAllocation);
scaleScriptOut.set_alpha(alpha);
scaleScriptOut.forEach_scale(outputAllocation, outputAllocation);
blendScript.forEachAdd(inputAllocation, outputAllocation);
outputAllocation.copyTo(tempBitmap);
return true;
}
18
Source : MainActivity.java
with MIT License
from chuanqi305
with MIT License
from chuanqi305
public clreplaced MainActivity extends AppCompatActivity {
private RenderScript rs;
private ObjectDetector detector = null;
private String modelPath = "mobilenet-ssd";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rs = RenderScript.create(this);
try {
replacedetManager replacedetManager = getreplacedets();
String[] fileList = replacedetManager.list(modelPath);
if (fileList.length != 0) {
detector = new MobileNetSSD(rs, replacedetManager, modelPath);
} else {
String modelDir = Environment.getExternalStorageDirectory().getPath() + "/" + modelPath;
detector = new MobileNetSSD(rs, null, modelDir);
}
} catch (IOException e) {
e.printStackTrace();
}
setContentView(R.layout.activity_main);
}
public void btnClicked(View view) {
Intent intent;
intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 0);
}
private Bitmap cropImage(Bitmap image) {
int height = image.getHeight();
int width = image.getWidth();
int newHeight = height;
int newWidth = width;
int x = 0;
int y = 0;
if (height > width) {
newHeight = width;
y = (height - newHeight) / 2;
} else {
newWidth = height;
x = (width - newWidth) / 2;
}
return Bitmap.createBitmap(image, x, y, newWidth, newHeight);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data == null) {
return;
}
try {
ContentResolver resolver = this.getContentResolver();
Uri uri = data.getData();
Bitmap bmp = MediaStore.Images.Media.getBitmap(resolver, uri);
Bitmap image = cropImage(bmp);
ImageView img = (ImageView) findViewById(R.id.imageView);
List<DetectResult> result = detector.detect(image);
Bitmap toDraw = PhotoViewHelper.drawTextAndRect(image, result);
img.setImageBitmap(toDraw);
} catch (IOException e) {
e.printStackTrace();
}
}
}
18
Source : Layer.java
with MIT License
from chuanqi305
with MIT License
from chuanqi305
public abstract clreplaced Layer {
protected RenderScript renderScript;
protected static ScriptIntrinsicBLAS scriptIntrinsicBLAS;
protected boolean selfConnected = false;
protected int[][] inputShape;
protected int[] outputShape;
protected Object[] featureMapInput;
protected Object featureMapOutput;
private boolean ready = false;
protected String name;
protected int getInputChannelAligned() {
int ca = inputShape[0][3];
if (ca % 4 != 0) {
ca = ca + 4 - ca % 4;
}
return ca;
}
protected int getOutputChannelAligned() {
int ca = outputShape[3];
if (ca % 4 != 0) {
ca = ca + 4 - ca % 4;
}
return ca;
}
// tensorflow pooling implement is different from caffe
protected static boolean weightFromTensorFlow = false;
// tensorflow reshape use NHWC, caffe use NCHW
protected static boolean reshapeFromTensorFlow = false;
public boolean isReady() {
return ready;
}
public void setReady(boolean ready) {
this.ready = ready;
}
public static void setWeightFromTensorFlow(boolean weightFromTensorFlow) {
Layer.weightFromTensorFlow = weightFromTensorFlow;
}
public static void setReshapeFromTensorFlow(boolean reshapeFromTensorFlow) {
Layer.reshapeFromTensorFlow = reshapeFromTensorFlow;
}
public void setName(String name) {
this.name = name;
}
/**
* layer is self-connected and can be processed on the input buffer, do not alloc new memory
* @param selfConnected
*/
public void setSelfConnected(boolean selfConnected) {
this.selfConnected = selfConnected;
}
/**
* if the layer is not last layer but has something output
* @return
*/
public boolean needOutput() {
return false;
}
/**
* do some initialize after all parameters are set
*/
public void setup() {
}
public final void setRenderScript(RenderScript renderScript) {
this.renderScript = renderScript;
if (scriptIntrinsicBLAS == null) {
scriptIntrinsicBLAS = ScriptIntrinsicBLAS.create(renderScript);
}
}
protected void allocFeatureMap() {
Type.Builder outputType = new Type.Builder(renderScript, Element.F32(renderScript));
outputType.setZ(outputShape[0]);
outputType.setY(outputShape[1] * outputShape[2]);
outputType.setX(getOutputChannelAligned());
Allocation outAllocation = Allocation.createTyped(renderScript, outputType.create());
FeatureMap output = new FeatureMap();
output.setFeatureMap(outAllocation);
output.setN(outputShape[0]);
output.setH(outputShape[1]);
output.setW(outputShape[2]);
output.setC(outputShape[3]);
output.setPad4(true);
if (this.featureMapOutput != null) {
((FeatureMap) featureMapOutput).getFeatureMap().destroy();
}
this.featureMapOutput = output;
}
protected void allocFeatureMapNoPad() {
Type.Builder outputType = new Type.Builder(renderScript, Element.F32(renderScript));
outputType.setZ(outputShape[0]);
outputType.setY(outputShape[1] * outputShape[2]);
outputType.setX(outputShape[3]);
Allocation outAllocation = Allocation.createTyped(renderScript, outputType.create());
FeatureMap output = new FeatureMap();
output.setFeatureMap(outAllocation);
output.setN(outputShape[0]);
output.setH(outputShape[1]);
output.setW(outputShape[2]);
output.setC(outputShape[3]);
output.setPad4(false);
if (this.featureMapOutput != null) {
((FeatureMap) featureMapOutput).getFeatureMap().destroy();
}
this.featureMapOutput = output;
}
protected Script.LaunchOptions getLaunchOptionVector4() {
Script.LaunchOptions options = new Script.LaunchOptions();
options.setX(0, getOutputChannelAligned() / 4).setY(0, outputShape[1] * outputShape[2]);
return options;
}
protected void allocFeatureMapBlock4() {
int outNum = outputShape[0];
int outHeight = outputShape[1];
int outWidth = outputShape[2];
int outChannel = outputShape[3];
int outChannelAlign = outChannel;
if (outChannelAlign % 4 != 0) {
outChannelAlign = outChannel + 4 - (outChannel % 4);
}
if (featureMapOutput != null) {
FeatureMap old = (FeatureMap) featureMapOutput;
if (old.getFeatureMap() != null) {
Allocation out = old.getFeatureMap();
if (out.getBytesSize() == outNum * outHeight * outWidth * outChannelAlign * 4) {
old.setN(outNum);
old.setH(outHeight);
old.setW(outWidth);
old.setC(outChannel);
return;
} else {
out.destroy();
}
}
}
Type outType = Type.createX(renderScript, Element.F32_4(renderScript), outNum * outHeight * outWidth * outChannelAlign / 4);
// Allocation outAllocation = Allocation.createTyped(renderScript, outType, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_GRAPHICS_TEXTURE | Allocation.USAGE_SCRIPT);
Allocation outAllocation = Allocation.createTyped(renderScript, outType, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT);
FeatureMap output = new FeatureMap();
output.setFeatureMap(outAllocation);
output.setN(outNum);
output.setH(outHeight);
output.setW(outWidth);
output.setC(outChannel);
output.setPad4(true);
output.setMatrix2D(false);
featureMapOutput = output;
}
protected void allocFeatureMapNoBlock() {
int outNum = outputShape[0];
int outHeight = outputShape[1];
int outWidth = outputShape[2];
int outChannel = outputShape[3];
if (featureMapOutput != null) {
FeatureMap old = (FeatureMap) featureMapOutput;
if (old.getFeatureMap() != null) {
Allocation out = old.getFeatureMap();
if (out.getBytesSize() == outNum * outHeight * outWidth * outChannel * 4) {
old.setN(outNum);
old.setH(outHeight);
old.setW(outWidth);
old.setC(outChannel);
return;
} else {
out.destroy();
}
}
}
Type outType = Type.createX(renderScript, Element.F32(renderScript), outNum * outHeight * outWidth * outChannel);
// Allocation outAllocation = Allocation.createTyped(renderScript, outType, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_GRAPHICS_TEXTURE | Allocation.USAGE_SCRIPT);
Allocation outAllocation = Allocation.createTyped(renderScript, outType, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT);
FeatureMap output = new FeatureMap();
output.setFeatureMap(outAllocation);
output.setN(outNum);
output.setH(outHeight);
output.setW(outWidth);
output.setC(outChannel);
output.setMatrix2D(false);
featureMapOutput = output;
}
public abstract void computeFeatureMap();
public abstract void computeOutputShape();
}
18
Source : ConvNet.java
with MIT License
from chuanqi305
with MIT License
from chuanqi305
private void loadGraphFromRawData(RenderScript renderScript, replacedetManager replacedetManager, String prototxt, String dataDir) throws IOException {
LayerParser parser = new LayerParser(renderScript);
try {
if (replacedetManager != null) {
layer = parser.parseFromRawDataOnreplacedet(prototxt, replacedetManager, dataDir);
} else {
layer = parser.parseFromRawDataOnStorage(prototxt, dataDir);
}
if (layer == null) {
throw new IOException("load model error");
}
int[] inputDims = layer.getInputSize();
this.networkInputHeight = inputDims[2];
this.networkInputWidth = inputDims[3];
layer.init();
} catch (IOException e) {
LogUtil.e(TAG, "load model error");
e.printStackTrace();
throw e;
}
}
18
Source : Yuv420Image.java
with MIT License
from BioID-GmbH
with MIT License
from BioID-GmbH
private void createBitmapRepresentation() {
RenderScript rs = getRenderScript();
// ScriptIntrinsicYuvToRGB works with NV21 - U and V order reversed: it starts with V.
// Change yuv to yvu
byte[] yuvData = ByteBuffer.allocate(yPlane.length + uPlane.length + vPlane.length).put(yPlane).put(vPlane).put(uPlane).array();
ScriptIntrinsicYuvToRGB yuvToRgb = ScriptIntrinsicYuvToRGB.create(rs, Element.U8_4(rs));
Type yuvType = new Type.Builder(rs, Element.U8(rs)).setX(yuvData.length).create();
Type rgbType = new Type.Builder(rs, Element.RGBA_8888(rs)).setX(width).setY(height).create();
Allocation input = Allocation.createTyped(rs, yuvType, Allocation.USAGE_SCRIPT);
input.copyFrom(yuvData);
yuvToRgb.setInput(input);
Allocation output = Allocation.createTyped(rs, rgbType, Allocation.USAGE_SCRIPT);
yuvToRgb.forEach(output);
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
output.copyTo(bitmap);
Matrix matrix = new Matrix();
matrix.postRotate(rotation);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
bitmapRepresentation = bitmap;
}
17
Source : SwipeBackHelper.java
with GNU Lesser General Public License v3.0
from WangDaYeeeeee
with GNU Lesser General Public License v3.0
from WangDaYeeeeee
private static Bitmap blur(Context context, Bitmap source, float radius) {
RenderScript renderScript = RenderScript.create(context);
final Allocation input = Allocation.createFromBitmap(renderScript, source);
final Allocation output = Allocation.createTyped(renderScript, input.getType());
ScriptIntrinsicBlur scriptIntrinsicBlur = ScriptIntrinsicBlur.create(renderScript, Element.U8_4(renderScript));
scriptIntrinsicBlur.setInput(input);
scriptIntrinsicBlur.setRadius(radius);
scriptIntrinsicBlur.forEach(output);
output.copyTo(source);
renderScript.destroy();
return source;
}
17
Source : ImageUtil.java
with Apache License 2.0
from triline3
with Apache License 2.0
from triline3
/**
* 图片高斯模糊具体实现方法
*
* @param context
* @param image
* @param radius
*
* @return
*/
public static Bitmap blur(Context context, Bitmap image, float radius) {
// 计算图片缩小后的长宽
int width = Math.round(image.getWidth() * BITMAP_SCALE);
int height = Math.round(image.getHeight() * BITMAP_SCALE);
// 将缩小后的图片做为预渲染的图片。
Bitmap inputBitmap = Bitmap.createScaledBitmap(image, width, height, false);
// 创建一张渲染后的输出图片。
Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap);
// 创建RenderScript内核对象
RenderScript rs = RenderScript.create(context);
// 创建一个模糊效果的RenderScript的工具对象
ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
// 由于RenderScript并没有使用VM来分配内存,所以需要使用Allocation类来创建和分配内存空间。
// 创建Allocation对象的时候其实内存是空的,需要使用copyTo()将数据填充进去。
Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap);
Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap);
// 设置渲染的模糊程度, 25f是最大模糊度
blurScript.setRadius(radius);
// 设置blurScript对象的输入内存
blurScript.setInput(tmpIn);
// 将输出数据保存到输出内存中
blurScript.forEach(tmpOut);
// 将数据填充到Allocation中
tmpOut.copyTo(outputBitmap);
return outputBitmap;
}
17
Source : 图片工具.java
with GNU General Public License v3.0
from testacount1
with GNU General Public License v3.0
from testacount1
public static Bitmap 模糊(Bitmap $图片, int $半径) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
Bitmap bitmap = $图片.copy($图片.getConfig(), true);
final RenderScript rs = RenderScript.create(上下文工具.取全局上下文());
final Allocation input = Allocation.createFromBitmap(rs, $图片, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT);
final Allocation output = Allocation.createTyped(rs, input.getType());
ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
script.setRadius($半径);
script.setInput(input);
script.forEach(output);
output.copyTo(bitmap);
// clean up renderscript resources
rs.destroy();
input.destroy();
output.destroy();
script.destroy();
return bitmap;
}
return null;
}
17
Source : ImageUtil.java
with Apache License 2.0
from scatl
with Apache License 2.0
from scatl
/**
* author: TanLei
* description: 图片模糊
*/
public static Bitmap blurPhoto(Context context, Bitmap bitmap, float radius) {
Bitmap result = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
RenderScript renderScript = RenderScript.create(context);
ScriptIntrinsicBlur blur = ScriptIntrinsicBlur.create(renderScript, Element.U8_4(renderScript));
Allocation in = Allocation.createFromBitmap(renderScript, bitmap);
Allocation out = Allocation.createFromBitmap(renderScript, result);
blur.setRadius(radius);
blur.setInput(in);
blur.forEach(out);
out.copyTo(result);
renderScript.destroy();
return result;
}
17
Source : BlurTask.java
with MIT License
from lvlrSajjad
with MIT License
from lvlrSajjad
/**
* @param rs RenderScript Context
* @param image screenshot bitmap
* @param Radius integer between 1 to 24
* @param brightness -255..255 0 is default
* @return blurred Bitmap
*/
private static Bitmap blur(RenderScript rs, Bitmap image, int Radius, float brightness, float factor) {
Bitmap outputBitmap;
if (Radius > 0 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
outputBitmap = Bitmap.createBitmap(image.getWidth(), image.getHeight(), Bitmap.Config.ARGB_8888);
ScriptIntrinsicBlur theIntrinsic = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
Allocation tmpIn = Allocation.createFromBitmap(rs, image);
Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap);
theIntrinsic.setRadius(Radius / factor);
theIntrinsic.setInput(tmpIn);
theIntrinsic.forEach(tmpOut);
tmpOut.copyTo(outputBitmap);
} else {
outputBitmap = image;
}
if (brightness != 0) {
ColorMatrix cm = new ColorMatrix(new float[] { (float) 1, 0, 0, 0, brightness, 0, (float) 1, 0, 0, brightness, 0, 0, (float) 1, 0, brightness, 0, 0, 0, 1, 0 });
Canvas canvas = new Canvas(outputBitmap);
Paint paint = new Paint();
paint.setColorFilter(new ColorMatrixColorFilter(cm));
canvas.drawBitmap(outputBitmap, 0, 0, paint);
}
return outputBitmap;
}
17
Source : BaseHook.java
with MIT License
from liuzhushaonian
with MIT License
from liuzhushaonian
/**
* 获取高斯模糊图片
* @param context 上帝对象context
* @param source 源Bitmap
* @param radius 渲染半径(模糊程度)
* @return 返回模糊后的Bitmap
*/
protected Bitmap getBitmap(Context context, Bitmap source, int radius) {
if (radius <= 0) {
radius = 1;
}
if (radius > 25) {
radius = 25;
}
Bitmap bitmap = source;
RenderScript renderScript = RenderScript.create(context);
final Allocation input = Allocation.createFromBitmap(renderScript, bitmap);
final Allocation output = Allocation.createTyped(renderScript, input.getType());
ScriptIntrinsicBlur scriptIntrinsicBlur = ScriptIntrinsicBlur.create(renderScript, Element.U8_4(renderScript));
scriptIntrinsicBlur.setInput(input);
scriptIntrinsicBlur.setRadius(radius);
scriptIntrinsicBlur.forEach(output);
output.copyTo(bitmap);
renderScript.destroy();
return bitmap;
}
17
Source : Predictor.java
with Mozilla Public License 2.0
from KernelErr
with Mozilla Public License 2.0
from KernelErr
public clreplaced Predictor {
private static final String TAG = Predictor.clreplaced.getSimpleName();
public boolean isLoaded = false;
public int warmupIterNum = 1;
public int inferIterNum = 1;
public int cpuThreadNum = 1;
public String cpuPowerMode = "LITE_POWER_HIGH";
public String modelPath = "";
public String modelName = "";
protected PaddlePredictor paddlePredictor = null;
protected float inferenceTime = 0;
// Only for object detection
protected Vector<String> wordLabels = new Vector<String>();
protected String inputColorFormat = "RGB";
protected long[] inputShape = new long[] { 1, 3, 320, 320 };
protected float[] inputMean = new float[] { 0.485f, 0.456f, 0.406f };
protected float[] inputStd = new float[] { 0.229f, 0.224f, 0.225f };
protected float scoreThreshold = 0.5f;
protected Bitmap inputImage = null;
protected String outputResult = "";
protected float preprocessTime = 0;
protected float postprocessTime = 0;
RenderScript rs;
public Predictor() {
}
public boolean init(Context appCtx, String modelPath, String labelPath, int cpuThreadNum, String cpuPowerMode, String inputColorFormat, long[] inputShape, float[] inputMean, float[] inputStd, float scoreThreshold, RenderScript rs) {
this.rs = rs;
if (inputShape.length != 4) {
Log.i(TAG, "Size of input shape should be: 4");
return false;
}
if (inputMean.length != inputShape[1]) {
Log.i(TAG, "Size of input mean should be: " + Long.toString(inputShape[1]));
return false;
}
if (inputStd.length != inputShape[1]) {
Log.i(TAG, "Size of input std should be: " + Long.toString(inputShape[1]));
return false;
}
if (inputShape[0] != 1) {
Log.i(TAG, "Only one batch is supported in the image clreplacedification demo, you can use any batch size in " + "your Apps!");
return false;
}
if (inputShape[1] != 1 && inputShape[1] != 3) {
Log.i(TAG, "Only one/three channels are supported in the image clreplacedification demo, you can use any " + "channel size in your Apps!");
return false;
}
if (!inputColorFormat.equalsIgnoreCase("RGB") && !inputColorFormat.equalsIgnoreCase("BGR")) {
Log.i(TAG, "Only RGB and BGR color format is supported.");
return false;
}
isLoaded = loadModel(appCtx, modelPath, cpuThreadNum, cpuPowerMode);
if (!isLoaded) {
return false;
}
isLoaded = loadLabel(appCtx, labelPath);
if (!isLoaded) {
return false;
}
this.inputColorFormat = inputColorFormat;
this.inputShape = inputShape;
this.inputMean = inputMean;
this.inputStd = inputStd;
this.scoreThreshold = scoreThreshold;
return true;
}
protected boolean loadModel(Context appCtx, String modelPath, int cpuThreadNum, String cpuPowerMode) {
// Release model if exists
releaseModel();
// Load model
if (modelPath.isEmpty()) {
return false;
}
String realPath = modelPath;
if (!modelPath.substring(0, 1).equals("/")) {
// Read model files from custom path if the first character of mode path is '/'
// otherwise copy model to cache from replacedets
realPath = appCtx.getCacheDir() + "/" + modelPath;
Utils.copyDirectoryFromreplacedets(appCtx, modelPath, realPath);
}
if (realPath.isEmpty()) {
return false;
}
MobileConfig config = new MobileConfig();
config.setModelFromFile(realPath + File.separator + "model.nb");
config.setThreads(cpuThreadNum);
if (cpuPowerMode.equalsIgnoreCase("LITE_POWER_HIGH")) {
config.setPowerMode(PowerMode.LITE_POWER_HIGH);
} else if (cpuPowerMode.equalsIgnoreCase("LITE_POWER_LOW")) {
config.setPowerMode(PowerMode.LITE_POWER_LOW);
} else if (cpuPowerMode.equalsIgnoreCase("LITE_POWER_FULL")) {
config.setPowerMode(PowerMode.LITE_POWER_FULL);
} else if (cpuPowerMode.equalsIgnoreCase("LITE_POWER_NO_BIND")) {
config.setPowerMode(PowerMode.LITE_POWER_NO_BIND);
} else if (cpuPowerMode.equalsIgnoreCase("LITE_POWER_RAND_HIGH")) {
config.setPowerMode(PowerMode.LITE_POWER_RAND_HIGH);
} else if (cpuPowerMode.equalsIgnoreCase("LITE_POWER_RAND_LOW")) {
config.setPowerMode(PowerMode.LITE_POWER_RAND_LOW);
} else {
Log.e(TAG, "unknown cpu power mode!");
return false;
}
paddlePredictor = PaddlePredictor.createPaddlePredictor(config);
this.cpuThreadNum = cpuThreadNum;
this.cpuPowerMode = cpuPowerMode;
this.modelPath = realPath;
this.modelName = realPath.substring(realPath.lastIndexOf("/") + 1);
return true;
}
public void releaseModel() {
Log.i(TAG, "Model released.");
paddlePredictor = null;
isLoaded = false;
cpuThreadNum = 1;
cpuPowerMode = "LITE_POWER_HIGH";
modelPath = "";
modelName = "";
}
protected boolean loadLabel(Context appCtx, String labelPath) {
wordLabels.clear();
// Load word labels from file
try {
InputStream replacedetsInputStream = appCtx.getreplacedets().open(labelPath);
int available = replacedetsInputStream.available();
byte[] lines = new byte[available];
replacedetsInputStream.read(lines);
replacedetsInputStream.close();
String words = new String(lines);
String[] contents = words.split("\n");
for (String content : contents) {
wordLabels.add(content);
}
Log.i(TAG, "Word label size: " + wordLabels.size());
} catch (Exception e) {
Log.e(TAG, e.getMessage());
return false;
}
return true;
}
public Tensor getInput(int idx) {
if (!isLoaded()) {
return null;
}
return paddlePredictor.getInput(idx);
}
public Tensor getOutput(int idx) {
if (!isLoaded()) {
return null;
}
return paddlePredictor.getOutput(idx);
}
@SuppressWarnings("unchecked")
public List<Object> runModel() {
final List<Object> predictions = new ArrayList<>();
if (inputImage == null || !isLoaded()) {
return predictions;
}
// Set input shape
Tensor inputTensor0 = getInput(0);
inputTensor0.resize(inputShape);
Tensor inputTensor1 = getInput(1);
inputTensor1.resize(new long[] { 1, 2 });
// Pre-process image, and feed input tensor with pre-processed data
Date start = new Date();
int channels = (int) inputShape[1];
int width = (int) inputShape[3];
int height = (int) inputShape[2];
float[] inputData = new float[channels * width * height];
if (channels == 3) {
int[] channelIdx = null;
if (inputColorFormat.equalsIgnoreCase("RGB")) {
channelIdx = new int[] { 0, 1, 2 };
} else if (inputColorFormat.equalsIgnoreCase("BGR")) {
channelIdx = new int[] { 2, 1, 0 };
} else {
Log.i(TAG, "Unknown color format " + inputColorFormat + ", only RGB and BGR color format is " + "supported!");
return predictions;
}
int[] channelStride = new int[] { width * height, width * height * 2 };
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int color = inputImage.getPixel(x, y);
float[] rgb = new float[] { (float) red(color) / 255.0f, (float) green(color) / 255.0f, (float) blue(color) / 255.0f };
inputData[y * width + x] = (rgb[channelIdx[0]] - inputMean[0]) / inputStd[0];
inputData[y * width + x + channelStride[0]] = (rgb[channelIdx[1]] - inputMean[1]) / inputStd[1];
inputData[y * width + x + channelStride[1]] = (rgb[channelIdx[2]] - inputMean[2]) / inputStd[2];
}
}
} else if (channels == 1) {
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int color = inputImage.getPixel(x, y);
float gray = (float) (red(color) + green(color) + blue(color)) / 3.0f / 255.0f;
inputData[y * width + x] = (gray - inputMean[0]) / inputStd[0];
}
}
} else {
Log.i(TAG, "Unsupported channel size " + Integer.toString(channels) + ", only channel 1 and 3 is " + "supported!");
return predictions;
}
inputTensor0.setData(inputData);
inputTensor1.setData(new int[] { 320, 320 });
Date end = new Date();
preprocessTime = (float) (end.getTime() - start.getTime());
// Warm up
for (int i = 0; i < warmupIterNum; i++) {
paddlePredictor.run();
}
// Run inference
start = new Date();
for (int i = 0; i < inferIterNum; i++) {
paddlePredictor.run();
}
end = new Date();
inferenceTime = (end.getTime() - start.getTime()) / (float) inferIterNum;
// Fetch output tensor
Tensor outputTensor = getOutput(0);
// Post-process
start = new Date();
long[] outputShape = outputTensor.shape();
long outputSize = 1;
for (long s : outputShape) {
outputSize *= s;
}
int imgWidth = inputImage.getWidth();
int imgHeight = inputImage.getHeight();
int objectIdx = 0;
for (int i = 0; i < outputSize; i += 6) {
float score = 0;
try {
score = outputTensor.getFloatData()[i + 1];
} catch (Exception e) {
Log.e(TAG, e.getMessage());
return predictions;
}
if (score < scoreThreshold) {
continue;
}
int categoryIdx = (int) outputTensor.getFloatData()[i];
String categoryName = "Unknown";
if (wordLabels.size() > 0 && categoryIdx >= 0 && categoryIdx < wordLabels.size()) {
categoryName = wordLabels.get(categoryIdx);
}
float rawLeft = outputTensor.getFloatData()[i + 2] / 320;
float rawTop = outputTensor.getFloatData()[i + 3] / 320;
float rawRight = outputTensor.getFloatData()[i + 4] / 320;
float rawBottom = outputTensor.getFloatData()[i + 5] / 320;
float clampedLeft = Math.max(Math.min(rawLeft, 1.f), 0.f);
float clampedTop = Math.max(Math.min(rawTop, 1.f), 0.f);
float clampedRight = Math.max(Math.min(rawRight, 1.f), 0.f);
float clampedBottom = Math.max(Math.min(rawBottom, 1.f), 0.f);
float imgLeft = clampedLeft * imgWidth;
float imgTop = clampedTop * imgWidth;
float imgRight = clampedRight * imgHeight;
float imgBottom = clampedBottom * imgHeight;
List objDetail = new ArrayList<>();
objDetail.add(objectIdx);
objDetail.add(categoryName);
objDetail.add(imgLeft);
objDetail.add(imgTop);
objDetail.add(imgRight);
objDetail.add(imgBottom);
objDetail.add(String.format("%.3f", score));
objectIdx++;
predictions.add(objDetail);
}
end = new Date();
postprocessTime = (float) (end.getTime() - start.getTime());
Log.i(TAG, "Time used " + Float.toString(inferenceTime) + " ms.");
return predictions;
}
public boolean isLoaded() {
return paddlePredictor != null && isLoaded;
}
public String modelPath() {
return modelPath;
}
public String modelName() {
return modelName;
}
public int cpuThreadNum() {
return cpuThreadNum;
}
public String cpuPowerMode() {
return cpuPowerMode;
}
public float inferenceTime() {
return inferenceTime;
}
public Bitmap inputImage() {
return inputImage;
}
public String outputResult() {
return outputResult;
}
public float preprocessTime() {
return preprocessTime;
}
public float postprocessTime() {
return postprocessTime;
}
public void setInputImage(HashMap image) {
if (image == null) {
return;
}
this.inputImage = null;
// Scale image to the size of input tensor
Bitmap imageBit = getBitmap(image);
Bitmap rgbaImage = imageBit.copy(Bitmap.Config.ARGB_8888, true);
Bitmap scaleImage = Bitmap.createScaledBitmap(rgbaImage, (int) inputShape[3], (int) inputShape[2], true);
this.inputImage = scaleImage;
}
public Bitmap getBitmap(HashMap image) {
Bitmap bitmap = Bitmap.createScaledBitmap(yuv420toBitMap(image), 416, 416, true);
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Matrix matrix = new Matrix();
matrix.postRotate((Integer) image.get("rotation"));
return Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
}
@SuppressWarnings("unchecked")
public Bitmap yuv420toBitMap(final HashMap image) {
int w = (int) image.get("width");
int h = (int) image.get("height");
ArrayList<Map> planes = (ArrayList) image.get("planes");
byte[] data = yuv420toNV21(w, h, planes);
Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
ScriptIntrinsicYuvToRGB yuvToRgbIntrinsic = ScriptIntrinsicYuvToRGB.create(rs, Element.U8_4(rs));
Type.Builder yuvType = new Type.Builder(rs, Element.U8(rs)).setX(data.length);
Allocation in = Allocation.createTyped(rs, yuvType.create(), Allocation.USAGE_SCRIPT);
in.copyFrom(data);
Type.Builder rgbaType = new Type.Builder(rs, Element.RGBA_8888(rs)).setX(w).setY(h);
Allocation out = Allocation.createTyped(rs, rgbaType.create(), Allocation.USAGE_SCRIPT);
yuvToRgbIntrinsic.setInput(in);
yuvToRgbIntrinsic.forEach(out);
out.copyTo(bitmap);
return bitmap;
}
public byte[] yuv420toNV21(int width, int height, ArrayList<Map> planes) {
byte[] yBytes = (byte[]) planes.get(0).get("bytes"), uBytes = (byte[]) planes.get(1).get("bytes"), vBytes = (byte[]) planes.get(2).get("bytes");
final int color_pixel_stride = (int) planes.get(1).get("bytesPerPixel");
ByteArrayOutputStream outputbytes = new ByteArrayOutputStream();
try {
outputbytes.write(yBytes);
outputbytes.write(vBytes);
outputbytes.write(uBytes);
} catch (IOException e) {
e.printStackTrace();
}
byte[] data = outputbytes.toByteArray();
final int y_size = yBytes.length;
final int u_size = uBytes.length;
final int data_offset = width * height;
for (int i = 0; i < y_size; i++) {
data[i] = (byte) (yBytes[i] & 255);
}
for (int i = 0; i < u_size / color_pixel_stride; i++) {
data[data_offset + 2 * i] = vBytes[i * color_pixel_stride];
data[data_offset + 2 * i + 1] = uBytes[i * color_pixel_stride];
}
return data;
}
}
17
Source : BitmapUtils.java
with Apache License 2.0
from jiangzhongbo
with Apache License 2.0
from jiangzhongbo
/**
* RenderScript模糊
*
* @param context
* 上下文
* @param bitmap
* 源位图
* @param radius
* 模糊半径
* @return bitmap
*/
@SuppressLint("NewApi")
public static Bitmap blurBitmapByRender(Context context, Bitmap bitmap, float radius) {
Bitmap outBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
RenderScript rs = RenderScript.create(context);
ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
Allocation allIn = Allocation.createFromBitmap(rs, bitmap);
Allocation allOut = Allocation.createFromBitmap(rs, outBitmap);
blurScript.setRadius(radius);
blurScript.setInput(allIn);
blurScript.forEach(allOut);
allOut.copyTo(outBitmap);
bitmap.recycle();
rs.destroy();
return outBitmap;
}
17
Source : DisplayUtils.java
with Apache License 2.0
from JaynmBo
with Apache License 2.0
from JaynmBo
/**
* android系统的模糊方法
*
* @param bitmap 要模糊的图片
* @param radius 模糊等级 >=0 && <=25
*/
public static Bitmap blurBitmap(Context context, Bitmap bitmap, int radius) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
// Let's create an empty bitmap with the same size of the bitmap we want to blur
Bitmap outBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
// Instantiate a new Renderscript
RenderScript rs = RenderScript.create(context);
// Create an Intrinsic Blur Script using the Renderscript
ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
// Create the Allocations (in/out) with the Renderscript and the in/out bitmaps
Allocation allIn = Allocation.createFromBitmap(rs, bitmap);
Allocation allOut = Allocation.createFromBitmap(rs, outBitmap);
// Set the radius of the blur
blurScript.setRadius(radius);
// 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;
} else {
return bitmap;
}
}
17
Source : BitmapUtils.java
with Apache License 2.0
from Horrarndoo
with Apache License 2.0
from Horrarndoo
/**
* android系统的模糊方法
*
* @param bitmap 要模糊的图片
* @param radius 模糊等级 >=0 && <=25
*/
private static Bitmap blurBitmap(Context context, Bitmap bitmap, int radius) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
// Let's create an empty bitmap with the same size of the bitmap we want to blur
Bitmap outBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
// Instantiate a new Renderscript
RenderScript rs = RenderScript.create(context);
// Create an Intrinsic Blur Script using the Renderscript
ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
// Create the Allocations (in/out) with the Renderscript and the in/out bitmaps
Allocation allIn = Allocation.createFromBitmap(rs, bitmap);
Allocation allOut = Allocation.createFromBitmap(rs, outBitmap);
// Set the radius of the blur
blurScript.setRadius(radius);
// 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;
} else {
return bitmap;
}
}
17
Source : PhotoFilter.java
with Apache License 2.0
from hgayan7
with Apache License 2.0
from hgayan7
/**
* Created by him on 9/10/2017.
*/
public clreplaced PhotoFilter {
RenderScript renderScript;
Allocation inputAllocation, outputAllocation;
Bitmap outBitmap;
// filter1
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
public Bitmap one(Context context, Bitmap bitmap) {
renderScript = RenderScript.create(context);
outBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig());
inputAllocation = Allocation.createFromBitmap(renderScript, bitmap);
outputAllocation = Allocation.createTyped(renderScript, inputAllocation.getType());
final ScriptIntrinsicColorMatrix colorMatrix1 = ScriptIntrinsicColorMatrix.create(renderScript, Element.U8_4(renderScript));
colorMatrix1.setColorMatrix(new android.renderscript.Matrix4f(new float[] { -0.33f, -0.33f, -0.33f, 1.0f, -0.59f, -0.59f, -0.59f, 1.0f, -0.11f, -0.11f, -0.11f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f }));
colorMatrix1.forEach(inputAllocation, outputAllocation);
outputAllocation.copyTo(outBitmap);
return outBitmap;
}
// filter2
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
public Bitmap two(Context context, Bitmap bitmap) {
renderScript = RenderScript.create(context);
outBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig());
inputAllocation = Allocation.createFromBitmap(renderScript, bitmap);
outputAllocation = Allocation.createTyped(renderScript, inputAllocation.getType());
final ScriptIntrinsicColorMatrix colorMatrix2 = ScriptIntrinsicColorMatrix.create(renderScript, Element.U8_4(renderScript));
colorMatrix2.setGreyscale();
colorMatrix2.forEach(inputAllocation, outputAllocation);
outputAllocation.copyTo(outBitmap);
return outBitmap;
}
// filter3
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
public Bitmap three(Context context, Bitmap bitmap) {
renderScript = RenderScript.create(context);
outBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig());
inputAllocation = Allocation.createFromBitmap(renderScript, bitmap);
outputAllocation = Allocation.createTyped(renderScript, inputAllocation.getType());
final ScriptIntrinsicColorMatrix colorMatrix3 = ScriptIntrinsicColorMatrix.create(renderScript, Element.U8_4(renderScript));
colorMatrix3.setColorMatrix(new android.renderscript.Matrix4f(new float[] { 0f, 0f, 0f, 0f, 0f, 0.78f, 0f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 1f }));
colorMatrix3.forEach(inputAllocation, outputAllocation);
outputAllocation.copyTo(outBitmap);
return outBitmap;
}
// filter4
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
public Bitmap four(Context context, Bitmap bitmap) {
renderScript = RenderScript.create(context);
outBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig());
inputAllocation = Allocation.createFromBitmap(renderScript, bitmap);
outputAllocation = Allocation.createTyped(renderScript, inputAllocation.getType());
final ScriptIntrinsicColorMatrix colorMatrix4 = ScriptIntrinsicColorMatrix.create(renderScript, Element.U8_4(renderScript));
colorMatrix4.setColorMatrix(new android.renderscript.Matrix4f(new float[] { 0.3f, 0f, 0f, 0f, 0f, 0.65f, 0f, 0f, 0f, 0f, 0.49f, 0f, 0f, 0f, 0f, 1f }));
colorMatrix4.forEach(inputAllocation, outputAllocation);
outputAllocation.copyTo(outBitmap);
return outBitmap;
}
// filter5
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
public Bitmap five(Context context, Bitmap bitmap) {
renderScript = RenderScript.create(context);
outBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig());
inputAllocation = Allocation.createFromBitmap(renderScript, bitmap);
outputAllocation = Allocation.createTyped(renderScript, inputAllocation.getType());
final ScriptIntrinsicColorMatrix colorMatrix5 = ScriptIntrinsicColorMatrix.create(renderScript, Element.U8_4(renderScript));
colorMatrix5.setColorMatrix(new android.renderscript.Matrix4f(new float[] { -0.359705309629158f, 0.377252728606377f, 0.663841667303255f, 0f, 1.56680818833214f, 0.456668209492391f, 1.12613917506705f, 0f, -0.147102878702981f, 0.226079061901232f, -0.729980842370303f, 0f, 0f, 0f, 0f, 1f }));
colorMatrix5.forEach(inputAllocation, outputAllocation);
outputAllocation.copyTo(outBitmap);
return outBitmap;
}
// filter6
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
public Bitmap six(Context context, Bitmap bitmap) {
renderScript = RenderScript.create(context);
outBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig());
inputAllocation = Allocation.createFromBitmap(renderScript, bitmap);
outputAllocation = Allocation.createTyped(renderScript, inputAllocation.getType());
final ScriptIntrinsicColorMatrix colorMatrix6 = ScriptIntrinsicColorMatrix.create(renderScript, Element.U8_4(renderScript));
colorMatrix6.setColorMatrix(new android.renderscript.Matrix4f(new float[] { 1.2f, 0.1f, 0.2f, 0.7f, 0.7f, 1f, 0f, -0.5f, -0.7f, 0.2f, 0.5f, 1.3f, 0, -0.1f, 0f, 0.9f }));
colorMatrix6.forEach(inputAllocation, outputAllocation);
outputAllocation.copyTo(outBitmap);
return outBitmap;
}
// filter7
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
public Bitmap seven(Context context, Bitmap bitmap) {
renderScript = RenderScript.create(context);
outBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig());
inputAllocation = Allocation.createFromBitmap(renderScript, bitmap);
outputAllocation = Allocation.createTyped(renderScript, inputAllocation.getType());
final ScriptIntrinsicColorMatrix colorMatrix7 = ScriptIntrinsicColorMatrix.create(renderScript, Element.U8_4(renderScript));
colorMatrix7.setColorMatrix(new android.renderscript.Matrix4f(new float[] { 1.22994596833595f, 0.0209523774645382f, 0.383244054685119f, 0f, 0.450138899443543f, 1.18737418804171f, -0.106933249401007f, 0f - 0.340084867779496f, 0.131673434493755f, 1.06368919471589f, 0f, 0f, 0f, 0f, 11.91f, 11.91f, 11.91f, 0f }));
colorMatrix7.forEach(inputAllocation, outputAllocation);
outputAllocation.copyTo(outBitmap);
return outBitmap;
}
// filter8
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
public Bitmap eight(Context context, Bitmap bitmap) {
renderScript = RenderScript.create(context);
outBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig());
inputAllocation = Allocation.createFromBitmap(renderScript, bitmap);
outputAllocation = Allocation.createTyped(renderScript, inputAllocation.getType());
final ScriptIntrinsicColorMatrix colorMatrix8 = ScriptIntrinsicColorMatrix.create(renderScript, Element.U8_4(renderScript));
colorMatrix8.setColorMatrix(new android.renderscript.Matrix4f(new float[] { 1.44f, 0f, 0f, 0f, 0f, 1.44f, 0f, 0f, 0f, 0f, 1.44f, 0f, 0f, 0f, 0f, 1f }));
colorMatrix8.forEach(inputAllocation, outputAllocation);
outputAllocation.copyTo(outBitmap);
return outBitmap;
}
// filter9
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
public Bitmap nine(Context context, Bitmap bitmap) {
renderScript = RenderScript.create(context);
outBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig());
inputAllocation = Allocation.createFromBitmap(renderScript, bitmap);
outputAllocation = Allocation.createTyped(renderScript, inputAllocation.getType());
final ScriptIntrinsicColorMatrix colorMatrix9 = ScriptIntrinsicColorMatrix.create(renderScript, Element.U8_4(renderScript));
colorMatrix9.setColorMatrix(new android.renderscript.Matrix4f(new float[] { -2f, -1f, 1f, -2f, 0f, -2f, 0f, 1f, 0f, 0f, -1f, 1f, 0f, 0f, 0f, 1f }));
colorMatrix9.forEach(inputAllocation, outputAllocation);
outputAllocation.copyTo(outBitmap);
return outBitmap;
}
// filter10
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
public Bitmap ten(Context context, Bitmap bitmap) {
renderScript = RenderScript.create(context);
outBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig());
inputAllocation = Allocation.createFromBitmap(renderScript, bitmap);
outputAllocation = Allocation.createTyped(renderScript, inputAllocation.getType());
final ScriptIntrinsicColorMatrix colorMatrix10 = ScriptIntrinsicColorMatrix.create(renderScript, Element.U8_4(renderScript));
colorMatrix10.setColorMatrix(new android.renderscript.Matrix4f(new float[] { 1f, 0f, 0.1f, -0.1f, 0f, 1f, 0.2f, 0f, 0f, 0f, 1.3f, 0f, 0f, 0f, 0f, 1 }));
colorMatrix10.forEach(inputAllocation, outputAllocation);
outputAllocation.copyTo(outBitmap);
return outBitmap;
}
// filter11
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
public Bitmap eleven(Context context, Bitmap bitmap) {
renderScript = RenderScript.create(context);
outBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig());
inputAllocation = Allocation.createFromBitmap(renderScript, bitmap);
outputAllocation = Allocation.createTyped(renderScript, inputAllocation.getType());
final ScriptIntrinsicColorMatrix colorMatrix11 = ScriptIntrinsicColorMatrix.create(renderScript, Element.U8_4(renderScript));
colorMatrix11.setColorMatrix(new android.renderscript.Matrix4f(new float[] { 1.72814708519562f, -0.412104992562475f, 0.541145007437525f, 0f, 0.289378264402959f, 1.18835534216106f, -1.17637173559704f, 0f, -1.01752534959858f, 0.223749650401417f, 1.63522672815952f, 0f, 0f, 0f, 0f, 1f }));
colorMatrix11.forEach(inputAllocation, outputAllocation);
outputAllocation.copyTo(outBitmap);
return outBitmap;
}
// filter12
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
public Bitmap twelve(Context context, Bitmap bitmap) {
renderScript = RenderScript.create(context);
outBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig());
inputAllocation = Allocation.createFromBitmap(renderScript, bitmap);
outputAllocation = Allocation.createTyped(renderScript, inputAllocation.getType());
final ScriptIntrinsicColorMatrix colorMatrix12 = ScriptIntrinsicColorMatrix.create(renderScript, Element.U8_4(renderScript));
colorMatrix12.setColorMatrix(new android.renderscript.Matrix4f(new float[] { .309f, .409f, .309f, 0f, .609f, .309f, .409f, 0f, 0.42f, .42f, .2f, 0f, 0f, 0f, 0f, 1f }));
colorMatrix12.forEach(inputAllocation, outputAllocation);
outputAllocation.copyTo(outBitmap);
return outBitmap;
}
// filter13
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
public Bitmap thirteen(Context context, Bitmap bitmap) {
renderScript = RenderScript.create(context);
outBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig());
inputAllocation = Allocation.createFromBitmap(renderScript, bitmap);
outputAllocation = Allocation.createTyped(renderScript, inputAllocation.getType());
final ScriptIntrinsicConvolve3x3 convolve1 = ScriptIntrinsicConvolve3x3.create(renderScript, Element.U8_4(renderScript));
convolve1.setInput(inputAllocation);
convolve1.setCoefficients(new float[] { -2, -1, 0, -1, 1, 1, 0, 1, 2 });
convolve1.forEach(outputAllocation);
outputAllocation.copyTo(outBitmap);
return outBitmap;
}
// filter14
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
public Bitmap fourteen(Context context, Bitmap bitmap) {
renderScript = RenderScript.create(context);
outBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig());
inputAllocation = Allocation.createFromBitmap(renderScript, bitmap);
outputAllocation = Allocation.createTyped(renderScript, inputAllocation.getType());
final ScriptIntrinsicConvolve3x3 convolve2 = ScriptIntrinsicConvolve3x3.create(renderScript, Element.U8_4(renderScript));
convolve2.setInput(inputAllocation);
convolve2.setCoefficients(new float[] { .2f, .3f, .2f, .1f, .1f, .1f, .2f, .3f, .2f });
convolve2.forEach(outputAllocation);
outputAllocation.copyTo(outBitmap);
return outBitmap;
}
// filter15
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
public Bitmap fifteen(Context context, Bitmap bitmap) {
renderScript = RenderScript.create(context);
outBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig());
inputAllocation = Allocation.createFromBitmap(renderScript, bitmap);
outputAllocation = Allocation.createTyped(renderScript, inputAllocation.getType());
final ScriptIntrinsicColorMatrix colorMatrix13 = ScriptIntrinsicColorMatrix.create(renderScript, Element.U8_4(renderScript));
colorMatrix13.setColorMatrix(new android.renderscript.Matrix4f(new float[] { 2.10279132254252f, -0.298212630531356f, 0.42128146417712f, 0f, 0.222897572029231f, 1.68701190285368f, -0.883421304780577f, 0f, -0.765688894571747f, 0.171200727677677f, 2.02213984060346f, 0f, 0, 0, 0, 1f }));
colorMatrix13.forEach(inputAllocation, outputAllocation);
outputAllocation.copyTo(outBitmap);
return outBitmap;
}
// filter16
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
public Bitmap sixteen(Context context, Bitmap bitmap) {
renderScript = RenderScript.create(context);
outBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig());
inputAllocation = Allocation.createFromBitmap(renderScript, bitmap);
outputAllocation = Allocation.createTyped(renderScript, inputAllocation.getType());
final ScriptIntrinsicColorMatrix colorMatrix14 = ScriptIntrinsicColorMatrix.create(renderScript, Element.U8_4(renderScript));
colorMatrix14.setColorMatrix(new android.renderscript.Matrix4f(new float[] { 1.27488526960083f, -0.228511311848763f, 0.441088688151237f, 0, 0.323664244263542f, 0.955140825713134f, -0.705935755736458f, 0, -0.698549513864371f, 0.173370486135629f, 1.16484706758522f, 0, 0, 0, 0, 1 }));
colorMatrix14.forEach(inputAllocation, outputAllocation);
outputAllocation.copyTo(outBitmap);
return outBitmap;
}
}
17
Source : BlurBitmapUtil.java
with Apache License 2.0
from HelloChenJinJun
with Apache License 2.0
from HelloChenJinJun
/**
* 模糊图片的具体方法
*
* @param context 上下文对象
* @param image 需要模糊的图片
* @return 模糊处理后的图片
*/
@SuppressLint("NewApi")
public static Bitmap blurBitmap(Context context, Bitmap image, float blurRadius) {
// 计算图片缩小后的长宽
int width = Math.round(image.getWidth() * BITMAP_SCALE);
int height = Math.round(image.getHeight() * BITMAP_SCALE);
// 将缩小后的图片做为预渲染的图片。
Bitmap inputBitmap = Bitmap.createScaledBitmap(image, width, height, false);
// 创建一张渲染后的输出图片。
Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap);
// 创建RenderScript内核对象
RenderScript rs = RenderScript.create(context);
// 创建一个模糊效果的RenderScript的工具对象
ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
// 由于RenderScript并没有使用VM来分配内存,所以需要使用Allocation类来创建和分配内存空间。
// 创建Allocation对象的时候其实内存是空的,需要使用copyTo()将数据填充进去。
Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap);
Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap);
// 设置渲染的模糊程度, 25f是最大模糊度
blurScript.setRadius(blurRadius);
// 设置blurScript对象的输入内存
blurScript.setInput(tmpIn);
// 将输出数据保存到输出内存中
blurScript.forEach(tmpOut);
// 将数据填充到Allocation中
tmpOut.copyTo(outputBitmap);
return outputBitmap;
}
17
Source : MainActivity.java
with Apache License 2.0
from googlecodelabs
with Apache License 2.0
from googlecodelabs
public clreplaced MainActivity extends Activity {
private static final String TAG = "MainActivity";
ImageView mImgView;
DrawView mDrawView;
Matrix mMatrix = new Matrix();
Matrix mInverseMatrix = new Matrix();
Bitmap mDisplayedImage;
Bitmap mImage2;
RenderScript mRs;
ScriptC_healing mHealingScript;
ScriptC_find_region mFindRegion;
private float mZoom = 0.8f;
float mYOffset = 0;
float mXOffset = 0;
RunScript mRunScript = null;
private String mImagePath;
private String mImageName;
private Region mLastRegion;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 1);
}
}
mImgView = (ImageView) findViewById(R.id.imageview);
mDrawView = (DrawView) findViewById(R.id.overlay);
mDrawView.setImageView(mImgView);
mRs = RenderScript.create(this.getBaseContext());
mHealingScript = new ScriptC_healing(mRs);
mFindRegion = new ScriptC_find_region(mRs);
mImgView.setOnTouchListener(new View.OnTouchListener() {
float[] imgPoint = new float[2];
float[] imgMoveList = new float[100];
boolean mPanZoomDown = false;
float mCenterDownX;
float mCenterDownY;
float mDistDown;
float mDownXOffset;
float mDownYOffset;
float mDownZoom;
boolean inMulreplacedouch = false;
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
float x = event.getX();
float y = event.getY();
imgPoint[0] = x;
imgPoint[1] = y;
int sw = mImgView.getWidth();
int sh = mImgView.getHeight();
int iw = mImgView.getDrawable().getIntrinsicWidth();
int ih = mImgView.getDrawable().getIntrinsicHeight();
switch(action) {
case MotionEvent.ACTION_DOWN:
Log.v(TAG, "ACTION_DOWN " + event.getPointerCount());
break;
case MotionEvent.ACTION_UP:
Log.v(TAG, "ACTION_UP " + event.getPointerCount());
break;
case MotionEvent.ACTION_MOVE:
Log.v(TAG, "ACTION_MOVE " + event.getPointerCount());
break;
}
if (event.getPointerCount() > 1) {
inMulreplacedouch = true;
}
if (event.getPointerCount() == 2) {
float x1 = event.getX(0);
float y1 = event.getY(0);
float x2 = event.getX(1);
float y2 = event.getY(1);
if (mPanZoomDown) {
float dx = (x1 + x2) / 2 - mCenterDownX;
float dy = (y1 + y2) / 2 - mCenterDownY;
float zoom = (float) Math.hypot(x1 - x2, y1 - y2);
mZoom = zoom * mDownZoom / mDistDown;
float scale = mZoom * Math.min(sw / (float) iw, sh / (float) ih);
mXOffset = mDownXOffset + 2 * (dx / (sw - scale * iw));
mYOffset = mDownYOffset + 2 * (dy / (sh - scale * ih));
if (Math.abs(mXOffset) > 1) {
mXOffset = Math.signum(mXOffset);
}
if (Math.abs(mYOffset) > 1) {
mYOffset = Math.signum(mYOffset);
}
} else {
mDrawView.undo();
mPanZoomDown = true;
mCenterDownX = (x1 + x2) / 2;
mCenterDownY = (y1 + y2) / 2;
mDistDown = (float) Math.hypot(x1 - x2, y1 - y2);
mDownXOffset = mXOffset;
mDownYOffset = mYOffset;
mDownZoom = mZoom;
}
} else {
if (mPanZoomDown) {
mPanZoomDown = false;
}
}
if (!mPanZoomDown) {
switch(action) {
case MotionEvent.ACTION_DOWN:
mInverseMatrix.mapPoints(imgPoint);
mDrawView.clearDrawables();
mDrawView.downPoint(imgPoint);
mDrawView.invalidate();
break;
case MotionEvent.ACTION_UP:
if (inMulreplacedouch && event.getPointerCount() == 1) {
inMulreplacedouch = false;
} else {
mInverseMatrix.mapPoints(imgPoint);
mDrawView.upPoint(imgPoint);
mDrawView.invalidate();
}
break;
case MotionEvent.ACTION_MOVE:
int size = event.getHistorySize();
size = Math.min(size, imgMoveList.length / 2);
for (int i = 0; i < size; i++) {
imgMoveList[i * 2] = event.getHistoricalX(size - i - 1);
imgMoveList[i * 2 + 1] = event.getHistoricalY(size - i - 1);
}
mInverseMatrix.mapPoints(imgMoveList, 0, imgMoveList, 0, size);
if (!inMulreplacedouch) {
mDrawView.movePoint(imgMoveList, size);
mDrawView.invalidate();
}
break;
}
}
updateMatrix();
return true;
}
});
new AsyncLoad().execute();
}
void updateMatrix() {
int sw = mImgView.getWidth();
int sh = mImgView.getHeight();
int iw = mImgView.getDrawable().getIntrinsicWidth();
int ih = mImgView.getDrawable().getIntrinsicHeight();
mMatrix.reset();
float scale = mZoom * Math.min(sw / (float) iw, sh / (float) ih);
mMatrix.postTranslate((1 + mXOffset) * (sw - iw * scale) / 2, (1 + mYOffset) * (sh - ih * scale) / 2);
mMatrix.preScale(scale, scale);
boolean ret = mMatrix.invert(mInverseMatrix);
if (!ret) {
Log.e(TAG, "Fail to invert");
}
mImgView.setImageMatrix(mMatrix);
mImgView.invalidate();
mDrawView.invalidate();
}
void getScreenCoord(float[] point) {
Matrix matrix = mImgView.getImageMatrix();
}
clreplaced AsyncLoad extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... regions) {
Intent intent = getIntent();
if (intent != null) {
String s = intent.getType();
if (s != null && s.indexOf("image/") != -1) {
Uri data = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
// TODO the wrong way to do this
mImageName = "edit" + data.getLastPathSegment();
if (data != null) {
InputStream input = null;
try {
input = getContentResolver().openInputStream(data);
mDisplayedImage = BitmapFactory.decodeStream(input);
return null;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
getLocalImage();
return null;
}
@Override
protected void onPostExecute(Void s) {
mImgView.setImageBitmap(mDisplayedImage);
Log.v(TAG, "BITMAP SIZE = " + mDisplayedImage.getWidth() + "," + mDisplayedImage.getHeight());
updateMatrix();
}
}
void getLocalImage() {
mDisplayedImage = BitmapFactory.decodeResource(this.getResources(), R.drawable.bugs);
mImageName = "bugs";
}
public void heal(View v) {
mLastRegion = mDrawView.getRegion(mDisplayedImage);
if (mRunScript == null) {
mRunScript = new RunScript();
mRunScript.execute(mLastRegion);
}
}
public void undo(View v) {
if (mImage2 != null) {
mLastRegion.undo(mImage2);
mDrawView.invalidate();
}
}
public void save(View v) {
String name = mImageName;
if (name.indexOf(".") > 0) {
name = name.substring(0, name.lastIndexOf(".")) + "_e";
}
MediaStoreSaver.save(mImage2, "healingbrush", name, this, MediaStoreSaver.TYPE_JPG);
Toast.makeText(this, "Saved " + name, Toast.LENGTH_SHORT).show();
}
clreplaced RunScript extends AsyncTask<Region, String, String> {
Drawable d;
protected String doInBackground(Region... regions) {
d = regions[0].findMatch(mFindRegion, mRs, mDisplayedImage);
if (mImage2 == null) {
mImage2 = mDisplayedImage.copy(Bitmap.Config.ARGB_8888, true);
}
regions[0].heal(mHealingScript, mRs, mImage2, mImage2);
return "";
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
mDrawView.addDrawable(d);
mDrawView.invalidate();
mImgView.setImageBitmap(mImage2);
mRunScript = null;
}
}
}
17
Source : ImageUtils.java
with Apache License 2.0
from fennifith
with Apache License 2.0
from fennifith
@Nullable
public static Bitmap blurBitmap(Context context, Bitmap bitmap) {
if (context == null || bitmap == null)
return null;
Bitmap blurredBitmap;
try {
blurredBitmap = Bitmap.createBitmap(bitmap);
} catch (OutOfMemoryError e) {
return null;
}
RenderScript renderScript = RenderScript.create(context);
Allocation input = Allocation.createFromBitmap(renderScript, bitmap, Allocation.MipmapControl.MIPMAP_FULL, Allocation.USAGE_SCRIPT);
Allocation output = Allocation.createTyped(renderScript, input.getType());
ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(renderScript, Element.U8_4(renderScript));
script.setInput(input);
script.setRadius(20);
script.forEach(output);
output.copyTo(blurredBitmap);
return blurredBitmap;
}
17
Source : BitmapUtil.java
with Apache License 2.0
from fengyuecanzhu
with Apache License 2.0
from fengyuecanzhu
/**
* 高斯模糊
*/
public static Bitmap stackBlur(Bitmap srcBitmap) {
if (srcBitmap == null)
return null;
RenderScript rs = RenderScript.create(App.getApplication());
Bitmap blurredBitmap = srcBitmap.copy(Config.ARGB_8888, true);
// 分配用于渲染脚本的内存
Allocation input = Allocation.createFromBitmap(rs, blurredBitmap, Allocation.MipmapControl.MIPMAP_FULL, Allocation.USAGE_SHARED);
Allocation output = Allocation.createTyped(rs, input.getType());
// 加载我们想要使用的特定脚本的实例。
ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
script.setInput(input);
// 设置模糊半径
script.setRadius(8);
// 启动 ScriptIntrinsicBlur
script.forEach(output);
// 将输出复制到模糊的位图
output.copyTo(blurredBitmap);
return blurredBitmap;
}
17
Source : BlurTransformation.java
with GNU General Public License v3.0
from dkanada
with GNU General Public License v3.0
from dkanada
@Override
protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {
int sampling;
if (this.sampling == 0) {
sampling = ImageUtil.calculateInSampleSize(toTransform.getWidth(), toTransform.getHeight(), 100);
} else {
sampling = this.sampling;
}
int width = toTransform.getWidth();
int height = toTransform.getHeight();
int scaledWidth = width / sampling;
int scaledHeight = height / sampling;
Bitmap out = pool.get(scaledWidth, scaledHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(out);
canvas.scale(1 / (float) sampling, 1 / (float) sampling);
Paint paint = new Paint();
paint.setFlags(Paint.FILTER_BITMAP_FLAG);
canvas.drawBitmap(toTransform, 0, 0, paint);
final RenderScript renderScript = RenderScript.create(context.getApplicationContext());
final Allocation input = Allocation.createFromBitmap(renderScript, out, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT);
final Allocation output = Allocation.createTyped(renderScript, input.getType());
final ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(renderScript, Element.U8_4(renderScript));
script.setRadius(blurRadius);
script.setInput(input);
script.forEach(output);
output.copyTo(out);
renderScript.destroy();
return out;
}
17
Source : BlurTransformation.java
with Apache License 2.0
from devallever
with Apache License 2.0
from devallever
/**
* Transforms the given {@link Bitmap} based on the given dimensions and returns the transformed
* result.
* <p/>
* <p>
* The provided Bitmap, toTransform, should not be recycled or returned to the pool. Glide will automatically
* recycle and/or reuse toTransform if the transformation returns a different Bitmap. Similarly implementations
* should never recycle or return Bitmaps that are returned as the result of this method. Recycling or returning
* the provided and/or the returned Bitmap to the pool will lead to a variety of runtime exceptions and drawing
* errors. See #408 for an example. If the implementation obtains and discards intermediate Bitmaps, they may
* safely be returned to the BitmapPool and/or recycled.
* </p>
* <p/>
* <p>
* outWidth and outHeight will never be {@link Target#SIZE_ORIGINAL}, this
* clreplaced converts them to be the size of the Bitmap we're going to transform before calling this method.
* </p>
*
* @param pool A {@link BitmapPool} that can be used to obtain and
* return intermediate {@link Bitmap}s used in this transformation. For every
* {@link Bitmap} obtained from the pool during this transformation, a
* {@link Bitmap} must also be returned.
* @param toTransform The {@link Bitmap} to transform.
* @param outWidth The ideal width of the transformed bitmap (the transformed width does not need to match exactly).
* @param outHeight The ideal height of the transformed bitmap (the transformed heightdoes not need to match
*/
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
boolean needScaled = mSampling == DEFAULT_SAMPLING;
int originWidth = toTransform.getWidth();
int originHeight = toTransform.getHeight();
int width, height;
if (needScaled) {
width = originWidth;
height = originHeight;
} else {
width = (int) (originWidth / mSampling);
height = (int) (originHeight / mSampling);
}
// find a re-use bitmap
Bitmap bitmap = pool.get(width, height, Bitmap.Config.ARGB_8888);
if (bitmap == null) {
bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(bitmap);
if (mSampling != DEFAULT_SAMPLING) {
canvas.scale(1 / mSampling, 1 / mSampling);
}
Paint paint = new Paint();
paint.setFlags(Paint.FILTER_BITMAP_FLAG | Paint.ANTI_ALIAS_FLAG);
PorterDuffColorFilter filter = new PorterDuffColorFilter(mColor, PorterDuff.Mode.SRC_ATOP);
paint.setColorFilter(filter);
canvas.drawBitmap(toTransform, 0, 0, paint);
// TIPS: Glide will take care of returning our original Bitmap to the BitmapPool for us,
// we needn't to recycle it.
// toTransform.recycle(); <--- Just for tips. by Ligboy
RenderScript rs = RenderScript.create(mContext);
Allocation input = Allocation.createFromBitmap(rs, bitmap, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT);
Allocation output = Allocation.createTyped(rs, input.getType());
ScriptIntrinsicBlur blur = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
blur.setInput(input);
blur.setRadius(mRadius);
blur.forEach(output);
output.copyTo(bitmap);
rs.destroy();
if (needScaled) {
return bitmap;
} else {
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, originWidth, originHeight, true);
bitmap.recycle();
return scaled;
}
}
17
Source : CoolBGView.java
with Apache License 2.0
from crazysunj
with Apache License 2.0
from crazysunj
/**
* 获取模糊的图片
*
* @param context 上下文对象
* @param bitmap 传入的bitmap图片
*/
private Bitmap blurBitmap(Context context, Bitmap bitmap) {
// 用需要创建高斯模糊bitmap创建一个空的bitmap
Bitmap outBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
// 初始化Renderscript,该类提供了RenderScript context,创建其他RS类之前必须先创建这个类,其控制RenderScript的初始化,资源管理及释放
RenderScript rs = RenderScript.create(context);
// 创建一个模糊效果的RenderScript的工具对象
ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
// 由于RenderScript并没有使用VM来分配内存,所以需要使用Allocation类来创建和分配内存空间。
// 创建Allocation对象的时候其实内存是空的,需要使用copyTo()将数据填充进去。
Allocation allIn = Allocation.createFromBitmap(rs, bitmap);
Allocation allOut = Allocation.createFromBitmap(rs, outBitmap);
// 设定模糊度(注:radius最大只能设置25f)
blurScript.setRadius(BLUR_RADIUS);
// 设置blurScript对象的输入内存
blurScript.setInput(allIn);
// 将输出数据保存到输出内存中
blurScript.forEach(allOut);
// 将数据填充到Allocation中
allOut.copyTo(outBitmap);
rs.destroy();
return outBitmap;
}
See More Examples