Using OpenCv 2.4
I have two options to load images:
1- CvMat and Imread
2- IpImage and CvLoadImage
Which one is better to use? I tried mixing the two and end up in seg fault.
imread
returns a Mat
, not CvMat
. They are the two different interfaces (Mat
/imread
for C++ and Ipl... and Cv.. for C interface).
The C++ interface is nicer, safer and easier to use. It automatically handles memory for you, and allows you to write less code for the same task. The OpenCV guys advocate for the usage of C++, unless some very specific project requirements force you to C.
Example (C++)
cv::Mat image = imread("path/to/myimage.jpg")
if(image.empty())
return;
cv::imshow("Image", image);
cv::Mat bw = image > 128; // threshold image
cv::Mat crop = image(cv::Rect(0, 0, 100, 100)); // a 100px x 100px crop
crop= 0; // set image to 0
cv::waitKey();
// end code here
Note that if not stated otherwise, all matrix assignments reference the same data. In the example above, the crop
matrix points to image
, and setting it to zero will set that specific part of the image
to 0.
To create a new copy of data, use Mat::copyTo, or Mat::clone();
And the C interface
IplImage* pImg = CvLoadImage("path/to/myimage.jpg");
if(pImg == NULL)
return;
// ... big bloat to do the same operations with IplImage
CvShowImage("Image", pImg);
cvWaitKey();
CvReleaseImage(&pImg); // Do not forget to release memory.
// end code here