Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select an area on bitmap with 4 points using Matrix.setPolyToPoly

I am playing with bitmap on Android and I am facing an issue when selecting an area on the bitmap using the 4 points. Not all the sets of 4 points work for me. In some cases, the result is just a blank bitmap instead of the cropped bitmap (like in the picture) and there is not any error in logcat(even memory error). Here is the basic code I used to do the transformation.

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.widget.ImageView;

public class CropImageActivity extends Activity {
private ImageView mCroppedImageView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.crop);
    setupViews();
    doCropping();
}

private void doCropping() {
    Bitmap srcBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.sample);

    //target size
    int bitmapWidth = 400;
    int bitmapHeight = 400;

    Bitmap bitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);

    //This is one of bad quadangle.
    points[0] = 0;    //top-left.x
    points[1] = 0;    //top-left.y
    points[2] = 230;  //top-right.x
    points[3] = 100;  //top-right.y
    points[4] = 350;  //bottom-right.x
    points[5] = 350;  //bottom-right.y
    points[6] = 0;    //bottom-left.x
    points[7] = 350;  //bottom-left.y

    float[] src = new float[]{
            points[0], points[1],
            points[2], points[3],
            points[4], points[5],
            points[6], points[7]
    };
    float[] dsc = new float[]{
            0, 0,
            bitmapWidth, 0,
            bitmapWidth, bitmapHeight,
            0, bitmapHeight
    };

    Matrix matrix = new Matrix();
    boolean transformResult = matrix.setPolyToPoly(src, 0, dsc, 0, 4);

    canvas.drawBitmap(srcBitmap, matrix, null);
    mCroppedImageView.setImageBitmap(bitmap);
}

private void setupViews() {
    mCroppedImageView = (ImageView) findViewById(R.id.croppedImageView);
}
}

So, does the 4 points coordinates affect the canvas drawing or the matrix transformation? Any help is appreciated.

Thank you

enter image description here This works

like image 832
h2nghia Avatar asked Oct 31 '22 11:10

h2nghia


1 Answers

Finally, I solve my issue using OpenCV. Thanks for the answer in this question! It seems that Matrix.setPolyToPoly does not work for all the cases.

like image 141
h2nghia Avatar answered Nov 15 '22 07:11

h2nghia