반응형

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
:

MariaDB(MySQL) C API

C, C++ 2021. 8. 29. 15:44 |
반응형

MariaDB도 MySQL과 거의 비슷한 방식으로 C API를 사용할 수 있다.

2018.11.20 - [C, C++] - MySQL C API

기본적인 내용은 MySQL C API와 거의 같고 아래와 같이 Project Property Pages에 Include/Library Directories 및 파일 이름만 변경 된다.

 

  • Project - XXX Properties... - Configuration Properties - C/C++ - General - Additional Include Directories - C:\Program Files\MariaDB 10.6\include
  • Project - XXX Properties... - Configuration Properties - Linker - General - Additional Library Directories - C:\Program Files\MariaDB 10.6\lib

 

아래 두 파일은 프로젝트 폴더에 복사한다. (libmysql.lib, libmysql.dll 이 아니다)

  • libmariadb.lib
  • libmariadb.dll

 

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
#include <stdio.h>
#include <mysql/mysql.h>
 
#pragma comment (lib, "libmariadb.lib")
 
int main()
{
    MYSQL mysql;            // MariaDB(MySQL) 정보를 담을 구조체
    MYSQL* mysqlPtr = NULL;    // MariaDB(MySQL) connection 핸들러
    MYSQL_RES* Result = NULL;        // 쿼리 성공시 결과를 담는 구조체 포인터
    MYSQL_ROW Row;            // 쿼리 성공시 결과로 나온 행의 정보를 담는 구조체
    int stat;                // 쿼리 요청 후 결과
 
    printf("MariaDB(MySQL) Client Version: %s\n\n", mysql_get_client_info());
    // Returns client version information as a string
 
    mysql_init(&mysql); // Gets or initializes a MYSQL structure 
 
    mysqlPtr = mysql_real_connect(&mysql, "127.0.0.1""root""password""database"3306, (char*)NULL0);
    // Connects to a MariaDB(MySQL) server
 
    if (mysqlPtr == NULL)
    {
        printf("MariaDB(MySQL) connection error: %s\n", mysql_error(&mysql));
        // Returns the error message for the most recently invoked MariaDB(MySQL) function
        return 1;
    }
 
    // MariaDB(MySQL)에서 사용하는 문자세트를 Visual Studio가 사용하는 euc-kr로 바꾸기
    mysql_query(mysqlPtr, "set session character_set_connection=euckr");
    mysql_query(mysqlPtr, "set session character_set_results=euckr");
    mysql_query(mysqlPtr, "set session character_set_client=euckr");
 
    const char* Query = "SELECT * FROM table";
    stat = mysql_query(mysqlPtr, Query);    // Executes an SQLquery specified as a null-terminated string
    if (stat != 0)
    {
        printf("MariaDB(MySQL) connection error: %s\n", mysql_error(&mysql));
        return 1;
    }
 
    Result = mysql_store_result(mysqlPtr);    // Retrieves a complete result set to the client
    printf("Number of rows: %I64d\nNumber of columns: %d\n\n", Result->row_count, Result->field_count);
    while ((Row = mysql_fetch_row(Result)) != NULL)    // Fetches the next row from the result set 
    {
        for (unsigned int i = 0; i < Result->field_count; i++)
        {
            printf("%s ", Row[i]);
        }
        printf("\n");
    }
    
    mysql_free_result(Result);    // Frees memory used by a result set
    mysql_close(mysqlPtr);    // Closes a server connection
 
    return 0;
}
 

 

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

Python에서 windows API를 사용 할 수 있게 해 주는 모듈이다.

간단한 Desktop GUI 예제:

 

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
import win32api
import win32gui
import win32con
import win32ui
 
#hinstance = win32api.GetModuleHandle(None)
 
