我正在更新一些OpenCV 1.1代码(即使用IplImages)写入的(我猜)OpenCV代码。OpenCV:加载多个图像
我现在想要完成的是简单地加载一系列图像(作为命令行参数传递)作为Mats。这是更大任务的一部分。下面的第一个代码示例是旧代码的图像加载方法。它从命令行加载5个图像并按顺序显示它们,在每个图像之后暂停键击,然后退出。
第二个代码示例是我使用Mat的更新版本。到目前为止它工作正常,但是这是做到这一点的最佳方式吗?我使用了一系列的垫子。我应该使用指向Mats的指针数组吗?有没有办法做到这一点,使图像的数量在运行时从argc
确定,并不需要提前设置IMAGE_NUM
。
基本上,我想能够通过图像作为命令行参数的任何数量的(在合理范围内),并将它们加载到一些方便的阵列或其他类似的存储以供以后参考。
谢谢。
旧代码:
#include <iostream>
#include <cv.h>
#include <cxcore.h>
#include <highgui.h>
using namespace std;
using namespace cv;
// the number of input images
#define IMAGE_NUM 5
int main(int argc, char **argv)
{
uchar **imgdata;
IplImage **img;
int index = 0;
char *img_file[IMAGE_NUM];
cout << "Loading files" << endl;
while(++index < argc)
if (index <= IMAGE_NUM)
img_file[index-1] = argv[index];
// malloc memory for images
img = (IplImage **)malloc(IMAGE_NUM * sizeof(IplImage *)); // Allocates memory to store just an IplImage pointer for each image loaded
imgdata = (uchar **)malloc(IMAGE_NUM * sizeof(uchar *));
// load images. Note: cvLoadImage actually allocates the memory for the images
for (index = 0; index < IMAGE_NUM; index++) {
img[index] = cvLoadImage(img_file[index], 1);
if (!img[index]->imageData){
cout << "Image data not loaded properly" << endl;
return -1;
}
imgdata[index] = (uchar *)img[index]->imageData;
}
for (index = 0; index < IMAGE_NUM; index++){
imshow("myWin", img[index]);
waitKey(0);
}
cvDestroyWindow("myWin");
cvReleaseImage(img);
return 0;
}
新代码:
#include <iostream>
#include <cv.h>
#include <cxcore.h>
#include <highgui.h>
#include <time.h>
using namespace std;
using namespace cv;
// the number of input images
#define IMAGE_NUM 5
int main(int argc, char **argv)
{
Mat img[IMAGE_NUM];
int index = 0;
for (index = 0; index < IMAGE_NUM; index++) {
img[index] = imread(argv[index+1]);
if (!img[index].data){
cout << "Image data not loaded properly" << endl;
cin.get();
return -1;
}
}
for (index = 0; index < IMAGE_NUM; index++) {
imshow("myWin", img[index]);
waitKey(0);
}
cvDestroyWindow("myWin");
return 0;
}
快速更新:当Gootik回复时,我不熟悉Standad Template Library的std :: vector,并且没有看到他的建议中的值。现在我对矢量更加熟悉,我更喜欢他的建议,虽然我的工作对我的目的来说确实很好。 – SSilk 2011-08-08 13:50:13