Tuesday, July 12, 2016

Android RenderScript mono filter 예제

// mono.rs
#pragma version(1)
#pragma rs java_package_name(com.example.renderscriptsample)

float3 gMonoMult = {0.2125, 0.7154, 0.0721};

void root(const uchar4 *v_in, uchar4 *v_out) {
    float4 f4 = rsUnpackColor8888(*v_in);
    float3 mono = dot(f4.rgb, gMonoMult);
    *v_out = rsPackColorTo8888(mono);
}

MainActivity.java
package com.example.renderscriptsample;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.renderscript.Allocation;
import android.renderscript.RenderScript;
import android.view.Menu;
import android.widget.ImageView;

public class MainActivity extends Activity {
 // RenderScript
 private RenderScript mRS;
 private Allocation mInAllocation;
 private Allocation mOutAllocation;
 private ScriptC_mono mScript;

 private Bitmap loadBitmap(int resource) {
  final BitmapFactory.Options options = new BitmapFactory.Options();
  options.inPreferredConfig = Bitmap.Config.ARGB_8888;
  return BitmapFactory.decodeResource(getResources(), resource, options);
 }

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  // bitmap load
  final Bitmap bm = loadBitmap(R.drawable.data);
  final Bitmap bmOut = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(), bm.getConfig());

  // renderscript init
  mRS = RenderScript.create(this);
  mInAllocation = Allocation.createFromBitmap(mRS, bm, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT);
  mOutAllocation = Allocation.createFromBitmap(mRS, bm, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT);
  mScript = new ScriptC_mono(mRS, getResources(), R.raw.mono);

  // renderscript run
  mScript.forEach_root(mInAllocation, mOutAllocation);
  mOutAllocation.copyTo(bmOut);
 
  // set output bitmap
  final ImageView iv = (ImageView) findViewById(R.id.imageView1);
  iv.setImageBitmap(bmOut);

 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }

}

No comments:

Post a Comment