C++ & OpenCV 断言失败

C++ & OpenCV assertion failed

我正在开发需要在 opencv 中进行以下 MATLAB 代码切换的应用程序。 这是我在 MATLAB 中的代码:

HSV = imread(k);
S=size(HSV)
x = zeros(3,S(1)*S(2));
k=1;
for i = 1:S(1)
  for j = 1:S(2)
    x(1,k)=i;
    x(2,k)=j; 
    x(3,k)=HSV(i,j,1); %H
    x(4,k)=HSV(i,j,2); %S 
    k=k+1;
  end
end

这是我在 OpenCV 中的代码,但我认为这是错误的:

IplImage* img;
img = cvLoadImage("---");

CvMat* x = cvCreateMat(4, img->width*img->height, CV_8UC3);
int k = 1;
for (int h = 1; h <= img->height; h++)
 {
  for (int w = 1; w <= img->width; w++)
  {
    CV_MAT_ELEM(*x, int, 1, k) = h; 
    CV_MAT_ELEM(*x, int, 2, k) = w;
    CV_MAT_ELEM(*x, int, 3, k) = CV_IMAGE_ELEM(img, uchar, h, 3 * w); //H
    CV_MAT_ELEM(*x, int, 4, k) = CV_IMAGE_ELEM(img, uchar, h, 3 * w + 1); //S 
    k = k + 1;
  }
}

我收到这样的错误:
断言失败:(unsigned)(4) < (unsigned)(k) && (unsigned)(k) < (unsigned)(*x).cols

Matlab 有基于 1 的索引,而 C 有基于 0 的索引 - 你所有的 for 循环和左边的 1-4 CV_MAT_ELEMs 需要从 0 到 length-1。