Android with opencv - image to grayscale - android

I'm looking for simple example of app in Android which convert color image to grayscale using opencv.
I'm trying with thic code, but app crash after this line Mat tmp = new Mat(bmp.getWidth(), bmp.getHeight(), CvType.CV_8U);
.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView img=(ImageView)findViewById(R.id.imageView1);
Bitmap bmp = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);
Mat tmp = new Mat(bmp.getWidth(), bmp.getHeight(), CvType.CV_8U);
Utils.bitmapToMat(bmp, tmp);
Imgproc.cvtColor(tmp, tmp, Imgproc.COLOR_RGB2GRAY);
Imgproc.cvtColor(tmp, tmp, Imgproc.COLOR_RGB2GRAY,4);
Utils.matToBitmap(tmp, bmp);
img.setImageBitmap(bmp);
}

Real quick way to do it. Without opencv.
private Button button;
private ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button1);
image = (ImageView)findViewById(R.id.imageView1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ColorMatrix matrix = new ColorMatrix();
matrix.setSaturation(0);
ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
image.setColorFilter(filter);
}
});
I just tried it, works for me.
edit: Check out the link here for official doc.
http://developer.android.com/reference/android/graphics/ColorMatrix.html#setSaturation(float)

Your layout has not been laid out yet, while you are in onCreate(), that is why bmp.getWidth() and bmp.getHeight() return 0.
One way to do it is to override onWindowFocusChanged()
private ImageView img;
private boolean isFullyInitialized = false;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img=(ImageView)findViewById(R.id.imageView1);
}
#Override
public void onWindowFocusChanged(boolean hasFocus)
{
super.onWindowFocusChanged(hasFocus);
if (hasFocus && !isFullyInitialized)
{
isFullyInitialized = true;
openCvCode();
}
}
private void openCvCode()
{
Bitmap bmp = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);
Mat tmp = new Mat(bmp.getWidth(), bmp.getHeight(), CvType.CV_8U);
Utils.bitmapToMat(bmp, tmp);
Imgproc.cvtColor(tmp, tmp, Imgproc.COLOR_RGB2GRAY);
Imgproc.cvtColor(tmp, tmp, Imgproc.COLOR_RGB2GRAY,4);
Utils.matToBitmap(tmp, bmp);
img.setImageBitmap(bmp);
}

Problem solved:
public class MainActivity extends Activity {
ImageView img;
Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img=(ImageView)findViewById(R.id.imageView1);
bitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.lena);
if (!OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_2, this, mOpenCVCallBack))
{
Log.e("TEST", "Cannot connect to OpenCV Manager");
}
}
private BaseLoaderCallback mOpenCVCallBack = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
{
Mat tmp = new Mat(bitmap.getWidth(), bitmap.getHeight(),CvType.CV_8UC1);
// Convert
Utils.bitmapToMat(bitmap, tmp);
Mat gray = new Mat(bitmap.getWidth(), bitmap.getHeight(),CvType.CV_8UC1);
// Conver the color
Imgproc.cvtColor(tmp, gray, Imgproc.COLOR_RGB2GRAY);
// Convert back to bitmap
Mat destination = new Mat(gray.rows(),gray.cols(),gray.type());
Imgproc.adaptiveThreshold(gray, destination, 255, Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY_INV, 15, 4);
Utils.matToBitmap(destination, bitmap);
img.setImageBitmap(bitmap);
} break;
default:
{
super.onManagerConnected(status);
} break;
}
}
};
}

Related

Draw a shape using canvas in android studio without using custom view

My task is to draw a shape on second activity when user clicks a button. So I tried a following code, but it doesn't work.
I have referred lot of tutorials but all they did in another View. I didn't understand the View.
MainActivity.java
public class MainActivity extends AppCompatActivity implements
View.OnClickListener {
Button draw;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
draw = findViewById(R.id.drawButton);
draw.setOnClickListener(this);
}
#Override
public void onClick(View v) {
shape = dropdown.getSelectedItem().toString();
Bundle b = new Bundle();
b.putString("shape",shape);
Intent i = new Intent(getApplicationContext(),shapes.class);
i.putExtras(b);
startActivity(i);
}
}
Shapes.java
public class shapes extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shapes);
Canvas canvas = new Canvas();
Rect rec = new Rect();
rec.top=100;
rec.left=100;
rec.bottom = rec.top + 100;
rec.right = rec.left+ 100;
Paint p = new Paint();
p.setColor(Color.GREEN);
canvas.drawRect(rec,p);
}
}
When button click you are calling intent and it will create a new Activity. You can add a simple image view to the activity main layout and then you can set your canvas drawing as follows.
ImageView imageView=(ImageView) findViewById(R.id.image);
Bitmap bitmap = Bitmap.createBitmap(100, 100,
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.BLACK);
Rect rec = new Rect();
rec.top=0;
rec.left=0;
rec.bottom = rec.top + 100;
rec.right = rec.left+ 100;
canvas.drawRect(rec,paint);
imageView.setImageBitmap(bitmap);

