반응형

C#에 MariaDB(MySQL) 데이터베이스를 연동해 보자.

 

NuGet Package Manager에서 MySql.Data를 설치한다.

 

위와 같은 데이터베이스를 준비한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
using MySql.Data.MySqlClient;
 
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string server = "192.168.171.200";
            string user = "root";
            string database = "member_db";
            string password = "1234";
            string connStr = $"server={server};user={user};database={database};port=3306;password={password}";
            MySqlConnection conn = new MySqlConnection(connStr);
 
            try
            {
                Console.WriteLine("Connecting to MySQL...");
                conn.Open();
                Console.WriteLine("Connected to MySQL.");
                // Perform database operations
 
                string sql = "SELECT * FROM member";
                MySqlCommand cmd = new MySqlCommand(sql, conn);
                MySqlDataReader rdr = cmd.ExecuteReader();
                // ExecuteReader to query the database.
                // ExecuteNonQuery to insert, update, and delete data.
 
                while (rdr.Read())
                {
                    Console.WriteLine($"ID: {rdr[0]}, Name: {rdr[1]}, Age: {rdr[2]}");
                }
                rdr.Close();
 
                sql = "SELECT name FROM member WHERE id='id2'";
                cmd = new MySqlCommand(sql, conn);
                object result = cmd.ExecuteScalar();
                // ExecuteScalar to return a single value.
 
                if (result != null)
                {
                    string name = Convert.ToString(result);
                    Console.WriteLine($"Name of id2: {name}.");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
 
            conn.Close();
        }
    }
}
 

 

소스를 입력하고 빌드한다.

 

요청한 데이터를 표시한다.

※ 참고

MySQL Connector/NET Developer Guide

 

반응형
Posted by J-sean
:
반응형

안드로이드 앱은 구글 애드몹(AdMob)으로 광고를 넣을 수 있지만 윈도우 데스크탑 프로그램은 광고를 넣을 수 없다.

AdsJumbo를 이용해 C# 윈폼(WinForm) 프로그램에 광고를 넣어보자.

 

NuGet Package Manager에서 AdsJumbo를 설치한다.

 

폼 디자인너 툴박스에 AdsJumboWinForm이 추가된다.

Nuget Package 설치 후 바로 툴박스에 추가되지 않는다면 솔루션을 다시 열어준다.

 

BannerAds와 InterstitialAd를 하나씩 적당히 배치한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace AdsJumbo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
 
            bannerAds1.ShowAd(72890"your_app_id");
            _ = AsyncAds();
            // Starting with C# 7.0, C# supports discards, which are placeholder
            // variables that are intentionally unused in application code.
            // Discards are equivalent to unassigned variables; they don't have
            // a value.
        }
 
        private async Task AsyncAds()
        {
            await Task.Delay(5000);
            interstitialAd1.ShowInterstitialAd("your_app_id");
            // The best place is to show an interstitial ad when the app is fully
            // loaded (eg. OnNavigated or your can simple timer await Task.Delay(2000) event)
        }
    }
}
 

 

소스를 입력하고 빌드한다.

 

 

프로그램을 실행하면 배너 광고가 표시된다.

 

5초후 전면 광고가 표시된다.

 

반응형
Posted by J-sean
:
반응형

C#으로 JSON 데이터를 파싱하고 원하는 값을 찾아보자.

 

아래와 같은 JSON 데이터 파일을 준비한다.

 

data.json
0.00MB

 