hWnd = win32gui.GetDesktopWindow()
# Retrieves a handle to the desktop window. The desktop window covers the entire screen.
# The desktop window is the area on top of which other windows are painted.
hdc = win32gui.GetDC(hWnd)
#win32gui.GetDC(None)
# A handle to the window whose DC is to be retrieved. If this value is NULL, GetDC
# retrieves the DC for the entire screen.
 
hMemDC = win32gui.CreateCompatibleDC(hdc)
 
hImage = win32gui.LoadImage(None, "cat.bmp", win32con.IMAGE_BITMAP, 00, win32con.LR_LOADFROMFILE | win32con.LR_CREATEDIBSECTION);
# Loads an icon, cursor, animated cursor, or bitmap
 
hOldBitmap = win32gui.SelectObject(hMemDC, hImage)
win32gui.BitBlt(hdc, 505050 + 40050 + 272, hMemDC, 00, win32con.SRCCOPY) # Image(400, 272) at (50, 50)
# The BitBlt function performs a bit-block transfer of the color data corresponding to a rectangle of pixels
# from the specified source device context into a destination device context.
 
win32gui.SelectObject(hMemDC, hOldBitmap)
win32gui.DeleteObject(hImage)
win32gui.DeleteDC(hMemDC)
win32gui.ReleaseDC(hWnd, hdc)
cs

 

결과

 

 

실행 방식에 따라 제대로 표시가 안되는 경우가 있다.

 

1) 스크립트파일 - 우클릭 - 연결 프로그램 - Python - 표시가 안되는 경우가 있다.

2) Console - 스크립트 파일 실행 - 잘 표시 된다.

 

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

Python에서 windows API를 사용 할 수 있게 해 주는 모듈이다.


간단한 Desktop GUI 예제:

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
import win32api
import win32gui
import win32con
import win32ui
 
hWnd = win32gui.GetDesktopWindow()
# Retrieves a handle to the desktop window. The desktop window covers the entire screen.
# The desktop window is the area on top of which other windows are painted.
hdc = win32gui.GetDC(hWnd)
#win32gui.GetDC(None)
# A handle to the window whose DC is to be retrieved. If this value is NULL, GetDC
# retrieves the DC for the entire screen.
 
red = win32api.RGB(25500)
win32gui.SetPixel(hdc, 00, red)  # (0, 0)에 빨간 점 그리기
 
MyPen = win32gui.CreatePen(win32con.PS_SOLID, 5, win32api.RGB(0,0,255));
OldPen = win32gui.SelectObject(hdc, MyPen);
 
