在OpenCV Android中访问相机帧像素

时间:2014-02-20 05:00:24

标签: android c++ opencv image-processing

我有以下c ++代码访问IplImage中的像素。这里有一个叫做的属性 IplImage中的imageData。我想将以下代码转换为OpenCV Android。

IplImage *imageIn = cvLoadImage(strFileImage, CV_LOAD_IMAGE_UNCHANGED);
IplImage *imageShirtHSV = cvCreateImage(cvGetSize(imageShirt), 8, 3);
cvCvtColor(imageShirt, imageShirtHSV, CV_BGR2HSV);

int h = imageShirtHSV->height;              
int w = imageShirtHSV->width;           
int rowSize = imageShirtHSV->widthStep; 
char *imOfs = imageShirtHSV->imageData;

for (int y=0; y<h; y++) {
    for (int x=0; x<w; x++) {
        // Get the HSV pixel components
        uchar H = *(uchar*)(imOfs + y*rowSize + x*3 + 0);   // Hue
        uchar S = *(uchar*)(imOfs + y*rowSize + x*3 + 1);   // Saturation
        uchar V = *(uchar*)(imOfs + y*rowSize + x*3 + 2);   // Value (Brightness)
    }
}

这就是我将上述c ++代码转换为OpenCV Android的方法。我使用double[] pixels = imageShirtHSV.get(y, x);作为c ++中char *imOfs = imageShirtHSV->imageData;的等价物。但是当我访问double []像素数组中的HSV值时,以下代码给出了ArrayIndexOutOfBoundsException。

imageIn = inputFrame.rgba();
Imgproc.cvtColor(imageIn, imageShirtHSV, Imgproc.COLOR_BGR2HSV);

int h = imageShirtHSV.height(); 
int w = imageShirtHSV.width();  
int rowSize = (int)imageShirtHSV.step1();   

for (int y=0; y<h; y++) {
    for (int x=0; x<w; x++) {
        double[] pixels = imageShirtHSV.get(y, x);

        int hVal = (int)pixels[(y*rowSize) + (x) + 0];  // Hue
        int sVal = (int)pixels[(y*rowSize) + (x) + 1];  // Saturation
        int vVal = (int)pixels[(y*rowSize) + (x) + 2];  // Value (Brightness)
    }
}

有人请指点我如何将c ++ char *imOfs = imageShirtHSV->imageData;行转换为OpenCV Android代码。非常感谢你。

1 个答案:

答案 0 :(得分:2)

这样:

double[] pixels = imageShirtHSV.get(y, x);

仅为您提供单个像素。你无法解决这样的邻居价值。

相反,分配一个数组来保存所有,然后访问: (这也很多更快!)

int h = imageShirtHSV.height(); 
int rowSize = (int)imageShirtHSV.step1();   
byte[] pixels = new byte[h*rowSize];
imageShirtHSV.get(0,0,pixels);

for (int y=0; y<h; y++) {
    for (int x=0; x<w; x++) {
        int hVal = (int)pixels[(y*rowSize) + (x) + 0];  // Hue
        int sVal = (int)pixels[(y*rowSize) + (x) + 1];  // Saturation
        int vVal = (int)pixels[(y*rowSize) + (x) + 2];  // Value (Brightness)
    }
}