Newtonsoft.Json을 설치한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
using System.IO;
 
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
 
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string jsonData = File.ReadAllText(@"d:\data.json");
            //Console.WriteLine(jsonData);
 
            JObject jObject = JObject.Parse(jsonData);
            //Console.WriteLine(jObject.ToString());
 
            Console.WriteLine("Last Update: " + (jObject["LastUpdate"]));
            Console.WriteLine("SalesRecord Count: " + (jObject["SalesRecord"]).Count());
            Console.WriteLine("SalesRecord[2]\"total\": " + jObject["SalesRecord"][2]["total"]);
 
            JToken jToken = jObject["SalesRecord"];
            foreach (JToken data in jToken)
            {
                Console.WriteLine("■ " + data["date"+ ": " + data["item"]);
            }
 
            Item item = JsonConvert.DeserializeObject<Item>(jsonData);
            Console.WriteLine("Last Update: " + item.LastUpdate);
            foreach (Record record in item.SalesRecord)
            {
                Console.WriteLine("■ " + record.date + ": " + record.item);
            }
 
            string serializedJsonData = JsonConvert.SerializeObject(item);
            //Console.WriteLine(serializedJsonData);
            JObject serializedJObject = JObject.Parse(jsonData);
            //Console.WriteLine(serializedJObject);
        }
 
        // 모든 필드명이 json 데이터의 key와 일치해야 한다.
        class Item
        {
            public string LastUpdate;
            public List<Record> SalesRecord;
        }
 
        class Record
        {
            public string date;
            public string item;
            public int price;
            public int quantity;
            public int total;
        }
    }
}
 

 

소스를 입력하고 빌드한다.

 

JSON 데이터가 원하는대로 출력된다.

 

반응형
Posted by J-sean
:
반응형

HTTP 요청을 보내고 응답을 받아 보자.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
using System.Net.Http;
 
namespace ConsoleApp1
{
    class Program
    {
        // HttpClient is intended to be instantiated once per application, rather than per-use.
        static readonly HttpClient httpClient = new HttpClient();
 
        static async Task Main(string[] args)
        {
            try
            {
                Console.Write("Enter URI: ");
                string uriString = Console.ReadLine();
 
                HttpResponseMessage httpResponseMessage = await httpClient.GetAsync(uriString.Trim());
                httpResponseMessage.EnsureSuccessStatusCode();
                // Throws an exception if the IsSuccessStatusCode property for the HTTP response is false.
                string responseBody = await httpResponseMessage.Content.ReadAsStringAsync();
                // Above three lines can be replaced with new helper method below
                //string responseBody = await httpClient.GetStringAsync(uriString.Trim());
 
                Console.WriteLine(responseBody);
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
}
 

 

소스를 입력하고 빌드한다.

 

원하는 URI를 입력하면 데이터가 출력된다.

 

반응형
Posted by J-sean
:
반응형

WebRequest 클래스를 이용해 웹페이지 데이터(내용)를 요청해 보자.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
using System.Net;
using System.IO;
 
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            WebRequest webRequest = null;
            WebResponse webResponse = null;
 
            Stream stream = null;
            StreamReader streamReader = null;
 
            try
            {
                Console.Write("Enter URI: ");
                string uriString = Console.ReadLine();
 
                webRequest = WebRequest.Create(uriString.Trim());
                // If required by the server, set the credentials.
                webRequest.Credentials = CredentialCache.DefaultCredentials;
 
                webResponse = webRequest.GetResponse();
                Console.WriteLine("WebResponse status: " + ((HttpWebResponse)webResponse).StatusDescription);
 
                stream = webResponse.GetResponseStream();
                streamReader = new StreamReader(stream);
 
                string readString = streamReader.ReadToEnd();
                Console.WriteLine(readString);
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
            }
            finally
            {
                if (webResponse != null)
                    webResponse.Close();
                if (streamReader != null)
                    streamReader.Close();
                if (stream != null)
                    stream.Close();
            }
        }
    }
}
 

 

소스를 작성하고 빌드한다.

 

원하는 URI를 입력하면 데이터가 출력된다.

 

반응형
Posted by J-sean
:
반응형

C#으로 엑셀 데이터를 다뤄보자.

 

Microsoft Excel XX.X Object Library를 추가한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;
 
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Excel.Application application = new Excel.Application();
            application.Visible = false;
            Excel.Workbook workbook = application.Workbooks.Open(@"d:\test.xlsx");
 
            Console.WriteLine("Number of sheets: " + workbook.Worksheets.Count);
 
            Console.WriteLine();
 
            Excel.Worksheet worksheet1 = workbook.Worksheets.Item[1];
            Excel.Worksheet worksheet2 = workbook.Worksheets.Item[2];
            Excel.Worksheet worksheet3 = workbook.Worksheets.Item[3];
 
            Console.WriteLine("Name of 1st sheet: " + worksheet1.Name);
            Console.WriteLine("Name of 2nd sheet: " + worksheet2.Name);
            Console.WriteLine("Name of 3rd sheet: " + worksheet3.Name);
 
            Console.WriteLine();
 
            //Excel.Range cell1 = worksheet1.Range["C2"];
            Excel.Range cell1 = worksheet1.Cells[23];
            Console.WriteLine("1st sheet [2, 3]: " + cell1.Value);
 
            Console.WriteLine();
 
            Console.WriteLine("2nd sheet [3, 1]: " + worksheet2.Cells[31].Value);
 
            Console.WriteLine();
 
            //Excel.Range range = worksheet2.Range["A1:C3"];
            Excel.Range range = worksheet2.Range[worksheet2.Cells[11], worksheet2.Cells[33]];
            for (int i = 1; i < 4; i++)
                for (int j = 1; j < 4; j++)
                {
                    Console.WriteLine("2nd sheet [{0}, {1}]: {2}", i, j, range.Cells[i, j].Value);
                }
 
            Console.WriteLine();
 
            //Excel.Range find = worksheet2.Range["A1:C3"].Find("vwx", Type.Missing, Excel.XlFindLookIn.xlValues,
            //    Excel.XlLookAt.xlWhole, Excel.XlSearchOrder.xlByColumns, Excel.XlSearchDirection.xlNext, false);
            Excel.Range find = worksheet2.Range["A1:C3"].Find("vwx");
            Console.WriteLine($"{find.Address} [{find.Row}, {find.Column}]: {worksheet2.Range[find.Address].Value}");
 
            workbook.Close();
            application.Quit();
 
            Marshal.ReleaseComObject(worksheet1);
            Marshal.ReleaseComObject(worksheet2);
            Marshal.ReleaseComObject(worksheet3);
 
            Marshal.ReleaseComObject(workbook);
 
            Marshal.ReleaseComObject(application);
        }
    }
}
 

 

소스를 입력하고 빌드한다.

 

 

Sheet1

 

Sheet2

 

Sheet3

 

text.xlsx 의 정보가 표시된다.

 

반응형
Posted by J-sean
:

OpenCvSharp Simple Camera Example

C# 2022. 1. 14. 18:07 |
반응형

C#과 OpenCvSharp를 이용한 간단한 카메라 응용 프로그램 예.

 

폼에 Button, RadioButton, PictureBox등을 적당히 배치한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
using System.Threading;
using OpenCvSharp;
using OpenCvSharp.Extensions;
 
namespace OpenCV
{
    delegate void dele(Mat m);
 
    public partial class Form1 : Form
    {
        bool isCameraOn;
 
        dele filter;    // 카메라에 적용할 필터(효과) 델리게이트
        Thread thread;
        Mat mat;
        VideoCapture videoCapture;
 
        public Form1()
        {
            InitializeComponent();
 
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
            pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
            button1.Text = "Camera Start";
            isCameraOn = false;
            filter = null;
            radioButton1.Checked = true;
        }
 
        private void CameraCallback()
        {
            mat = new Mat();
            videoCapture = new VideoCapture(0);
 
            if (!videoCapture.IsOpened())
            {
                Text = "Camera open failed!";
                MessageBox.Show("카메라를 열 수 없습니다. 연결 상태를 확인 해 주세요.");
 
                return;
            }
 
            while (true)
            {
                videoCapture.Read(mat);
 
                if (!mat.Empty() && filter != null)
                {
                    filter(mat);    // 선택된 라디오 버튼에 따른 필터 적용.                    
                }
 
                if (!mat.Empty())
                {
                    // 로고를 디스플레이하기 위해 그레이 이미지(1채널)는 컬러 포맷(3채널)으로 변환
                    if (mat.Channels() == 1)
                    {
                        Cv2.CvtColor(mat, mat, ColorConversionCodes.GRAY2BGR);
                    }
                    Cv2.PutText(mat, "SEAN"new OpenCvSharp.Point(550470), HersheyFonts.HersheyDuplex, 1new Scalar(00255), 2);
 
                    // 이 전 프레임에서 PictureBox에 로드된 비트맵 이미지를 Dispose하지 않으면 메모리 사용량이 크게 증가한다.
                    if (pictureBox1.Image != null)
                    {
                        pictureBox1.Image.Dispose();
                    }
                    pictureBox1.Image = BitmapConverter.ToBitmap(mat);
                }
            }
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            if (isCameraOn == false)
            {
                thread = new Thread(new ThreadStart(CameraCallback));
 
                thread.Start();
                isCameraOn = true;
                button1.Text = "Camera Stop";
            }
            else
            {
                if (videoCapture.IsOpened())
                {
                    thread.Abort();
                    if (pictureBox1.Image != null)
                    {
                        pictureBox1.Image.Dispose();
                    }
                    videoCapture.Release();
                    mat.Release();
                }
                isCameraOn = false;
                button1.Text = "Camera Start";
            }
        }
 
