Dale
Dale

Reputation: 5805

OpenCv Core.line draws white when color is expected

In an OpenCv4Android environment, when I create a Mat image and use Core.line() to draw on the image, it always shows a white instead of the color I specify.

white square instead of green square

I have seen a question related to gray scale, but the image I have has not been converted to gray.

public class DrawingTest extends AppCompatActivity {
    public static final Scalar GREEN = new Scalar(0,255,0);
    private RelativeLayout mLayout;
    private ImageView imageView;

    static {
        System.loadLibrary("opencv_java");
    }

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

        mLayout = (RelativeLayout) findViewById(R.id.activity_drawing_test);
        mLayout.setDrawingCacheEnabled(true);

        imageView = (ImageView) this.findViewById(imageView_dt);

        //test.jpg is in the drawable-nodpi folder, is an normal color jpg image.
        int drawableResourceId = getResources().getIdentifier("test", "drawable", getPackageName());
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), drawableResourceId);
        //Mat matImage = new Mat(); // Also white
        Mat matImage = new Mat(bitmap.getHeight(), bitmap.getWidth(), CV_8UC4);
        Utils.bitmapToMat(bitmap, matImage);


        // Attempt to draw a GREEN box, but it comes out white
        Core.line(matImage, new Point(new double[]{100,100}), new Point(new double[]{100, 200}), GREEN,4);
        Core.line(matImage, new Point(new double[]{100,200}), new Point(new double[]{200, 200}), GREEN,4);
        Core.line(matImage, new Point(new double[]{200,200}), new Point(new double[]{200, 100}), GREEN,4);
        Core.line(matImage, new Point(new double[]{200,100}), new Point(new double[]{100, 100}), GREEN,4);

        Bitmap bitmapToDisplay = Bitmap.createBitmap(matImage.cols(), matImage.rows(), Bitmap.Config.ARGB_8888);
        Utils.matToBitmap(matImage, bitmapToDisplay);
        imageView.setImageBitmap(bitmapToDisplay);
    }
}

Upvotes: 1

Views: 1594

Answers (1)

ZdaR
ZdaR

Reputation: 22954

The problem is with the color you have initialized

public static final Scalar GREEN = new Scalar(0,255,0); 

as per this statement

Mat matImage = new Mat(bitmap.getHeight(), bitmap.getWidth(), CV_8UC4);`

you are creating a 4-channel Mat, but initializing the GREEN Scalar with 3 components only, hence the 4th component, which defines the color of fourth channel of your line, which is set of default value 0 in your case.

So, what you are perceiving as white color is transparent in reality. You may fix this either by creating matImage with CV_8UC3 or changing your GREEN scalar to be public static final Scalar GREEN = new Scalar(0,255,0, 255);

Upvotes: 6

Related Questions