知识要点:图像行宽四字节对齐。
背景:以前都是使用opencv的Mat类型进行图像数据的操作,后面碰到函数对图像数据的输入类型为BYTE*,碰到图像复原显示后出现图像的扭曲或者重影。图像四字节对齐是如果图像宽不是4的倍数,那么opencv(其实大部分其他库也一样)会对每行数据进行填充(为了加快存储和读取,计算机读取数据以4字节为单位),使其填充为4的倍数,所以在获取每行图像首地址时的偏移量是widthstep(一定是4的倍数)而不一定是width(当width是4的倍数时,widthstep=width)。例如,
3*3的未填充图像
1 2 3
4 5 6
7 8 9
那么填充后为
1 2 3 @
4 5 6 @
7 8 9 @
如果将3*3的未填充图像放到存储空间中为1 2 3 4 5 6 7 8 9
填充后的图像为1 2 3 @ 4 5 6 @ 7 8 9 @
由于在Mat中没有widthstep的成员变量,需要自己计算widthstep。图像为Mat Img,widthStep计算如下:
widthStep=(img.cols*img.elemSize()+3)/4*4;
以下为像素访问的小例子,其功能是从Mat类型的中读取图像数据。并将图像数据保存到BYTE类型的数组中。最后将BYTE数据写入Mat类型中。并进行显示。功能比较简单,其目的主要是弄清楚图像行宽四字节对齐。方便以后读取出BYTE数据后进行处理。
#include<opencv.hpp>
#include<iostream>
using namespace cv;
using namespace std;
typedef unsigned char BYTE;
//获取图像数据,并将获取的图像数据放入新建的图像中。
int main()
{
Mat img = imread("图像宽度4字节.png");
BYTE *tSrc;
int tSheight = 0, tSwidth = 0, tDheight = 0, tDwidth = 0;
//测试的源图像高度和宽度
tSheight = img.rows;
tSwidth = img.cols;
//测试的目的图像高度和宽度
tDheight = tSheight;
tDwidth = tSwidth;
tSrc = new BYTE[tSheight*tSwidth * 3];
//计算行宽
int widthStep = (img.cols*img.elemSize() + 3) / 4 * 4;
//获取图像数据
for (int i = 0; i < tSheight; i++)
{
for (int j = 0; j < tSwidth; j++)
{
*(tSrc + i*tSwidth*3 + 3 * j + 0) = *(img.data + i*widthStep + 3 * j + 0);
*(tSrc + i*tSwidth*3 + 3 * j + 1) = *(img.data + i*widthStep + 3 * j + 1);
*(tSrc + i*tSwidth*3 + 3 * j + 2) = *(img.data + i*widthStep + 3 * j + 2);
}
}
//恢复原始图像并显示
Mat outimg = Mat(tDheight, tDwidth, CV_8UC3);
for (int i = 0; i < tDheight; i++)
{
for (int j = 0; j < tDwidth; j++)
{
*(outimg.data + i*widthStep + j * 3 + 0) = tSrc[i*tDwidth*3 + j * 3 + 0];
*(outimg.data + i*widthStep + j * 3 + 1) = tSrc[i*tDwidth*3 + j * 3 + 1];
*(outimg.data + i*widthStep + j * 3 + 2) = tSrc[i*tDwidth*3 + j * 3 + 2];
}
}
imshow("原始图像", img);
imshow("恢复的原始图像", outimg);
waitKey(0);
return 0;
}
效果图:

怕忘记,将其记录之。