        private void button2_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("https://s-engineer.tistory.com/");
        }
 
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (thread != null && thread.IsAlive && videoCapture.IsOpened())
            {
                thread.Abort();
                if (pictureBox1.Image != null)
                {
                    pictureBox1.Image.Dispose();
                }
                videoCapture.Release();
                mat.Release();
            }
        }
 
        // 필터 함수들
        private void ToGray(Mat mat)
        {
            Cv2.CvtColor(mat, mat, ColorConversionCodes.BGR2GRAY);
        }
 
        private void ToEmboss(Mat mat)
        {
            float[] data = { -1.0f, -1.0f, 0.0f, -1.0f, 0f, 1.0f, 0.0f, 1.0f, 1.0f };
            Mat emboss = new Mat(33, MatType.CV_32FC1, data);
 
            Cv2.CvtColor(mat, mat, ColorConversionCodes.BGR2GRAY);
            Cv2.Filter2D(mat, mat, -1, emboss, new OpenCvSharp.Point(-1-1), 128);
 
            emboss.Release();
        }
 
        private void ToBlur(Mat mat)
        {
            Cv2.GaussianBlur(mat, mat, new OpenCvSharp.Size(), (double)3);
        }
 
        private void ToSharpen(Mat mat)
        {
            Mat blurred = new Mat();
            Cv2.GaussianBlur(mat, blurred, new OpenCvSharp.Size(), (double)3);
 
            // 아래 연산이 반복되면 메모리 사용량이 크게 증가한다.
            float alpha = 2.0f;
            ((1 + alpha) * mat - alpha * blurred).ToMat().CopyTo(mat);
            //mat = (1 + alpha) * mat - alpha * blurred;
 
            blurred.Release();
        }
 
        private void ToEdge(Mat mat)
        {
            Cv2.CvtColor(mat, mat, ColorConversionCodes.BGR2GRAY);
            Cv2.Canny(mat, mat, 5070);
        }
 
        // 라디오 버튼 이벤트 핸들러들
        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            if (((RadioButton)sender).Checked)
            {
                filter = null;
            }
        }
 
        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            if (((RadioButton)sender).Checked)
            {
                filter = ToGray;
            }
        }
 
        private void radioButton3_CheckedChanged(object sender, EventArgs e)
        {
            if (((RadioButton)sender).Checked)
            {
                filter = ToEmboss;
            }
        }
 
        private void radioButton4_CheckedChanged(object sender, EventArgs e)
        {
            if (((RadioButton)sender).Checked)
            {
                filter = ToBlur;
            }
        }
 
        private void radioButton5_CheckedChanged(object sender, EventArgs e)
        {
            if (((RadioButton)sender).Checked)
            {
                filter = ToSharpen;
            }
        }
 
        private void radioButton6_CheckedChanged(object sender, EventArgs e)
        {
            if (((RadioButton)sender).Checked)
            {
                filter = ToEdge;
            }
        }
    }
}
 

 

소스를 입력하고 빌드한다.

 

프로그램을 실행하고 Camera Start 버튼을 클릭한다.

 

다른 필터를 선택하면 그에 맞는 화면이 출력된다.

 

※ 소스에서 ToSharpen() 의 주석 부분은 제대로 실행되지 않는다. 관련 내용은 아래 링크를 참고하자.

