반응형

C# WinForm 으로 구글 클라우드 비전 API를 이용해 Detect localized objects in a single image 를 진행해 보자. 아래 링크를 참고해 기본 준비를 한다.

2022.02.11 - [C#] - C# Google Cloud Vision API - 구글 클라우드 비전 API 2

 

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
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 Google.Cloud.Vision.V1;
 
namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        ImageAnnotatorClient client;
 
        public Form1()
        {
            InitializeComponent();
 
            try
            {
                client = new ImageAnnotatorClientBuilder
                {
                    CredentialsPath = "your_credentials.json"
                }.Build();
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
                Close();
            }
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                System.Drawing.Image systemImage;
 
                OpenFileDialog dlg = new OpenFileDialog();
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    systemImage = System.Drawing.Image.FromFile(dlg.FileName);
                    pictureBox1.Image = systemImage;
 
                    pictureBox1.Refresh();
 
                    Graphics graphics = pictureBox1.CreateGraphics();
 
                    Google.Cloud.Vision.V1.Image visionImage = Google.Cloud.Vision.V1.Image.FromFile(dlg.FileName);
 
                    IReadOnlyList<LocalizedObjectAnnotation> annotations = client.DetectLocalizedObjects(visionImage);
                    foreach (LocalizedObjectAnnotation annotation in annotations)
                    {
                        Google.Protobuf.Collections.RepeatedField<NormalizedVertex> normalizedVertices =
                            annotation.BoundingPoly.NormalizedVertices;
 
                        int imageWidth = systemImage.Width;
                        int imageHeight = systemImage.Height;
                        // Google.Cloud.Vision.V1.Image 는 Width, Height 필드가 없다.
 
                        Rectangle rectangle = new Rectangle(
                            (int)(normalizedVertices[0].X * imageWidth),
                            (int)(normalizedVertices[0].Y * imageHeight),
                            (int)((normalizedVertices[2].X - normalizedVertices[0].X) * imageWidth),
                            (int)((normalizedVertices[2].Y - normalizedVertices[0].Y) * imageHeight)
                            );
                        // BoundingPoly.NormalizedVertices 는 0~1의 범위를 가지는 값이다.
 
                        StringFormat stringFormat = new StringFormat
                        {
                            Alignment = StringAlignment.Center,
                            LineAlignment = StringAlignment.Center
                        };
 
                        graphics.DrawRectangle(System.Drawing.Pens.Red, rectangle);
                        graphics.DrawString($"Name: {annotation.Name}\n ID: {annotation.Mid}\n Score: {annotation.Score}",
                            Font, Brushes.Red, rectangle, stringFormat);
                    }
 
                    graphics.Dispose();
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }
    }
}
 

 

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

 

 

 

 

 

 

 

 

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

C# WinForm 으로 구글 클라우드 비전 API 결과를 확인해 보자. 아래 링크를 참고해 기본적인 구글 클라우드 비전 API 사용 준비를 한다.

2022.02.11 - [C#] - C# Google Cloud Vision API - 구글 클라우드 비전 API 1

 

Visual Studio - NuGet Package Manager에서 Google.Cloud.Vision.V1을 설치한다.

 

PictureBox, Button을 적당히 배치한다.

 

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
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.IO;
using Google.Cloud.Vision.V1;
 
namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        ImageAnnotatorClient client;
 
        public Form1()
        {
            InitializeComponent();
 
            try
            {                
                client = new ImageAnnotatorClientBuilder
                {
                    CredentialsPath = "./values-324913-58dd97f8b8ec.json"                    
                }.Build();
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
                Close();
            }
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                System.Drawing.Image systemImage;
 
                OpenFileDialog dlg = new OpenFileDialog();
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    systemImage = System.Drawing.Image.FromFile(dlg.FileName);
                    pictureBox1.Image = systemImage;
 
                    pictureBox1.Refresh();
                    //Forces the control to invalidate its client area and immediately redraw itself and any child controls.
                    // 미리 Refresh()를 호출하지 않으면 아래 얼굴 영역 사각형, 신뢰도 텍스트 출력이 보이지 않는다.
 
                    Graphics graphics = pictureBox1.CreateGraphics();
 
                    Google.Cloud.Vision.V1.Image visionImage = Google.Cloud.Vision.V1.Image.FromFile(dlg.FileName);
                    //MemoryStream memoryStream = new MemoryStream();
                    //pictureBox1.Image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);
                    //Google.Cloud.Vision.V1.Image visionImage = Google.Cloud.Vision.V1.Image.FromBytes(memoryStream.ToArray());                    
                    // Google.Cloud.Vision.V1.Image와 System.Drawing.Image는 서로 호환되지 않는다.
                    
                    IReadOnlyList<FaceAnnotation> result = client.DetectFaces(visionImage);
                    foreach (FaceAnnotation face in result)
                    {
                        Google.Protobuf.Collections.RepeatedField<Vertex> vertices = face.BoundingPoly.Vertices;
                        
                        Rectangle rectangle = new Rectangle(vertices[0].X, vertices[0].Y, vertices[2].X - vertices[0].X,
                            vertices[2].Y - vertices[0].Y);
                        // 얼굴 영역 (vertices[0]: 좌상단, vertices[1]:우상단, vertices[2]:우하단, vertices[3]:좌하단)
                        StringFormat stringFormat = new StringFormat
                        {
                            Alignment = StringAlignment.Center,
                            LineAlignment = StringAlignment.Center
                        };
                        // 신뢰도 문자열 센터 정렬
 
                        graphics.DrawRectangle(System.Drawing.Pens.Red, rectangle);
                        graphics.DrawString($"Confidence: {(int)(face.DetectionConfidence * 100)}%", Font,
                            Brushes.Red, rectangle, stringFormat);
                    }
 
                    graphics.Dispose();
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }
    }
}
 

 

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

 

