opencv人脸识别,jni中Bitmap转BGR格式

来源:互联网 发布:魔力怀旧宠物满档数据 编辑:程序博客网 时间:2024/05/08 16:48

        续上篇,继续人脸识别。

        上篇虽然成功把Bitmap转为了BGRA的格式传到Mat矩阵中,但是在做人脸识别的过程中,需要的图像是3通道的,即BGR格式。虽然opencv中有函数cvtColor(test,bgr,CV_RGBA2BGR);可以将其转换,但是这样经过ARGB_8888->BGRA->BGR转了一大圈貌似浪费cpu和内存资源。不如直接将Bitmap的ARGB_8888直接转为BGR传到Mat矩阵中。代码如下:

public byte[] getPixelsBGR(Bitmap image) {    // calculate how many bytes our image consists of    int bytes = image.getByteCount();    ByteBuffer buffer = ByteBuffer.allocate(bytes); // Create a new buffer    image.copyPixelsToBuffer(buffer); // Move the byte data to the buffer    byte[] temp = buffer.array(); // Get the underlying array containing the data.    byte[] pixels = new byte[(temp.length/4) * 3]; // Allocate for BGR    // Copy pixels into place    for (int i = 0; i < temp.length/4; i++) {          pixels[i * 3] = temp[i * 4 + 2];//B    pixels[i * 3 + 1] = temp[i * 4 + 1]; //G        pixels[i * 3 + 2] = temp[i * 4 ];//R           }    return pixels;}


这样得到的数组就是BGR格式的图像数据,可以传递到Mat矩阵中,格式为CV_8UC3.

 

        但是这样全是自己写代码进行的转换,一次偶然发现完全没必要这么麻烦,完全可以有更简单的方法。。。看到了这篇文章:bitmap转mat

在安卓设备上进行人脸识别,效率比较重要,内存和cpu的消耗要降到最低。以上各种方法哪种用时最少,还有待验证。

0 0