我需要使用OpenCV获取灰度图像上许多像素的标量值信息。由于要遍历数十万像素,因此需要最快的方法。我在网上找到的每个来源都非常晦涩难懂。是否有一行简单的代码可以直接返回代表图像第一个通道(亮度)的简单整数值的标量值?
我需要使用OpenCV获取灰度图像上许多像素的标量值信息。由于要遍历数十万像素,因此需要最快的方法。我在网上找到的每个来源都非常晦涩难懂。是否有一行简单的代码可以直接返回代表图像第一个通道(亮度)的简单整数值的标量值?
for (int row=0;row<image.height;row++) {
unsigned char *data = image.ptr(row);
for (int col=0;col<image.width;col++) {
// then use *data for the pixel value, assuming you know the order, RGB etc
// Note 'rgb' is actually stored B,G,R
blue= *data++;
green = *data++;
red = *data++;
}
}
因为opencv在每一行的开头都会将数据填充到32位边界,所以您需要在每一行上获取数据指针。
关于Martin的帖子,你实际上可以使用OpenCV的Mat对象中的isContinuous()方法来检查内存是否被连续分配。以下是确保外部循环仅在可能情况下循环一次的常见习语:
#include <opencv2/core/core.hpp>
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<Vec3b>(i);
for (int j = 0; j < cols; j++)
{
Vec3b pixel = ptr[j];
}
}
return 0;
}