반응형

Pygame으로 게임을 개발하기 위한 기본 코드를 작성해 보자. 

 

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
# Example file showing a basic pygame "game loop"
# pygame 기본 셋업
import os
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'= '1'
# pygame 실행시 표시되는 메세지를 보이지 않게 한다.
# pygame을 import 하기 전에 설정해야 한다.
import pygame
 
# pygame setup
pygame.init()
pygame.display.set_caption("Super fun game development")
# 게임창 제목 표시
screen = pygame.display.set_mode((640480))
# 게임창 크기를 640X480으로 설정.
clock = pygame.time.Clock()
running = True
 
while running:
    # poll for events
    # pygame.QUIT event means the user clicked X to close your window
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            running = False
 
    # fill the screen with a color to wipe away anything from last frame
    screen.fill("black")
 
    # RENDER YOUR GAME HERE
    pygame.draw.circle(screen, "gray", screen.get_rect().center, 100)
    # 스크린 중앙에 회색원을 하나 그린다.
 
    # flip() the display to put your work on screen
    pygame.display.flip()
 
    clock.tick(60)  # limits FPS to 60
 
pygame.quit()
 

 

 

코드를 실행하면 검은 배경에 회색 원이 하나 표시된다.

 

PYGAME_HIDE_SUPPORT_PROMPT를 설정하지 않으면 위와 같은 메세지가 표시된다.

 

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

파이썬에서 Google Speech to Text를 사용해 보자.

 

SpeechRecognition을 설치한다.

 

마이크 사용을 위해 PyAudio를 설치한다.

 

소스를 입력하고 실행한다.

 

완벽하지는 않지만 꽤 잘 인식한다. ('현'이 아니라 '션'이었다)

 

 

마이크가 아닌 음성 파일을 이용하는 경우 위와 같이 소스를 수정한다.

 

get_XXX_data()를 이용하면 오디오 데이터를 raw, wav, flac 등의 파일로 저장할 수 있다.

 

※ 참고

SpeechRecognition

 

반응형
Posted by J-sean
:

MySQL(MariaDB) Connector

Python 2022. 5. 5. 00:15 |
반응형

2018.11.19 - [Python] - PyMySQL

 

Python에서 원격으로 MySQL(MariaDB)을 사용해 보자.

아래 링크를 참고해 데이터베이스를 준비한다.

2021.08.28 - [Linux] - Linux(Ubuntu) MariaDB(MySQL) Server Remote Access - 데이터베이스 원격 접속

 

mysql-connector-python을 설치한다.

 

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

 

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 mysql.connector
from mysql.connector import errorcode
 
try:
    cnx = mysql.connector.connect(host="192.168.171.20", user="root",
                                  passwd="1234", database="test_db",
                                  connection_timeout=5)
except mysql.connector.Error as err:
    if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print("Something is wrong with your user name or password")
    elif err.errno == errorcode.ER_BAD_DB_ERROR:
        print("Database does not exist")
    elif err.errno == 2003# 호스트 주소가 틀리거나 문제가 있다면
        print("Connection error(Timeout)")
    else:
        print(err)
else:   # 데이터베이스 접속 오류가 없다면
    cursor = cnx.cursor()
    
    query = ("SELECT * FROM test_tb")
    cursor.execute(query)
    for (id, name, age) in cursor:
        print("id: {}, name: {}, age: {}".format(id, name, age))
            
    #for row in cursor:
    #    print(row)
 
    cursor.close()
    cnx.close()
 

 

소스를 입력하고 실행한다.

 

데이터베이스의 내용이 출력된다.

 

※ 참고

MySQL Connector/Python Developer Guide

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

라즈베리 파이 카메라를 사용해 보자.


중국에서 구매한 라즈베리 파이용 카메라가 1주일만에 배송 되었다. 라즈베리 파이에서 판매하는 정품 카메라가 아닌 5MP 저가 호환 카메라이다. 약 3만원에 판매되는 8MP 정품 카메라보다 성능은 떨어지지만 가격이 1/10이다.


뒷면


HDMI Port와 Audio Jack 사이에 CSI Camera Port가 있다.


보호 테이프를 제거하고 latch를 들어 올린 다음 케이블을 삽입하고 고정한다.



라즈베리 파이를 부팅하고 Raspberry Pi Configuration에서 Camera - Enable을 선택한다. 재부팅 한다.


파이썬 Picamera 모듈을 사용해 보자. (Picamera 모듈은 기본 설치되어 있다)


파이썬 코드를 실행하면 라즈베리 파이에 연결한 카메라 LED에 불이 들어오고 preview 화면이 30초동안 표시된다.


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

리눅스(우분투)에 OpenCV-Python을 설치하자.


opencv-python을 설치하면 numpy도 함께 설치된다.


간단한 opencv 예제를 입력하고 파이썬 파일로 저장한다.


예제를 실행하면 이미지가 출력된다.


GUI가 없는 리눅스 서버에서는 실행되지 않는다. 이미지를 디스플레이 하는 코드가 포함되었기 때문인데 이미지 읽기, 저장, 연산등의 작업만 하는 프로그램은 문제 없이 실행된다.


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

파이썬으로 이메일(Gmail)을 보내보자.


Gmail 설정 화면. IMAP 사용으로 설정되어 있다. 이메일 클라이언트 구성 설정 방법을 확인해 보자.


발신 메일(SMTP) 서버 내용을 사용한다.


Gmail은 계정 비밀번호를 그대로 사용할 수 없다. Google 계정에서 앱 비밀번호를 생성해 사용해야 한다.


'생성할 앱 - 메일', '기기 - Windows 컴퓨터'를 선택하고 생성한다.



생선된 앱 비밀번호를 복사해 둔다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import smtplib
from email.mime.text import MIMEText
 
email_from = 'your email address'
email_to = 'recipient's email address'
email_subject = 'Email Test.'
email_content = 'Sending an email test.'
 
