0

I am looking for a fast way to rotate a Bitmap 180 degrees using OpenCV on Android. Also, the Bitmap may be rotated in place, i.e. without allocation of additional memory.

Here riwnodennyk described different methods of rotating Bitmaps and compared their performances: https://stackoverflow.com/a/29734593/1707617. Here is GitHub repository for this study: https://github.com/riwnodennyk/ImageRotation.

This study doesn't include OpenCV implementation. So, I tried my own implementation of OpenCV rotator (only 180 degrees).

The best rotation methods for my test picture are as follows:

  • OpenCV: 13 ms
  • Ndk: 15 ms
  • Usual: 29 ms

Because OpenCV performance looks very promising and my implementation seems to be unoptimized, I decided to ask you how to implement it better.

My implementation with comments:

@Override
public Bitmap rotate(Bitmap srcBitmap, int angleCcw) {
    Mat srcMat = new Mat();
    Utils.bitmapToMat(srcBitmap, srcMat); // Possible memory allocation and copying
    
    Mat rotatedMat = new Mat();
    Core.flip(srcMat, rotatedMat, -1); // Possible memory allocation
    
    Bitmap dstBitmap = Bitmap.createBitmap(srcBitmap.getWidth(), srcBitmap.getHeight(), Bitmap.Config.ARGB_8888); // Unneeded memory allocation
    Utils.matToBitmap(rotatedMat, dstBitmap); // Unneeded copying

    return dstBitmap;
}

There are 3 places where, I suppose, unnecessary allocations and copying may take place.

Is it possible to get rid of theese unnecessary operations?

Ivan Bychkov
  • 269
  • 3
  • 8
  • 2
    you oughta check what `bitmapToMat` does exactly. does it reuse the memory? cv::Mat can do that, it doesn't "own" the memory then. same goes for `matToBitmap`. if you have `srcBitmap`, and you allocate `dstBitmap`, and the Mat objects (I don't know) are reusing those pieces of memory, then that's probably the smallest amount of allocations you can get. I don't know if cv::flip is able to operate truly in-place. docs don't say. it might use multithreading, which your other methods might not. – Christoph Rackwitz May 15 '22 at 20:01

1 Answers1

0

I implemented fast bitmap rotation library.

Performance (approximately):

  • 5 times faster than Matrix rotation method.
  • 3.8 times faster than Ndk rotation method.
  • 3.3 times faster than OpenCV rotation method.

https://github.com/ivankrylatskoe/fast-bitmap-rotation-lib

Ivan Bychkov
  • 269
  • 3
  • 8