버튼을 클릭하고 이미지 파일을 불러온다.

 

 

불러온 이미지의 얼굴 영역에 사각형과 신뢰도가 표시된다.

 

얼굴 이미지가 잘리거나 명확하지 않으면 제대로 검출되지 않는다.

 

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

C#에서 구글 클라우드 비전 API를 사용해 보자.

 

Google Could Platform - APIs&amp;amp;amp;Services 에서 Cloud Vision API를 활성화(Enable)한다.

 

Service account key를 생성하고 JSON파일로 다운로드한다.

 

Visual Studio - NuGet Package Manager에서 Google.Cloud.Vision.V1을 설치한다.

 

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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
using System.IO;
using Google.Cloud.Vision.V1;
 
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Image image = Image.FromFile("./barbara.png");
                string credentialsString = File.ReadAllText("./your_jsoncredentials.json");
 
                ImageAnnotatorClient client = new ImageAnnotatorClientBuilder
                {
                    JsonCredentials = credentialsString
                    //CredentialsPath = "./your_jsoncredentials.json"
                    // 간단히 CredentialsPath에 서비스 계정 키(json) 파일을 직접 대입해도 된다.
                }.Build();
 
                IReadOnlyList<FaceAnnotation> result = client.DetectFaces(image);
                foreach (FaceAnnotation face in result)
                {
                    string poly = string.Join(" - ", face.BoundingPoly.Vertices.Select(v => $"({v.X}, {v.Y})"));
                    Console.WriteLine($"Confidence: {(int)(face.DetectionConfidence * 100)}%; BoundingPoly: {poly}");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
}
 

 

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

 

 

분석 이미지

 

분석 이미지의 얼굴 좌표와 신뢰도가 함께 표시된다.

 

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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
using Google.Cloud.Vision.V1;
using Newtonsoft.Json;
 
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Image image = Image.FromFile("./barbara.png");
                Credentials credentials = new Credentials
                {
                    type = "your_type",
                    project_id = "your_project_id",
                    private_key_id = "your_key_id",
                    private_key = "-----BEGIN PRIVATE KEY-----your_key-----END PRIVATE KEY-----\n",
                    client_email = "your_email",
                    client_id = "your_client_id",
                    auth_uri = "your_auth_uri",
                    token_uri = "your_token_uri",
                    auth_provider_x509_cert_url = "your_auth_cert_url",
                    client_x509_cert_url = "your_client_cert_url"
                };
 
                ImageAnnotatorClient client = new ImageAnnotatorClientBuilder
                {
                    JsonCredentials = JsonConvert.SerializeObject(credentials)
 
                }.Build();
 
                IReadOnlyList<FaceAnnotation> result = client.DetectFaces(image);
                foreach (FaceAnnotation face in result)
                {
                    string poly = string.Join(" - ", face.BoundingPoly.Vertices.Select(v => $"({v.X}, {v.Y})"));
                    Console.WriteLine($"Confidence: {(int)(face.DetectionConfidence * 100)}%; BoundingPoly: {poly}");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
 
    class Credentials
    {
        public string type;
        public string project_id;
        public string private_key_id;
        public string private_key;
        public string client_email;
        public string client_id;
        public string auth_uri;
        public string token_uri;
        public string auth_provider_x509_cert_url;
        public string client_x509_cert_url;
    }
}
 

 

위 소스처럼 서비스 계정 키(json)의 내용을 코드에 직접 삽입 할 수도 있다.

 

※ 참고

Google.Cloud.Vision.V1

 

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

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
: