我们在处理图像的过程中常会遇到只需要对图像一部分进行截取,即感兴趣区域(ROI)。我知道的在opencv中截取感兴趣区域的办法有两种,一种是通过 cvSetImageROI(src, rect)进行设置。
在opencv中Iplimage的结构体定义如下:
typedef struct _IplImage
{
int nSize; /* sizeof(IplImage) */
int ID; /* version (=0)*/
int nChannels; /* Most of OpenCV functions support 1,2,3 or 4 channels */
int alphaChannel; /* Ignored by OpenCV */
int depth; /* Pixel depth in bits: IPL_DEPTH_8U, IPL_DEPTH_8S, IPL_DEPTH_16S,
IPL_DEPTH_32S, IPL_DEPTH_32F and IPL_DEPTH_64F are supported. */
char colorModel[4]; /* Ignored by OpenCV */
char channelSeq[4]; /* ditto */
int dataOrder; /* 0 - interleaved color channels, 1 - separate color channels.
cvCreateImage can only create interleaved images */
int origin; /* 0 - top-left origin,
1 - bottom-left origin (Windows bitmaps style). */
int align; /* Alignment of image rows (4 or 8).
OpenCV ignores it and uses widthStep instead. */
int width; /* Image width in pixels. */
int height; /* Image height in pixels. */
struct _IplROI *roi; /* Image ROI. If NULL, the whole image is selected. */
struct _IplImage *maskROI; /* Must be NULL. */
void *imageId; /* " " */
struct _IplTileInfo *tileInfo; /* " " */
int imageSize; /* Image data size in bytes
(==image->height*image->widthStep
in case of interleaved data)*/
char *imageData; /* Pointer to aligned image data. */
int widthStep; /* Size of aligned image row in bytes. */
int BorderMode[4]; /* Ignored by OpenCV. */
int BorderConst[4]; /* Ditto. */
char *imageDataOrigin; /* Pointer to very origin of image data
(not necessarily aligned) -
needed for correct deallocation */
}
IplImage;
设置roi后,对原图的任何操作只会在roi区域内进行,通过 cvResetImageROI()可以对设置的roi进行释放。
所以截取图像roi区域可以采用如下方法:
第一步:将必需剪切的图像图像不局部设置为ROI
cvSetImageROI(src , cvRect(x,y,width,height));
第二步:修建一个与必需剪切的图像局部同样大小的新图像
cvCreateImage(cvSize(width,height),IPL_DEPTH,nchannels);
第三步:将源图像复制到修建的图像中
cvCopy(src,dst,0);
第四步:释放ROI区域
cvResetIamgeROI(src);
第二种方法是,采用遍历的方法, 。