반응형

SDL 기본 라이브러리는 BMP 형식의 이미지만 처리할 수 있다. JPG나 PNG 형식을 처리하기 위해서는 SDL_image 라이브러리가 필요하다.

 

우선 SDL 기본 라이브러리로 BMP 이미지를 렌더링 해 보자.

 

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
#include <iostream>
#include "SDL.h"
 
#pragma comment(lib, "sdl2.lib")
#pragma comment(lib, "sdl2main.lib")
 
int main(int argc, char* argv[]) {
    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        printf("SDL Initialization Fail: %s\n", SDL_GetError());
        return -1;
    }
 
    SDL_Window* window = SDL_CreateWindow("SDL Test", SDL_WINDOWPOS_UNDEFINED,
        SDL_WINDOWPOS_UNDEFINED, 640480, SDL_WINDOW_RESIZABLE);
 
    if (!window) {
        printf("SDL_CreateWindow Error: %s\n", SDL_GetError());
        SDL_Quit();
        return -1;
    }
 
    SDL_Renderer* renderer = SDL_CreateRenderer(window, -10);
 
    SDL_Surface* bmpSurface = SDL_LoadBMP("image.bmp");
    // Load a BMP image from a file path.
    if (bmpSurface == NULL) {
        SDL_DestroyRenderer(renderer);
        SDL_DestroyWindow(window);
        printf("SDL_LoadBMP Error: %s\n", SDL_GetError());
        SDL_Quit();
        return -1;
    }
    SDL_Rect destRect = { 00, bmpSurface->w, bmpSurface->h };
 
    SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, bmpSurface);
    // Create a texture from an existing surface.
    if (texture == NULL) {
        SDL_FreeSurface(bmpSurface);
        // Free an RGB surface.
        SDL_DestroyRenderer(renderer);
        SDL_DestroyWindow(window);
        printf("SDL_CreateTextureFromSurface Error: %s\n", SDL_GetError());
        SDL_Quit();
        return -1;
    }
    SDL_FreeSurface(bmpSurface);
 
    SDL_Event event;
    bool quit = false;
 
    while (!quit) {
        while (SDL_PollEvent(&event)) {
            switch (event.type) {
            case SDL_QUIT:
                quit = true;
                break;
            case SDL_KEYDOWN:
                printf("Key pressed: %s\n", SDL_GetKeyName(event.key.keysym.sym));
                if (event.key.keysym.sym == SDLK_ESCAPE)
                    quit = true;
                break;
            default:
                break;
            }
        }
 
        SDL_SetRenderDrawColor(renderer, 255255255, SDL_ALPHA_OPAQUE);
        SDL_RenderClear(renderer);
        SDL_RenderCopy(renderer, texture, NULL&destRect);
        // Copy a portion of the texture to the current rendering target.
        SDL_RenderPresent(renderer);
    }
 
    SDL_DestroyTexture(texture);
    // Destroy the specified texture.
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();
 
    return 0;
}
 

 

코드를 작성하고 빌드한다.

 

실행하면 윈도우에 이미지가 렌더링 된다.

 

만약 그래픽 카드의 지원을 받을 수 없는 Embedded System 등에서 소프트웨어 방식의 렌더링만 사용할 수 있다면 Texture, Renderer 를 사용하지 않고 Window Surface, BMP Surface 를 사용해 직접 화면에 이미지를 출력할 수 있다.

 

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
#include <iostream>
#include "SDL.h"
 
#pragma comment(lib, "sdl2.lib")
#pragma comment(lib, "sdl2main.lib")
 
