最近在做毕业设计,需要求出一帧二值图像上最左最右最上最下的坐标值。想到的一个方法如下(附上代码注释):
//灰度值为255点的点,取图像上的白点,白点以外的点,像素值为0
//图像是以左下角为坐标原点,横轴是X轴,竖轴是Y轴。注意下面四个值的设置
int xmin = pFrImg->width;
int ymin = pFrImg->height;
int xmax = 0;
int ymax = 0;
//下面是逐行扫描像素点,从左至右,从下到上(注意原点在左下角)
for (size_t row = 0; row<pFrImg->height; row++)
{
unsigned char * ptr = (unsigned char*)pFrImg->imageData+row*pFrImg- >width;//每一行数据
for (size_t cols = 0 ; cols<pFrImg->width; cols++)
{
if ( ptr[cols] == 255)
{
if (row <= ymin)
{
ymin = row;
}
if (cols <= xmin)
{
xmin = cols;
}
if (row >= ymax)
{
ymax = row;
}
if (cols > xmax)
{
xmax = cols;
}
}
}
}
int width = abs(xmax - xmin)+10;//矩形的宽高
int height = abs(ymax - ymin)+10;
printf("xmin = %d\n", xmin);//有助于观察各值变化情况
printf("xmax = %d\n", xmax);
printf("ymin = %d\n", ymin);
printf("ymax = %d\n", ymax);
printf("width = %d\n", width);
printf("height = %d\n", height);
printf("\n****************************************\n");
cvRectangle( pFrame, cvPoint(xmin,ymin), //在原视频中画矩形框
cvPoint(xmin + width, ymin+ height),
CV_RGB(255,0,0), 2, CV_AA,0);*/
cvRectangle(src, cvPoint(xmin,ymin), //在二值图像中画框框
cvPoint(xmin + width, ymin+ height),
CV_RGB(255,255,255), 2, CV_AA,0);
**********************************************************************
上面是按行扫描,如果是按列扫描,方法如下(贴上代码):
int step = pFrImg->widthStep/sizeof(uchar);//每一行像素个数。第一行字节数/每个像素点所占字节
unsigned char * ptr = (unsigned char*)pFrImg->imageData;
for (size_t cols = 0 ; cols<pFrImg->width; cols++)
{
for (size_t row = 0; row<pFrImg->height; row++)
{
if ( (ptr[cols + row*step] == 255))
{
if (row <= ymin)
{
ymin = row;
}
if (cols <= xmin)
{
xmin = cols;
}
if (row >= ymax)
{
ymax = row;
}
if (cols > xmax)
{
xmax = cols;
}
}
}
}