2

我有一个可能很简单的问题,但我仍然不确定!

其实我只想平滑一个直方图,我不确定以下哪种方法是正确的。我会这样做吗:

vector<double> mask(3);
mask[0] = 0.25; mask[1] = 0.5; mask[2] = 0.25;

vector<double> tmpVect(histogram->size());
for (unsigned int i = 0; i < histogram->size(); i++)
  tmpVect[i] = (*histogram)[i];

for (int bin = 1; bin < histogram->size()-1; bin++) {
  double smoothedValue = 0;
  for (int i = 0; i < mask.size(); i++) {
    smoothedValue += tmpVect[bin-1+i]*mask[i];
  }
  (*histogram)[bin] = smoothedValue;
}

或者你通常会这样做吗?:

vector<double> mask(3);
mask[0] = 0.25; mask[1] = 0.5; mask[2] = 0.25;

for (int bin = 1; bin < histogram->size()-1; bin++) {
  double smoothedValue = 0;
  for (int i = 0; i < mask.size(); i++) {
    smoothedValue += (*histogram)[bin-1+i]*mask[i];
  }
  (*histogram)[bin] = smoothedValue;
}

我的问题是:首先将直方图复制到一个额外的向量中是否合理,这样当我在 bin 处平滑时,i我可以使用原始i-1值,或者我会简单地这样做smoothedValue += (*histogram)[bin-1+i]*mask[i];,以便我使用已经平滑i-1的值而不是原始值。

问候和感谢您的回复。

4

1 回答 1

3

您的直觉是正确的:您需要一个临时向量。否则,您最终将使用部分旧值和部分新值,结果将不正确。用一个简单的例子在纸上自己尝试一下。

There are two ways you can write this algorithm:

  1. Copy the data to a temporary vector first; then read from that one, and write to histogram. This is what you did in your first code fragment.
  2. Read from histogram and write to a temporary vector; then copy from the temporary vector back to histogram.

To prevent needless copying of data, you can use vector::swap. This is an extremely fast operation that swaps the contents of two vectors. Using strategy 2 above, this would result in:

vector<double> mask(3);
mask[0] = 0.25; mask[1] = 0.5; mask[2] = 0.25;

vector<double> newHistogram(histogram->size());

for (int bin = 1; bin < histogram->size()-1; bin++) {
  double smoothedValue = 0;
  for (int i = 0; i < mask.size(); i++) {
    smoothedValue += (*histogram)[bin-1+i]*mask[i];
  }
  newHistogram[bin] = smoothedValue;
}

histogram->swap(newHistogram);
于 2010-07-02T11:14:49.383 回答