遍歷圖像在OpenCV中經(jīng)常用到,高效的方法是使用Pointer,需要考慮圖像size,避免出錯(cuò):
Mat& ScanImageAndReduceC(Mat& I, const uchar* const table)
{
CV_Assert(I.depth() == CV_8U); // 斷言是否8bit uchar
const int channels = I.channels();
int rows = I.rows;
int cols = I.cols * channels;
if (I.isContinuous())
{
cols *= rows; // 連續(xù)存儲(chǔ)則將列數(shù)設(shè)為row*col,行數(shù)row設(shè)為1
rows = 1;
}
// 遍歷圖像,修改
uchar *p;
for (int i = 0; i < rows; ++i)
{
p = I.ptr<uchar>(i);
for (int j = 0; j < cols; ++j)
// lookup table;讀取則直接 X = p[j]
//也可以用I.at<uchar>(row, col)來(lái)讀取指定元素(效率低)
p[j] = table[p[j]];
}
return I;
}
還可以使用 Iterator的方式進(jìn)行迭代,可以不用考慮圖像的size,會(huì)自動(dòng)處理:
Mat& ScanImageAndReduceIterator(Mat& I, const uchar* const table)
{
CV_Assert(I.depth() == CV_8U);
const int channels = I.channels();
switch (channels)
{
case 1: // 單通道 gray
{
MatIterator_<uchar> it, end;
for (it = I.begin<uchar>(), end = I.end<uchar>(); it != end; ++it)
*it = table[*it];
break;
}
case 3: // 3通道 RGB,使用 Vec3b
{
MatIterator_<Vec3b> it, end;
for (it = I.begin<Vec3b>(), end = I.end<Vec3b>(); it != end; ++it)
{
(*it)[0] = table[(*it)[0]];
(*it)[1] = table[(*it)[1]];
(*it)[2] = table[(*it)[2]];
}
}
default:
break;
}
return I;
}
除了上述兩種方法還有一種隨機(jī)訪問(wèn),使用I.at<type>(row, col),但這種方法效率低,除非需要訪問(wèn)特定元素,遍歷一般不考慮這種。使用指針的方式是最高效的,但是需要注意圖像的size,避免越界;而迭代器則方便點(diǎn),不需要考慮size問(wèn)題,但是效率稍低。