Search code examples
androidopencvcanvasimage-rotation

Canvas returns black image on rotate


I'm ussing OpenCV, the face recognizer project example one, made by Robotic Apps team, for Android, but camera is not as expected, the rotation has bugs and in order to rotate the camera view to use in Portrait orientation, we have to rotate the canvas inside of CameraBridgeViewBase class in the deliverAndDrawFrame method, i have the next canvas rotation method:

canvas.drawColor(0, android.graphics.PorterDuff.Mode.CLEAR);
canvas.rotate(180);
mScale = canvas.getWidth() / (float) mCacheBitmap.getHeight();
float scale2 = canvas.getHeight() / (float) mCacheBitmap.getWidth();
if (scale2 > mScale) {
    mScale = scale2;
}
if (mScale != 0) {
     canvas.scale(mScale, mScale, 0, 0);
}
Log.d(TAG, "mStretch value: " + mScale);
canvas.drawBitmap(mCacheBitmap, 0, -mCacheBitmap.getHeight(), null);
// ...

When i use the rotate method with value 90 canvas.rotate(90); it returns the image rotated 90 degrees as expected, but when i rotate more than 90 or less than 90 like, 0, -90, 180, 270, etc. It returns a black image :(

What's the problem with this code?


Solution

  • It is about the coordinant system. Canvas property has a fill style default:"black". Since your image gets out of the scene you have a black image. In your situation you are rotating it around (0,0). You should change your image's origin to middle of the image(width/2,height/2).