int main(int argc, char* argv[]) {
    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        printf("SDL Initialization Fail: %s\n", SDL_GetError());
        return -1;
    }
 
    SDL_Window* window = SDL_CreateWindow("SDL Test", SDL_WINDOWPOS_UNDEFINED,
        SDL_WINDOWPOS_UNDEFINED, 640480, SDL_WINDOW_RESIZABLE);
 
    if (!window) {
        printf("SDL_CreateWindow Error: %s\n", SDL_GetError());
        SDL_Quit();
        return -1;
    }
 
    SDL_Surface* windowSurface = SDL_GetWindowSurface(window);
    // Get the SDL surface associated with the window.
    // A new surface will be created with the optimal format for the window,
    // if necessary. This surface will be freed when the window is destroyed.
    // Do not free this surface.
    // This surface will be invalidated if the window is resized. After resizing
    // a window this function must be called again to return a valid surface.
    // You may not combine this with 3D or the rendering API on this window.
 
    SDL_Surface* bmpSurface = SDL_LoadBMP("image.bmp");
    if (bmpSurface == NULL) {
        SDL_DestroyWindow(window);
        printf("SDL_LoadBMP Error: %s\n", SDL_GetError());
        SDL_Quit();
        return -1;
    }
 
    SDL_Event event;
    bool quit = false;
 
    while (!quit) {
        while (SDL_PollEvent(&event)) {
            switch (event.type) {
            case SDL_QUIT:
                quit = true;
                break;
            case SDL_KEYDOWN:
                printf("Key pressed: %s\n", SDL_GetKeyName(event.key.keysym.sym));
                if (event.key.keysym.sym == SDLK_ESCAPE)
                    quit = true;
                break;
            default:
                break;
            }
        }
 
        SDL_BlitSurface(bmpSurface, NULL, windowSurface, NULL);
        // Use this function to perform a fast surface copy to a destination surface.
        SDL_UpdateWindowSurface(window);
        // Copy the window surface to the screen. This is the function you use to
        // reflect any changes to the surface on the screen.
    }
 
    SDL_FreeSurface(bmpSurface);
    SDL_DestroyWindow(window);
    SDL_Quit();
 
    return 0;
}
 

 

코드를 작성하고 빌드한다.

 

윈도우에 이미지가 출력된다.

 

 

 

이번엔 SDL_image를 이용해 JPG, PNG 등의 이미지를 출력해 보자. 아래 링크에서 SDL_image를 다운받고 적당히 설치한다.

SDL Libraries

 

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
#include <iostream>
#include "SDL.h"
#include "SDL_image.h"
 
#pragma comment(lib, "sdl2.lib")
#pragma comment(lib, "sdl2main.lib")
#pragma comment(lib, "sdl2_image.lib")
 
int main(int argc, char* argv[]) {
    SDL_Init(SDL_INIT_VIDEO);
    SDL_Window* window = SDL_CreateWindow("SDL Test", SDL_WINDOWPOS_UNDEFINED,
        SDL_WINDOWPOS_UNDEFINED, 640480, SDL_WINDOW_RESIZABLE);
    SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
    // SDL_RENDERER_SOFTWARE: the renderer is a software fallback
    // SDL_RENDERER_ACCELERATED : the renderer uses hardware acceleration
    // SDL_RENDERER_PRESENTVSYNC : present is synchronized with the refresh rate
    // SDL_RENDERER_TARGETTEXTURE : the renderer supports rendering to texture
    // Note that providing no flags gives priority to available SDL_RENDERER_ACCELERATED
    // renderers.
 
    IMG_Init(IMG_INIT_JPG | IMG_INIT_PNG);
    // Initialize SDL_image.
 
    SDL_Surface* imageSurface = IMG_Load("image.png");
    // Load an image from a filesystem path into a software surface.
    SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, imageSurface);
    SDL_Rect destRect = { 00, imageSurface->w, imageSurface->h };
 
    SDL_Event event;
    bool quit = false;
 
    while (!quit) {
        while (SDL_PollEvent(&event)) {
            switch (event.type) {
            case SDL_QUIT:
                quit = true;
                break;
            case SDL_KEYDOWN:
                printf("Key pressed: %s\n", SDL_GetKeyName(event.key.keysym.sym));
                if (event.key.keysym.sym == SDLK_ESCAPE)
                    quit = true;
                break;
            default:
                break;
            }
        }
 
        //SDL_SetRenderDrawColor(renderer, 255, 255, 255, SDL_ALPHA_OPAQUE);
        //SDL_RenderClear(renderer);
        SDL_RenderCopy(renderer, texture, NULL&destRect);
        SDL_RenderPresent(renderer);
    }
 
    SDL_DestroyTexture(texture);
    SDL_FreeSurface(imageSurface);
    IMG_Quit();
    // Deinitialize SDL_image.
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();
 
    return 0;
}
 

 

코드를 입력하고 빌드한다.

 

실행하면 윈도우에 이미지가 렌더링 된다.

 

주석처리된 배경 처리 부분을 아래와 같이 해제하고 알파 채널이 있는 PNG 파일을 렌더링 해 보자.

 

SDL_SetRenderDrawColor(renderer, 0, 0, 255, SDL_ALPHA_OPAQUE);
SDL_RenderClear(renderer);

 

player.png
0.00MB

 

 

 

특별한 처리 없이도 알파 채널이 보존되어 투명한 부분이 잘 표현된다.

 

※ 참고

SDL_image API

 

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

아래 링크에서 SDL_ttf를 다운받아 설치하고 텍스트를 출력해 보자.

SDL_Libraries

 

SDL_ttf의 include, lib 디렉토리 파일들을 SDL 라이브러리에 적절히 복사한다.

 

sdl2_ttf.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <iostream>
#include "SDL.h"
#include "SDL_ttf.h"
 
int main(int argc, char* argv[]) {
    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        printf("SDL Initialization Fail: %s\n", SDL_GetError());
        return -1;
    }
 
    SDL_Window* window = SDL_CreateWindow("Hello World", SDL_WINDOWPOS_UNDEFINED,
        SDL_WINDOWPOS_UNDEFINED, 640480, SDL_WINDOW_RESIZABLE);
 
    if (!window) {
        printf("SDL_CreateWindow Error: %s\n", SDL_GetError());
        SDL_Quit();
        return -1;
    }
 
    SDL_Renderer* renderer = SDL_CreateRenderer(window, -10);
 
    if (TTF_Init() < 0) {
        // Initialize SDL_ttf.
        printf("SDL TTF Initialization Failed: %s\n", TTF_GetError());
        return -1;
    }
 
    TTF_Font* font = TTF_OpenFont("C:\\Windows\\Fonts\\arial.ttf"30);
    // Create a font from a file, using a specified point size.
    if (font == NULL) {
        printf("Could not open font! (%s)\n", TTF_GetError());
        return -1;
    }
    SDL_Color textColor = { 25500 };
    SDL_Surface* textSurface = TTF_RenderText_Blended(font, "Hello World!", textColor);
    // Render Latin1 text at high quality to a new ARGB surface.
    SDL_Texture* textTexture = SDL_CreateTextureFromSurface(renderer, textSurface);
    // Create a texture from an existing surface.
    SDL_FreeSurface(textSurface);
    // Free an RGB surface.
    SDL_Rect destRect = { 1010, textSurface->w, textSurface->h };
    TTF_CloseFont(font);
    // Dispose of a previously-created font.
 
    SDL_Event event;
    bool quit = false;
 
    while (!quit) {
        while (SDL_PollEvent(&event)) {
            switch (event.type) {
            case SDL_QUIT:
                quit = true;
                break;
            case SDL_KEYDOWN:
                printf("Key pressed: %s\n", SDL_GetKeyName(event.key.keysym.sym));
                if (event.key.keysym.sym == SDLK_ESCAPE)
                    quit = true;
                break;
            default:
                break;
            }
        }
 
        SDL_SetRenderDrawColor(renderer, 255255255, SDL_ALPHA_OPAQUE);
        SDL_RenderClear(renderer);
        SDL_RenderCopy(renderer, textTexture, NULL, &destRect);
        // Copy a portion of the texture to the current rendering target.
        SDL_RenderPresent(renderer);
    }
 
    TTF_Quit();
    // Deinitialize SDL_ttf.
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();
 
    return 0;
}
 

 

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

 

실행하면 윈도우에 텍스트가 렌더링 된다.

※ 참고

SDL_ttf API

 

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

아래 링크에서 SDL을 다운로드하고 C++을 이용해 사용할 수 있도록 설정해 보자.

Simple DirectMedia Layer

 

헤더 파일이 있는 Include 디렉토리를 설정한다.

 

라이브러리 파일이 있는 Library 디렉토리를 설정한다.

 

사용할 라이브러리 파일을 설정한다.

 

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
58
59
60
61
62
#include <iostream>
#include "SDL.h"
 
int main(int argc, char* argv[]) {
    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        // Initialize the SDL library.
        printf("SDL Initialization Fail: %s\n", SDL_GetError());
        // Retrieve a message about the last error that occurred on the current thread.
        return -1;
    }
 
    SDL_Window* window = SDL_CreateWindow("Hello World", SDL_WINDOWPOS_UNDEFINED,
        SDL_WINDOWPOS_UNDEFINED, 640480, SDL_WINDOW_RESIZABLE);
    // Create a window with the specified position, dimensions, and flags.
 
    if (!window) {
        printf("SDL_CreateWindow Error: %s\n", SDL_GetError());
        SDL_Quit();
        // Clean up all initialized subsystems.
        return -1;
    }
 
    SDL_Renderer* renderer = SDL_CreateRenderer(window, -10);
    // Create a 2D rendering context for a window.
 
    SDL_Event event;
    bool quit = false;
 
    while (!quit) {
        while (SDL_PollEvent(&event)) {
            // Poll for currently pending events.
            switch (event.type) {
            case SDL_QUIT:
                quit = true;
                break;
            case SDL_KEYDOWN:
                printf("Key pressed: %s\n", SDL_GetKeyName(event.key.keysym.sym));
                if (event.key.keysym.sym == SDLK_ESCAPE)
                    quit = true;
                break;
            default:
                break;
            }
        }
 
        SDL_SetRenderDrawColor(renderer, 255255255, SDL_ALPHA_OPAQUE);
        // Set the color used for drawing operations (Rect, Line and Clear).
        SDL_RenderClear(renderer);
        // Clear the current rendering target with the drawing color.
        SDL_RenderPresent(renderer);
        // Update the screen with any rendering performed since the previous call.
    }
 
    SDL_DestroyRenderer(renderer);
    // Destroy the rendering context for a window and free associated textures.
    SDL_DestroyWindow(window);
    // Destroy a window.
    SDL_Quit();
    // Clean up all initialized subsystems.
 
    return 0;
}
 

 

코드를 입력하고 빌드한다.

 

실행하면 윈도우가 나타난다.

 

콘솔창에는 키입력이 표시된다.

 

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

Python pypdf를 이용해 PDF 파일을 조작해 보자.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import os
from tkinter import filedialog
from pypdf import PdfWriter, PdfReader
 
filename = filedialog.askopenfilename(
    filetypes = (("PDF 파일""*.pdf"), ("모든 파일""*.*")),
    initialdir = os.getcwd())
 
reader = PdfReader(filename)
writer = PdfWriter()
 
newname = filename[0:-4]
ext = ".pdf"
 
try:
    for index in range(len(reader.pages)):
        writer.add_page(reader.pages[index])
        with open(newname+str(index+1)+ext, "wb"as pf:
            writer.write(pf)
            writer = PdfWriter() # writer 초기화.
        print(filename + "  ===>  " + newname+str(index+1)+ext)
except:
    print("Error")
 
 

 

여러장의 PDF 파일을 각각 한 페이지로 분리하는 코드를 작성한다.

 

코드를 실행하고 4장으로 이루어진 PDF 파일을 선택한다.

 

결과가 표시된다.

 

4장으로 분리 되었다.

 

이번엔 여러개의 PDF 파일들을 하나로 합쳐보자.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import os
from tkinter import filedialog
from pypdf import PdfWriter
 
filenames = filedialog.askopenfilenames(
    filetypes = (("PDF 파일""*.pdf"), ("모든 파일""*.*")),
    initialdir = os.getcwd())
 
merger = PdfWriter()
newname = filenames[0][0:-4]
ext = "_merged.pdf"
 
try:
    for pdf in filenames:
        merger.append(pdf)
    merger.write(newname+ext)
except:
    print("Error")
finally:
    print(filenames[0+ " ~ " + filenames[-1+ " merged.")
    merger.close()
 

 

코드를 작성하고 실행한다.

 

합치고 싶은 파일들을 선택한다.

 

문제가 없다면 결과가 표시된다.

 

선택한 파일들이 모두 합쳐졌다.

 

※ 참고

pypdf Documentation

 

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

Python Pillow 라이브러리를 이용해 PDF 변환기를 만들어 보자.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import os
from tkinter import filedialog
from PIL import Image
 
filename = filedialog.askopenfilename(
    filetypes = (("이미지 파일""*.jpg *.png"), ("모든 파일""*.*")),
    initialdir = os.getcwd())
# tkinter.filedialog.askopenfilename(**options)
# tkinter.filedialog.askopenfilenames(**options)
# The above two functions create an Open dialog and return the selected
# filename(s) that correspond to existing file(s).
 
newname = filename[0:-4]
ext = ".pdf"
 
try:
    with Image.open(filename) as pf:
        pf.save(newname + ext)
        print(filename + "  ===>  " + newname + ext)
except:
    print("Error")
 

 

파이썬 코드를 작성하고 실행한다.

 

파일 선택 다이얼로그에서 원하는 이미지 파일을 선택한다.

 

변환에 문제가 없다면 결과 화면이 출력된다.

 

PDF 파일이 생성된다.

 

※ 참고

Tkinter Dialogs

 

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

네이버에서 환율 정보를 scraping 하고 IFTTT를 이용해 SMS로 보낸다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from bs4 import BeautifulSoup as bs
import urllib.request as req
import requests
 
url = 'https://finance.naver.com/marketindex/' # 시장지표: 네이버 금융
res = req.urlopen(url)
 
soup = bs(res, 'html.parser')
title = soup.select_one('a.head > h3.h_lst').string
rate = soup.select_one('div.head_info > span.value').string
 
# IFTTT Platform
# To trigger an Event make a POST or GET web request to:
trigger_url = 'https://maker.ifttt.com/trigger/이벤트_입력/with/key/키_입력'
# With an optional JSON body of:
result = requests.post(trigger_url, data = { "value1" : title, "value2" : rate, "value3" : 'Sean' })
# The data is completely optional, and you can also pass value1, value2, and value3 as query parameters
# or form variables. This content will be passed on to the Action in your Recipe.
print('Result:', result, result.status_code, result.reason)
 

 

 

 

 

 

 

 

 

반응형

'Machine Learning' 카테고리의 다른 글

[Scraping] 환율 정보  (0) 2024.01.02
OCR with Tesseract on Windows - Windows에서 테서랙트 사용하기  (0) 2020.10.07
CSV 분석  (0) 2019.01.20
JSON 분석  (0) 2019.01.18
Beautifulsoup XML 분석  (0) 2019.01.15
Posted by J-sean
:
반응형

 환율 정보를 스크랩 해 보자.

 

네이버 환율 정보다.

 

크롬에서 F12를 누르면 위와 같은 정보가 표시된다. 정보를 태그와 클래스명으로 구분할 수 있을거 같다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import urllib.request
from bs4 import BeautifulSoup as bs
 
url = "https://m.stock.naver.com/marketindex/home/exchangeRate/exchange"
with urllib.request.urlopen(url) as response:
    html = response.read().decode('utf-8')
 
soup = bs(html, 'html.parser')
 
all_countries = soup.find_all('strong''MainListItem_name__2Nl6J')
all_rates = soup.find_all('span''MainListItem_price__dP8R6')
 
for country, rate in zip(all_countries, all_rates):
    print(country.string + ': ', rate.string)
 
#for i, c in enumerate(all_countries):
#    print(i+1, c.string)
 
#for i, r in enumerate(all_rates):
#    print(i+1, r.string)
 
#print(soup.find('strong', 'MainListItem_name__2Nl6J').string)
#print(soup.find('span', 'MainListItem_price__dP8R6').string)
 

 

같은 클래스명을 쓰는 정보가 여러개 있다. 모두 검색하여 표시한다.

 

환율 정보가 잘 표시된다.

 

반응형

'Machine Learning' 카테고리의 다른 글

[Scraping] 환율 정보를 SMS로 보내기  (3) 2024.01.02
OCR with Tesseract on Windows - Windows에서 테서랙트 사용하기  (0) 2020.10.07
CSV 분석  (0) 2019.01.20
JSON 분석  (0) 2019.01.18
Beautifulsoup XML 분석  (0) 2019.01.15
Posted by J-sean
:
반응형

픽셀 이미지(JPG, PNG)를 벡터(AI) 이미지로 바꿔보자.

 

일러스트레이터를 실행하고 변환할 이미지를 불러온다.

 

snoopy.jpg
0.09MB

 

 

Tracing으로 바꾼다.

 

변환할 이미지를 선택하고 Image Trace 탭에서 Auto-Color를 선택한다. 필요하다면 다른 옵션을 조절하고 Expand 버튼을 클릭한다.

 

픽셀 이미지가 벡터 이미지로 변환된다.

 

반응형
Posted by J-sean
: