关于OpenCV Mat读取像素值

来源:互联网 发布:ubuntu subline 编辑:程序博客网 时间:2024/06/14 20:14

最近开始使用OPenCV读取图像像素值,并做处理,裁剪出ROI区域,并做保存。

对于Mat类生成的对象,包含诸多属性,Mat.rows, Mat.cols分别表示图像的heighten和width属性。

Mat的坐标系从左上角(0,0)开始,到右下角(Mat.rows, Mat.cols)。采集像素按照rows为X轴,cols为Y轴,提取像素的模式如:

mat.at<char>(mat.rows, mat.cols), 与正常提取数据的方式相反的。主要原因是opencv保存数据的方式是按行保存,不像MATLAB一样按列保存的方式进行。

对于Rect对象的使用,需要注意,Rect有四个参数,x, y, width, height.四个参数是按照正常的坐标系工作的,width为X轴, height方向为Y轴,与读取像素的方式相反。

例如:我需要读取二值化以后的手部区域图像的

代码如下:

for(int i = 0; i < oldImg.rows; i++)//rows->height->Y
{
for (int j = 0; j < oldImg.cols; j++)//cols->width->X//提取像素值,按照i为rows, j为cols。
{


if (oldImg.at<uchar>(i, j) != 0)
{

if ((upperleftX == 0) || (upperleftX != 0 && upperleftX > j))
{
upperleftX = j;

}
if ((upperleftY == 0) || (upperleftY != 0 && upperleftY > i))
{
upperleftY = i;
}


if ((bottomrightX == 0) || (bottomrightX != 0 && bottomrightX < j))
{
bottomrightX = j;
}
if ((bottomrightY == 0) || (bottomrightY != 0 && bottomrightY < i))
{
bottomrightY = i;
}
}


}


}

clipImg = oldImg(Rect(upperleftX, upperleftY,   (bottomrightX - upperleftX),(bottomrightY - upperleftY)));//提取需要的区域,坐标系是正常坐标系,水平X,竖直Y