Fastest way to extract individual pixel data?

前端 未结 2 838
孤城傲影
孤城傲影 2020-12-07 03:15

I have to get information about the scalar value of a lot of pixels on a gray-scale image using OpenCV. It will be traversing hundreds of thousands of pixels so I need the

2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-07 03:38

    With regards to Martin's post, you can actually check if the memory is allocated continuously using the isContinuous() method in OpenCV's Mat object. The following is a common idiom for ensuring the outer loop only loops once if possible:

    #include 
    
    using namespace cv;
    
    int main(void)
    {
    
        Mat img = imread("test.jpg");
        int rows = img.rows;
        int cols = img.cols;
    
        if (img.isContinuous())
        {
            cols = rows * cols; // Loop over all pixels as 1D array.
            rows = 1;
        }
    
        for (int i = 0; i < rows; i++)
        {
            Vec3b *ptr = img.ptr(i);
            for (int j = 0; j < cols; j++)
            {
                Vec3b pixel = ptr[j];
            }
        }
    
        return 0;
    }
    

提交回复
热议问题