win32gui.Rectangle(hdc, 5050100100# (50, 50, 100, 100)에 파란 선으로 사각형 그리기
 
win32gui.SelectObject(hdc, OldPen);
win32gui.DeleteObject(MyPen);
 
# 폰트 만들기
font_spec = {'name':'Arial''height':42'weight':30}
font = win32ui.CreateFont(font_spec)
#lf = win32gui.LOGFONT()
#lf.lfFaceName = "Times New Roman"
#lf.lfHeight = 100
#lf.lfWeight = win32con.FW_NORMAL
#hf = win32gui.CreateFontIndirect(lf)
 
oldfont = win32gui.SelectObject(hdc, font.GetSafeHandle())
 
win32gui.SetTextColor(hdc, win32api.RGB(255,0,0))
win32gui.SetBkColor(hdc, win32api.RGB(255,255,0))
#win32gui.SetBkMode(hdc, win32con.TRANSPARENT)
# Desktop window DC로는 SetBKMode()가 잘 작동하지 않는다
 
text = 'Software Engineer'
rect = win32gui.GetClientRect(hWnd)
win32gui.DrawText(hdc, text, len(text), rect, win32con.DT_CENTER | win32con.DT_VCENTER
                  | win32con.DT_SINGLELINE | win32con.DT_WORDBREAK)
# 화면 가운데 문자열 출력
 
win32gui.SelectObject(hdc,oldfont)
win32gui.DeleteObject(font.GetSafeHandle())
 
win32gui.ReleaseDC(hWnd, hdc)
cs


반응형

'Python' 카테고리의 다른 글

Pillow 이미지 서치(Image Search) 1  (0) 2018.11.30
pywin32 Windows Extensions for Python 2  (0) 2018.11.27
Pillow 화면 변화 감지(Pixel Checksum) 2  (0) 2018.11.21
Pillow 화면 변화 감지(Pixel Checksum) 1  (0) 2018.11.20
PyMySQL  (2) 2018.11.19
Posted by J-sean
:

Python C API

C, C++ 2018. 11. 21. 15:52 |
반응형

가장 간단하게 Python을 C에 embed 시키는 방법은 Very High Level interface를 사용 하는 것이다. VHL interface는 어플리케이션과 직접적인 상관 없이 Python script를 실행하기 위한 것이다.


관련 문서

Python/C API Reference Manual


우선 Python C API 관련 Include, Library 디렉토리를 프로젝트에 추가한다.


파이썬 공식 홈페이지에서 다운 받은 파이썬 인스톨러 패키지를 설치 했다면 Solution Configurations를 Release로 설정 한다. Debug 모드로 build 할 경우 pythonXX_d.lib를 찾을 수 없다는 에러가 발생한다. pythonXX_d.lib 파일을 생성하려면 파이썬 소스를 받아서 직접 컴파일해야 한다.


예제:

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
#pragma comment(lib, "python36.lib")
#include <Python.h>
 
int main(int argc, char *argv[])
{
    wchar_t *program = Py_DecodeLocale(argv[0], NULL);
    // Decode a byte string from the locale encoding with the surrogateescape error handler:
    // undecodable bytes are decoded as characters in range U+DC80..U+DCFF. If a byte sequence
    // can be decoded as a surrogate character, escape the bytes using the surrogateescape error
    // handler instead of decoding them.
    // Return a pointer to a newly allocated wide character string, use PyMem_RawFree() to free
    // the memory. If size is not NULL, write the number of wide characters excluding the null
    // character into *size
    if (program == NULL) {
        fprintf(stderr, "Fatal error: cannot decode argv[0]\n");
        exit(1);
    }
    Py_SetProgramName(program);  /* optional but recommended */
    // This function should be called before Py_Initialize() is called for the first time, if it
    // is called at all.It tells the interpreter the value of the argv[0] argument to the main()
    // function of the program(converted to wide characters).This is used by Py_GetPath() and some
    // other functions below to find the Python run - time libraries relative to the interpreter
    // executable.
 
    Py_Initialize();
    // Initialize the Python interpreter. In an application embedding Python, this should be called
    // before using any other Python/C API functions
    if (Py_IsInitialized())
    // Return true (nonzero) when the Python interpreter has been initialized, false (zero) if not.
    // After Py_FinalizeEx() is called, this returns false until Py_Initialize() is called again.
    {
        PyRun_SimpleString("print('Hello Python')");
        // This is a simplified interface to PyRun_SimpleStringFlags(), leaving the PyCompilerFlags*
        // argument set to NULL.
        PyRun_SimpleString("from time import time, ctime\n"
            "print('Today is', ctime(time()))\n");
        //PyRun_SimpleString("from time import time, ctime\nprint('Today is', ctime(time()))\n");
 
        if (Py_FinalizeEx() < 0)
        // Undo all initializations made by Py_Initialize() and subsequent use of Python/C API
        // functions, and destroy all sub-interpreters that were created and not yet destroyed
        // since the last call to Py_Initialize().
        {
            exit(120);
        }
        PyMem_RawFree(program);
        // Frees the memory block pointed to by p, which must have been returned by a previous call
        // to PyMem_RawMalloc(), PyMem_RawRealloc() or PyMem_RawCalloc().
        // Otherwise, or if PyMem_RawFree(p) has been called before, undefined behavior occurs.
        // If p is NULL, no operation is performed.
    }
 
    return 0;
}
cs


반응형
Posted by J-sean
: