在 C++ 中使用 accumulate 的问题

Problems with using accumulate in c++

我正在使用 OpenCV 访问指定区域内像素的颜色数据,目前我正在尝试使用 c++ 中的 accumulate 方法来汇总在该指定区域内获得的所有数据编号。但现在它只给了我指定区域内一个像素的总和,而不是整个区域。我确定它给了我单个像素的总和,因为我使用了 push_back 方法并且它给了我该像素中的双倍数量。有什么我遗漏了没有写的吗?我是 C++ 的新手,所以如果有人能指出正确的方向,我将不胜感激。

    //the rows of the image
    for(int j=0; j<image; j++){
      int step = j*cols*elemSize;
      //the columns for the image
      for(int i-0; i<image; i++){
        int elm = i*elemSize;
        //obtaining the color data of the pixels
        uchar blue = image.data[step + elm + 0];
        uchar green = image.data[step + elm + 1];
        uchar red = image.data[step + elm + 2];
        std::vector<int> v = {blue};
        std::vector<int> w = {green};
        std::vector<int> x = {red};
        //using accumulate to sum up all the data
        int sumofblue = accumulate(v.begin(), v.end(), 0);
        int sumofgreen = accumulate(w.begin(), w.end(), 0);
        int sumofred = accumulate(x.begin(), x.end(), 0);

蓝绿红是从指定区域提取的颜色数据(0-255),image.data定义为提取使用的图像。

Is there something that I have missed and have not written?

您错过了您仍处于循环中间的事实。循环前需要定义vwx,每个元素相加,循环后累加。

std::vector<int> v;
std::vector<int> w;
std::vector<int> x;
//the rows of the image
for(int j=0; j<image/*??*/; j++){
  int step = j*cols*elemSize;
  //the columns for the image
  for(int i-0; i<image/*??*/; i++){
    int elm = i*elemSize;
    //obtaining the color data of the pixels
    v.push_back(image.data[step + elm + 0]);
    w.push_back(image.data[step + elm + 1]);
    x.push_back(image.data[step + elm + 2]);
  }
}

//using accumulate to sum up all the data
int sumofblue = accumulate(v.begin(), v.end(), 0);
int sumofgreen = accumulate(w.begin(), w.end(), 0);
int sumofred = accumulate(x.begin(), x.end(), 0);

不过你也可以在循环中使用 +=

int sumofblue = 0;
int sumofgreen = 0;
int sumofred = 0;
//the rows of the image
for(int j=0; j<image/*??*/; j++){
  int step = j*cols*elemSize;
  //the columns for the image
  for(int i-0; i<image/*??*/; i++){
    int elm = i*elemSize;
    //obtaining the color data of the pixels
    sumofblue += image.data[step + elm + 0];
    sumofgreen += image.data[step + elm + 1];
    sumofred += image.data[step + elm + 2];
  }
}

如果您可以访问 ranges library with stride and drop,则根本不需要嵌套循环。根据 image.data 的确切含义,您可能需要将其包装在 std::span

std::span data { image.data, image.data_size }; // cols * rows * elemSize?
auto blue = data | views::stride(3);
auto green = data | views::drop(1) | views::stride(3);
auto red = data | views::drop(2)  | views::stride(3);
int sumofblue = std::accumulate(begin(blue), end(blue), 0);
int sumofgreen = std::accumulate(begin(green), end(green), 0);
int sumofred = std::accumulate(begin(red), end(red), 0);