2022.01.14 - [C#] - OpenCvSharp Simple Example and MatExpr

 

※ ToSharpen() 의 반복 실행으로 인한 메모리 사용량 증가는 OpenCV의 메모리 할당을 파악하지 못하는 .NET Garbage Collector의 문제다. 아래와 같이 Garbage Collector 호출 코드 추가로 해결은 가능하다.

1
2
3
4
5
6
7
8
9
10
11
12
private void ToSharpen(Mat mat)
{
    Mat blurred = new Mat();
    Cv2.GaussianBlur(mat, blurred, new OpenCvSharp.Size(), (double)3);
 
    float alpha = 2.0f;
    ((1 + alpha) * mat - alpha * blurred).ToMat().CopyTo(mat);
 
    GC.Collect();
 
    blurred.Release();
}
 

 

https://github.com/shimat/opencvsharp/issues/391

 

반응형
Posted by J-sean
:
반응형

C#과 OpenCvSharp를 이용한 간단한 이미지 변환 예.

 

폼에 Button과 PictureBox를 적당히 배치한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
using OpenCvSharp;
 
namespace OpenCV
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog dlg = new OpenFileDialog();
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    Mat mat = Cv2.ImRead(dlg.FileName);
 
                    if (pictureBox1.Image != null)
                    {
                        pictureBox1.Image.Dispose();
                    }
 
                    // Canny Edge Detection(컬러 이미지를 그레이 이미지로 변환 후 Canny Edge Detection)
                    //Cv2.CvtColor(mat, mat, ColorConversionCodes.BGR2GRAY);
                    //Cv2.Canny(mat, mat, 50, 100);
 
                    // 이미지 샤프닝(가우시안블러 후 샤프닝)
                    Mat blurred = new Mat();
                    Cv2.GaussianBlur(mat, blurred, new OpenCvSharp.Size(), (double)3);
 
                    float alpha = 2.0f;
                    mat = (1 + alpha) * mat - alpha * blurred;
                    //((1 + alpha) * mat - alpha * blurred).ToMat().CopyTo(mat);
 
                    // PictureBox에 이미지 디스플레이(Mat to Bitmap)
                    System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(mat.ToBytes());
                    pictureBox1.Image = new Bitmap(memoryStream);
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }
    }
}
 

 

이미지 샤프닝 예제를 입력하고 빌드한다.

 

프로그램을 실행하고 이미지를 불러오면 샤프닝 처리가 되어 표시된다.

 

원본 이미지

 

1
2
3
4
5
6
7
// 이미지 샤프닝(가우시안블러 후 샤프닝)
Mat blurred = new Mat();
Cv2.GaussianBlur(mat, blurred, new OpenCvSharp.Size(), (double)3);
 
float alpha = 2.0f;
mat = (1 + alpha) * mat - alpha * blurred;
//((1 + alpha) * mat - alpha * blurred).ToMat().CopyTo(mat);
 

 

이미지 샤프닝 코드 부분을 보면 위와같이 Mat 클래스에 +, -, * 등의 연산을 직접한다. 이 때 Mat 클래스는 효율을 높이기 위해 MatExpr 클래스로 변환 되어 연산이 진행된다.

 

위 예제에서는 별 문제 없지만 Mat 클래스 인스턴스의 레퍼런스(포인터)가 함수의 파라미터로 넘어 오고 그 함수에서 계산해서 다시 리턴하는 등의 작업이 진행될 때는 이렇게 계산 결과를 대입하는 경우 계산된 데이터가 제대로 전달 되지 않는다. C++에서는 같은 방식으로 해도 문제가 없다. 내가 모르는 C#의 특성이 있는거 같다.

 

이럴때는 주석 부분과 같이 MatExpr 클래스로 변환 되는 부분을 괄호로 감싸고 MatExpr.ToMat()로 Mat 클래스로 변환해서 다시 Mat.CopyTo()로 복사한다. 아니면 함수의 파라미터 선언을 (ref Mat mat) 처럼 바꿔서 레퍼런스를 주고 받도록 바꾸면 된다. 아래 링크의 경우 델리게이트 선언도 레퍼런스를 주고 받도록 바꿔야 한다.

2022.01.14 - [C#] - OpenCvSharp Simple Camera Example

 

반응형
Posted by J-sean
: