1
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?

C++でif分岐, min(), max()を使わない畳み込み計算

Last updated at Posted at 2024-03-01

二次元・反射パディングです。imgにkerを畳み込んでimfに格納します。

#include<iostream>
#include<random>

int main() {
    int n=3,px=100,py=120;
	std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_real_distribution<float> dis(0.,255.);

    //配列作成
    float** img=new float*[py+2*n]+n;
	float** imf=new float*[py];
	float** ker=new float*[1+2*n]+n;
	for(int y=-n;y<=py+n;y++)
	{
		img[y]=new float[px+2*n]+n;
	}
	for(int y=0;y<py;y++)
	{
		imf[y]=new float[px];
	}
	for(int y=-n;y<=n;y++)
	{
		ker[y]=new float[1+2*n]+n;
	}
	//初期化
	for(int y=0;y<py;y++)
	{
		for(int x=0;x<px;x++)
		{
			img[y][x]=dis(gen);
		}
	}

	for(int x=0;x<px;x++)
	{
		for(int k=1;k<=n;k++)
		{
			img[py-1+k][x]=img[py-k][x];
			img[-k][x]=img[k-1][x];
		}
	}

	for(int y=-n;y<=py+n;y++)
	{
		for(int k=1;k<=n;k++)
		{
			img[y][-k]=img[y][k-1];
			img[y][px-1+k]=img[y][px-k];
		}
	}

	for(int y=0;y<py;y++)
	{
		for(int x=0;x<px;x++)
		{
			imf[y][x]=0.;
		}
	}

	for(int y=-n;y<=n;y++)
	{
		for(int x=-n;x<=n;x++)
		{
			ker[y][x]=1./((2*n+1)*(2*n+1));
		}
	}
	//畳み込み
	for(int y=0;y<py;y++)
	{
		for(int x=0;x<px;x++)
		{
			for(int ky=-n;ky<=n;ky++)
			{
				for(int kx=-n;kx<=n;kx++)
				{
					imf[y][x]+=img[y+ky][x+kx]*ker[ky][kx];
				}
			}
		}
	}
	//動作確認
	int Y=12,X=20;
	float S=0;
	for(int y=Y-n;y<=Y+n;y++)
	{
		for(int x=X-n;x<=X+n;x++)
		{
			S+=img[y][x]/((2*n+1)*(2*n+1));
		}
	}
	std::cout<<S<<std::endl;
	std::cout<<imf[Y][X]<<std::endl;
	//配列破棄
	for(int y=-n;y<py+n;y++)
	{
		delete[] (img[y]-n);
	}
	for(int y=0;y<py;y++)
	{
		delete[] imf[y];
	}
	for(int y=-n;y<=n;y++)
	{
		delete[] (ker[y]-n);
	}
    delete[] (img-n);
	delete[] (ker-n);

    return(0);
}
1
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
1
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?