본문 바로가기
프로그래밍˙알고리즘/C#ㆍXamarin

[C# Windows 프로그래밍] 이미지값을 배열에 담아서 두 이미지 비교하기

by 승주니 2020. 4. 24.
반응형

이미지의 Pixel값을 하나씩 불러와서 배열에 담고,

그 배열에 있는 값들을 서로 비교하면서 이미지가 같은지 틀린지를 구분할 수있다.

 

        private void Form1_Load(object sender, EventArgs e)
        {
            Bitmap bmp = new Bitmap("test1.jpg");
            pictureBox1.Image = bmp;
            Bitmap bmp2 = new Bitmap("test2.jpg");
            pictureBox2.Image = bmp2;
        }

먼저 이해를 쉽게 하기 위해 PictureBox1,PictureBox2를 폼에 띄워놓고 비교할 이미지를 불러온다.

 

        public void test()
        {
            Bitmap bmp1 = new Bitmap(pictureBox1.Image);
            Bitmap bmp2 = new Bitmap(pictureBox2.Image);
            
            if (bmp1.Width != bmp2.Width)
            {
                Console.WriteLine("이미지 크기가 다름!");
            }
            else if (bmp1.Height != bmp2.Height)
            {
                Console.WriteLine("이미지 크기가 다름!");
            }
            
            string[] result1 = new string[bmp1.Width * bmp1.Height];
            string[] result2 = new string[bmp2.Width * bmp2.Height];

            for (int i = 0; i < bmp1.Width; i++)
            {
                for(int j = 0; j < bmp1.Height; j++)
                {
                    string value1 = bmp1.GetPixel(i, j).ToString();
                    result1[j] = value1;
                    string value2 = bmp2.GetPixel(i, j).ToString();
                    result2[j] = value2;
                }
            }

            for(int c = 0; c < bmp1.Width * bmp1.Height; c++)
            {
                if(result1[c] == result2[c])
                {
                    ochabeomwe = ochabeomwe + 0;
                }
                else
                {
                    ochabeomwe = ochabeomwe + 1;
                }
            }

        }

 

Bitmap클래스로 bmp1,2를 생성해주고, 방금전에 넣었던 pictureBox1, pictureBox2로 인스턴스 초기화한다.

배열을 만드는과정에서 Width(너비) * Height(높이)는 이미지의 넓이를 구하는 공식이다.

 

그 다음으로 bmp1와 bmp2의 이미지 크기가 같은지 확인한다.

 

정수형 ochabeomwe 변수는 전역변수로 선언해둬야 한다.

 

맨 아래는 result1[배열번지], result2[배열번지]의 값이 틀리면 오차범위 값을 ochabeomwe + 1 한다.

(ochabeomwe = ochabeomwe + 0은 무의미한 식이지만 이해를 쉽게하기 위해 작성한 코드)

 

            if (ochabeomwe <= Convert.ToInt32(textBox1.Text))
            {
                Console.WriteLine("두 이미지는 동일하다.");
                ochabeomwe = 0;
            }
            else
            {
                Console.WriteLine("두 이미지는 동일하지 않다.");
                ochabeomwe = 0;
            }

마지막으로 이미지가 동일한지 확인하는 방법이다.

textbox1의 텍스트란에 오차범위로 설정하고싶은 값을 설정할 수 있다.

 

 

 

이 코드를 통해 이미지서치, 매크로 등을 만들수 있다.

반응형

댓글