msg = MIMEText(email_content)
msg['From'= email_from
msg ['To'= email_to
msg['Subject'= email_subject
 
smtp = smtplib.SMTP('smtp.gmail.com'587)
smtp.starttls()
smtp.login('your email address''password')
smtp.sendmail("your email address""recipient's email address", msg.as_string())
 
print(msg.as_string())
 
smtp.quit()


위 코드를 입력하고 실행한다. smtp.login()의 'password'에는 위에서 생성한 앱 비밀번호를 입력한다.


에러 없이 실행되면 이메일이 보내진다.


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
# Import smtplib for the actual sending function
import smtplib
 
# Import the email modules we'll need
from email.message import EmailMessage
 
email_from = 'your email address'
email_to = 'recipient's email address'
email_subject = 'Email Test.'
email_content = 'Sending an email test.'
 
# Create a text/plain message
msg = EmailMessage()
msg.set_content(email_content)
 
# From == the sender's email address
# To == the recipient's email address
msg['From'= email_from
msg['To'= email_to
msg['Subject'= email_subject
 
# Send the message via our own SMTP server.
smtp = smtplib.SMTP('smtp.gmail.com'587)
smtp.starttls()
smtp.login('your email address''password')
smtp.send_message(msg)
 
print(msg.as_string())
 
smtp.quit()


위 코드로도 동일하게 진행 할 수 있다.



내용은 동일하지만 실행 결과를 확인해 보면 charset이 utf-8로 설정된다는 차이가 있다.


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
# Import smtplib for the actual sending function
import smtplib
# Import the email modules we'll need
from email.message import EmailMessage
# And imghdr to find the types of our images
import imghdr
 
email_from = 'your email address'
email_to = 'recipient's email address'
email_cc = 'cc1 email address, cc2 email address, ...'
email_subject = 'Email Test.'
email_content = 'Sending an email test.'
 
# Create a text/plain message
msg = EmailMessage()
msg.set_content(email_content)
 
# From == the sender's email address
# To == the recipient's email address
msg['From'= email_from
msg['To'= email_to
msg['Cc'= email_cc
msg['Subject'= email_subject
 
# Open the file in binary mode. Use imghdr to figure out the MIME subtype for the image.
with open('image.png''rb') as fp:
    img_data = fp.read()
    msg.add_attachment(img_data, maintype = 'image', subtype = imghdr.what(None, img_data), filename = 'image.png')
 
# Send the message via SMTP server.
smtp = smtplib.SMTP('smtp.gmail.com'587)
smtp.starttls()
smtp.login('your email address''password')
smtp.send_message(msg)
 
smtp.quit()


이번엔 Cc(Carbon copy)와 첨부파일을 추가해 보자.


참조와 첨부파일 모두 잘 처리 되었다. (feat. Lena)


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

광학 문자 인식(Optical Character Recognition; OCR)은 사람이 쓰거나 기계로 인쇄한 문자의 영상이나 이미지를 기계가 읽을 수 있는 문자로 변환하는 것이다. 다양한 운영체제를 위한 광학 문자 인식 엔진 Tesseract를 윈도우즈에서 사용해 보자.


Tesseract Windows version을 제공하는 UB Mannheim에 접속해서 적당한 플랫폼의 Tesseract를 다운 받는다.


설치한다.







Additional language data (download)를 클릭한다.


Korean을 선택한다.











Python-tesseract(pytesseract)를 설치한다. Python-tesseract은 Google의 Tesseract-OCR Engine의 wrapper이다.


영문 이미지를 준비한다.



한글 이미지를 준비한다.


1
2
3
4
5
6
7
from PIL import Image
import pytesseract
 
pytesseract.pytesseract.tesseract_cmd = r'D:\Program Files\Tesseract-OCR\tesseract'
 
print(pytesseract.image_to_string(Image.open('English.png')))
#print(pytesseract.image_to_string(Image.open('Korean.png'), lang = 'kor'))


영문, 한글 이미지를 읽고 텍스트를 출력한다.


영문 이미지 결과.


한글 이미지 결과.



Console에서 아래 명령어로도 같은 결과를 얻을 수 있다.

tesseract English.png stdout


tesseract Korean.png stdout -l kor


stdout이 아닌 다른 이름으로 출력을 지정하면 그 이름의 텍스트 파일로 출력된다.

tesseract English.png result


반응형

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

[Scraping] 환율 정보를 SMS로 보내기  (3) 2024.01.02
[Scraping] 환율 정보  (0) 2024.01.02
CSV 분석  (0) 2019.01.20
JSON 분석  (0) 2019.01.18
Beautifulsoup XML 분석  (0) 2019.01.15
Posted by J-sean
:
반응형

Python comes preinstalled on most Linux distributions and is available as a package on all others. However, there are certain features you might want to use that are not available on your distro’s package. You can easily compile the latest version of Python from the source.


대부분의 리눅스에는 파이썬이 포함되어 있어 바로 사용할 수 있지만 최신 버전의 파이썬 소스를 직접 컴파일해 사용할 수 도 있다.


파이썬 홈페이지에서 소스 파일 링크 주소를 확인 한다.


wget으로 소스코드를 다운 받는다.


다운 받은 소스 코드 확인.


--enable-optimizations 옵션과 함께 configure를 실행 한다.


make가 없다면 설치 한다.



make로 컴파일 한다. 지정된 디렉토리에 설치 하고 싶다면 make 실행 후 make altinstall 까지 진행 한다.


Warning: make install can overwrite or masquerade the python3 binary. make altinstall is therefore recommended instead of make install since it only installs exec_prefix/bin/pythonversion.


exec_prefix (${exec_prefix}) is installation-dependent and should be interpreted as for GNU software. For example, on most Linux systems, the default is /usr.


./python을 실행하면 컴파일된 파이썬이 실행 된다.


간단히 python명령어로 실행하기 위해 /usr/bin에 소프트 링크를 만들어 준다.


파이썬 홈페이지에서 다운 받았던 압축 파일은 삭제 한다.


dnf로 최신 버전 파이썬을 간단히 설치 할 수 도 있다.



설치가 완료되면 파이썬[버전] 형식으로 실행 할 수 있다.


Python package installer인 pip도 설치 한다. 


pip3 --version 명령으로 pip버전을 확인할 수 있다.


반응형
Posted by J-sean
: