0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【画像処理100本ノックに挑戦】Q.9. ガウシアンフィルタ

Last updated at Posted at 2019-12-14

使用したライブラリ

【画像処理100本ノック】独自の画像入出力クラスを作る

Q.9. ガウシアンフィルタ

ガウシアンフィルタ(3x3、標準偏差1.3)を実装し、imori_noise.jpgのノイズを除去せよ。

畳み込みですね。普段は適当な閾値で切って、もっと大きなカーネルサイズで使ってます。速度が必要な時はFFTを使います。

int main()
{
	PPM ppm("imori_noise.pnm");
	int width = ppm.Get_width();
	int height = ppm.Get_height();
	PPM ppm2(width, height);

	auto kernel = [&](int i, int j)
	{
		double ret = 2;
		if (i == 0 && j == 0) ret = 4;
		else if (abs(i) == 1 && abs(j)==1) ret = 1;
		return ret;// / 16.;
	};

	auto conv = [&](const std::vector<std::vector<double>> &f)
	{
		std::vector < std::vector < double >> ret(width, std::vector<double>(height));
		for(int j=0; j<height; j++)
			for (int i = 0; i < width; i++)
			{
				ret[i][j] = 0;
			}
		for (int j = 0; j < height; j++)
			for (int i = 0; i < width; i++)
			{
				int sum = 0;
				for(int di=-1; di<=1; di++)
					for (int dj = -1; dj <= 1; dj++)
					{
						if (i - di >= 0 && i - di < width && j - dj >= 0 && j - di < height)
						{
							ret[i][j] += kernel(di, dj) * f[i - di][j - dj];
							sum += kernel(di, dj);
						}
					}
				ret[i][j] /= (double)sum;
			}
		return ret;
	};

	std::vector < std::vector < double >> arrr(width, std::vector<double>(height));
	std::vector < std::vector < double >> arrg(width, std::vector<double>(height));
	std::vector < std::vector < double >> arrb(width, std::vector<double>(height));
	for (int j = 0; j < height; j++)
		for (int i = 0; i < width; i++)
		{
			arrr[i][j] = ppm(i, j, 'r');
			arrg[i][j] = ppm(i, j, 'g');
			arrb[i][j] = ppm(i, j, 'b');
		}
	arrr = conv(arrr);
	arrg = conv(arrg);
	arrb = conv(arrb);

	for (int j = 0; j < height; j++)
		for (int i = 0; i < width; i++)
		{
			ppm2(i, j, 'r') = arrr[i][j];
			ppm2(i, j, 'g') = arrg[i][j];
			ppm2(i, j, 'b') = arrb[i][j];
		}

	ppm2.Flush("out.ppm");
	return 0;
}

imori_noise.jpg out.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?