How to corp a picture into any shape via a template in android?

I wanted to know if it was possible to crop a picture to any other shape not just square, rectangle or circle.
Basically what I am looking for is that, the user can select a template of a png file (already present) and it cuts the picture in that shape.
Check out this code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView imageViewPreview = (ImageView) findViewById(R.id.imageview_preview);
new Thread(new Runnable() {
#Override
public void run() {
final Bitmap source = BitmapFactory.decodeResource(MainActivity.this.getResources(),
R.drawable.source);
final Bitmap mask = BitmapFactory.decodeResource(MainActivity.this.getResources(),
R.drawable.mask);
final Bitmap croppedBitmap = cropBitmap(source, mask);
runOnUiThread(new Runnable() {
#Override
public void run() {
imageViewPreview.setImageBitmap(croppedBitmap);
}
});
}
}).start();
}
private Bitmap cropBitmap(final Bitmap source, final Bitmap mask){
final Bitmap croppedBitmap = Bitmap.createBitmap(
source.getWidth(), source.getHeight(),
Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(croppedBitmap);
canvas.drawBitmap(source, 0, 0, null);
final Paint maskPaint = new Paint();
maskPaint.setXfermode(
new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
canvas.drawBitmap(mask, 0, 0, maskPaint);
return croppedBitmap;
}
}
The main function is the "cropBitmap" function. Basically it receives two bitmaps, a source and a mask, and then it "crops" the source bitmap using the mask's shape.
This is my source bitmap:
This is the mask bitmap:
And this is the result:
Also, check out this great presentation, this might help you too: Fun with Android shaders and filters

Clear circle Bitmap

I have loaded a floor plan image and converted it into a Bitmap. And I have a circle drawn onto that floor plan image. This circle shows the current position of this user on the floor plan.
The problem is, when it comes a slow response from the server, multiple circle are drawn on the floor plan
Here is my code :
public void onServiceUpdate(ServiceState state) {
final int i, j;
i = state.getImagePoint().getI();
j = state.getImagePoint().getJ();
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.buildDrawingCache();
Bitmap bitmap = imageView.getDrawingCache();
final ImageView imageFloor = (ImageView) findViewById(R.id.imageView);
final Bitmap bitmapCircle = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig());
Canvas canvas = new Canvas(bitmapCircle);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.BLUE);
paint.setStrokeWidth(10);
canvas.drawBitmap(bitmap, new Matrix(), null);
canvas.drawCircle(i, j, 10, paint);
runOnUiThread(new Runnable() {
#Override
public void run() {
imageFloor.setImageBitmap(bitmapCircle);
}
});
and this is method calling floor plan image from indooratlas server.
public void loadFloorPlanImage(FloorPlan floorPlan) {
BitmapFactory.Options options = createBitmapOptions(floorPlan);
FutureResult<Bitmap> result = mIndoorAtlas.fetchFloorPlanImage(floorPlan,options);
result.setCallback(new ResultCallback<Bitmap>() {
#Override
public void onResult(final Bitmap result) {
runOnUiThread(new Runnable() {
#Override
public void run() {
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageBitmap(result);
log("onResult LoadFloorPlanImage");
}
});
}
is there any ideas or some advice how to clear the circle inside floor plan bitmap ?
You could do like this:
onServiceUpdate(...){
final ImageView imageFloor = (ImageView) findViewById(R.id.imageView);
imageFloor.setVisibility(View.GONE);
....
runOnUiThread(new Runnable() {
#Override
public void run() {
imageFloor.setVisibility(View.VISIBLE);
imageFloor.setImageBitmap(bitmapCircle);
But your question isn't very clear, I would not be surprised if I didn't understand what you meant

How to draw different shapes by clicking a button in android?

I have been looking for help doing this, I am attempting to create a snake game, what I need to do is draw into a bitmap or into an image view while clicking a button, that's the problem: every time I draw a shape, then the layout is erased, the goal for me is to draw into any object while I can still click a button, what I have already done is to draw over a layout and displaying an image, here is my code:
public class DisplayMessage extends Activity {
ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
Intent intent = getIntent();
String message = intent.getStringExtra("Hola Jorge");
DrawView drawView;
drawView = new DrawView(this);
setContentView(drawView);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.display_message, menu);
return true;
}
}
package mipaca;
public class DrawView extends View {
Paint paint = new Paint();
public DrawView(Context context) {
super(context);
paint.setColor(Color.BLACK);
}
#Override
public void onDraw(Canvas canvas) {
//canvas.drawColor(Color.GREEN);
canvas.drawLine(0, 0, 20, 20, paint);
canvas.drawLine(20, 0, 0, 20, paint);
Bitmap compara = Bitmap.createBitmap(100, 100, Config.ARGB_8888);
canvas.drawBitmap(compara, 0, 0, paint);
Rect rectangle = new Rect(0,0,100,100);
canvas.drawBitmap(compara, 0,0,null);
}
}
public class MainActivity extends Activity {
CharSequence[] items = {"Google","Apple","Microsoft"};
boolean[] itemsChecked = new boolean[items.length];
ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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;
}
public void onClick2(View v)
{
Intent intent = new Intent(this, DisplayMessage.class);
startActivity(intent);
}
public void onClick(View v)
{
//image.setImageResource(R.drawable.ferrari_458_italia_1);
showDialog(0);
DrawView2 alpha;
}
#Override
protected Dialog onCreateDialog(int id){
switch(id){
case 0:
return new AlertDialog.Builder(this)
.setIcon(R.drawable.ic_launcher)
.setTitle("Este es un diálogo con algo de texto")
.setPositiveButton("OK",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int whichButton)
{
Toast.makeText(getBaseContext(), "bien, click!", Toast.LENGTH_SHORT).show();
}
}
)
.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int whichButton)
{
Toast.makeText(getBaseContext(), "bien, click!", Toast.LENGTH_SHORT).show();
}
}
).create();
}
return null;
}
public void onDraw(Canvas canvas)
{
Paint p = new Paint();
p.setColor(Color.BLUE);
p.setAntiAlias(true);
canvas.drawColor(Color.CYAN);
canvas.drawCircle(200, 200, 50, p);
}
}
I hope this help someone, I forgot about this question until I came across with this idea: We can use an ImageView and then use a bitmap to draw any shape with a canvas, it is easier for me to draw in this way rather than using OnPaint function and invalidate because just modifying the bitmap and displaying it we can move an object on image and still have buttons, textboxs, etc. Here is what I have done:
(linen is our ImageView)
Bitmap bMap = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
android.graphics.Bitmap.Config bitmapConfig = bMap.getConfig();
if(bitmapConfig == null) {
bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
}
bMap = bMap.copy(bitmapConfig, true);
Canvas canvas = new Canvas(bMap);
paint.setColor(Color.rgb(61, 61, 61));
canvas.drawCircle(10, 10, 5, paint);
linen = (ImageView)findViewById(R.id.View1);
linen.setImageBitmap(bMap);

Android : Converting imageview to bitmap, to grayscale, bitmap to imageview

I don't don't get any warning on eclipse when I compile this code, but when I run it on device or emulator, that program was forced to close.
public class MainActivity extends Activity {
ImageView img;
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//convert imageview to bitmap
img =(ImageView) findViewById(R.id.imageView1);
BitmapDrawable drawable = (BitmapDrawable) img.getDrawable();
final Bitmap imgbitmap = drawable.getBitmap();
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//convert bitmap to grayscale
Bitmap imgnew;
imgnew = toGrayscale(imgbitmap);
//convert bitmap to imageview
ImageView imgbit;
imgbit = (ImageView) findViewById(R.id.imageView2);
imgbit.setImageBitmap(imgnew);
}
});
}
public Bitmap toGrayscale(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();
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);
ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
paint.setColorFilter(f);
c.drawBitmap(bmpOriginal, 0, 0, paint);
return bmpGrayscale;
}
}
If above is your full code then, basic problem is there, you haven't define btn. You need to define it before using it, else when you ar egoing to click on the button it will not work. and this might closing your application.
btn=(Button) findViewById(R.id.button1);

Categories

Resources