using namespace cv;
using namespace std;
Convert an IplImage or CvMat to an cv::Mat and a cv::Mat to an IplImage or CvMat:
// Assuming somewhere IplImage *iplimg; exists
// and has been allocated and cv::Mat Mimg has been defined
Mat imgMat(iplimg); //Construct an Mat image "img" out of an IplImage
Mimg = iplimg; //Or just set the header of pre existing cv::Mat
//Ming to iplimg's data (no copying is done)
//Convert to IplImage or CvMat, no data copying
IplImage ipl_img = img;
CvMat cvmat = img; // convert cv::Mat -> CvMat
A very simple way to operate on a rectanglular sub-region of an image (ROI – “Region of Interest”):
//Make a rectangle
Rect roi(10, 20, 100, 50);
//Point a cv::Mat header at it (no allocation is done)
Mat image_roi = image(roi);
A bit advanced, but should you want efficiently to sample from a circular region in an image (below, instead of sampling, we just draw into a BGR image) :
// the function returns x boundary coordinates of
// the circle for each y. RxV[y1] = x1 means that
// when y=y1, -x1 <=x<=x1 is inside the circle
void getCircularROI(int R, vector < int > & RxV)
{
RxV.resize(R+1);
for( int y = 0; y <= R; y++ )
RxV[y] = cvRound(sqrt((double)R*R - y*y));
}
// This draws a circle in the green channel
// (note the "[1]" for a BGR" image,
// blue and red channels are not modified),
// but is really an example of how to *sample* from a circular region.
void drawCircle(Mat &image, int R, Point center)
{
vector<int> RxV;
getCircularROI(R, RxV);
Mat_<Vec3b>& img = (Mat_<Vec3b>&)image; //3 channel pointer to image
for( int dy = -R; dy <= R; dy++ )
{
int Rx = RxV[abs(dy)];
for( int dx = -Rx; dx <= Rx; dx++ )
img(center.y+dy, center.x+dx)[1] = 255;
}
}