2023년 2월 10일 금요일

JPEG 이미지에서 GPS 위치 정보 추출 후, 주소로 전환

JPEG 이미지에서 GPS 위치 정보 추출 후, 주소로 전환.

이미지가 획득된 시간 정보도 출력. 


# From Image through GPS location to Address
from geopy.geocoders import Nominatim
from exif import Image as exImg


def geocoding_reverse(lat_lng_str):
    geolocoder = Nominatim(user_agent = 'South Korea', timeout=None)
    address = geolocoder.reverse(lat_lng_str)
    return address

def decimal_coords(coords, ref):
    decimal_degrees = coords[0] + coords[1] / 60 + coords[2] / 3600
    if ref == "S" or ref =='W' :
        decimal_degrees = -decimal_degrees
    return decimal_degrees

def image_coordinates(img):
    if img.has_exif:
        try:
            coords = (decimal_coords(img.gps_latitude, img.gps_latitude_ref),
                         decimal_coords(img.gps_longitude, img.gps_longitude_ref))
        except AttributeError:
            print ('No Coordinates')
            return {}
    else:
        print ('The Image has no EXIF information')
        return {}
    return {"imageTakenTime":img.datetime_original, "geolocation_lat":coords[0],"geolocation_lng":coords[1]}


image_path = 'bbb.jpg"
with open(image_path, 'rb') as src:
    img = exImg(src)

img_info = image_coordinates(img)
if "imageTakenTime" in img_info:
    posi = '{},{}'.format(img_info["geolocation_lat"],img_info["geolocation_lng"])
    address = geocoding_reverse(posi)
    print(img_info["imageTakenTime"], address)

#address = geocoding_reverse('36.5760732781656, 128.15935928504484')
#print(address)

2023년 2월 1일 수요일

PostgreSQL 설치 및 사용법

/* PostgreSQL 설치 및 사용법
 * (1) 설치(PostgreSQL과 DBeaver): Youbube를 참고하여 설치하였음
 * (2) SQL 기본 구문 구조 이해
 * (3) 파이썬 연결 관련
 * (4) SQL shell 명령(psql)
 * (5) 이미지 파일의 저장(BYTEA)
 * (6) 저장된 파일 경로
 *      d:\2023\postgresql\test_script.sql
 *      data도 있음
 */


/* (1) PostgreSQL과 DBeaver 설치
 *   Win10기준으로 Youtube를 참조하여 설치
 */
--자세한 내용은 Youtube를 참조함

/*
 * (2) SQL 기본 구문 구조 이해
 *   테스트 data는 (2)의 Youtube에 있음
 *   DBeaver에서 테스트(test_scripts.sql)
 */
-- 실행할 구문 선택 후 ^+Enter로 실행

select * from prod_cat_info;
select * from transactions;
select * from city;
select * from customer;


/* 테스트(필터링) 구문 */
select          count(distinct a.transaction_id) as cnt_orders
    ,       sum(a.total_amt) as sum_amt
    ,       max(a.tran_date) as latest_tran_date
from        transactions a
--where         total_amt > 0
--group by  customer_id
--having        count(discount transaction_id) >= 2
--order by  sum_amt desc
--limit         12;

-- c는 alias(별칭), distinct는 구별되는 유니크한 것만 추출


select      count(c.customer_id)
    ,       count(distinct c.transaction_id)
    ,       sum(c.total_amt)
from        transactions c;


select      a.customer_id       as  고객번호
    ,       a.tran_date         as  거래일자
    ,       a.rate              as  판매가
    ,       a.qty               as  주문수량
    ,       a.total_amt         as  주문금액
from        transactions a;


select      count(distinct  b.transaction_id)
        ,   count(distinct  b.customer_id)
        ,   sum(b.total_amt)
from        transactions b;


-- 중복포함 모두 출력
select      store_type
from        transactions;


-- 중복된 것은 제거하고 서로 다른 것만 출력
select      distinct store_type
from        transactions ;


-- 문자 형식의 리터럴은 ''으로 감싸서 입력
-- 날짜 리터럴은 date키워드와 함께 날짜형식으로 입력
-- 날짜와 nation이 일치하는 데이터만 추출
select      a.city_code
    ,       a.city_name
    ,       'KOREA'                 as  nation
    ,       date '2021-09-26'       as  insert_dt
    ,       4923                    as  number_literal
from        city a;


/* 새로운 테이블을 하나 만든다
 * 기 생성된 DB Retail아래에 mytable이란 테이블 생김
 * public -> Tables -> mytable이 생김
 */

create table mytable (
    name        varchar(80),
    pet         varchar(80)
);


insert into mytable values ('Mary', 'dog'), ('John', 'cat'), ('Robert', 'bitt');


-- 테이블 만드는 또 다른 예제
CREATE TABLE CUSTOMER
(   CUSTOMER_ID VARCHAR(200)    PRIMARY KEY,
    DOB         DATE            NOT NULL,
    GENDER      VARCHAR(200),
    CITY_CODE   VARCHAR(200)
);


/* (3) Python 연결
 * Python 코드로 어떤 테이블에 데이터 추가
 * import psycopg2
 * conn = psycopg2.connect("host='localhost' dbname='Retail' user='postgres' password='0577' port=5432")
 * cur = conn.cursor()
 * cur.execute("INSERT INTO mytable (name, pet) values ('Kdj', 'tan');")
 * conn.commit()  # 데이터 추가됨
 */


select * from mytable;


 *  cur.execute("SELECT * from mytable;")
 *  rows = cur.fetchall()
 *  rows # 출력
 *  [('Mary', 'dog'), ('John', 'cat'), ('Robert', 'bitt'), ('Kdj', 'tan')]
 */


-- 데이터 갱신
-- > cur.execute("update mytable set name='kdj' where pet='tan'")
-- > cur.execute("select * from mytable;")
-- > conn.commit()
-- > rows:
--   [('Mary', 'dog'), ('John', 'cat'), ('Robert', 'bitt'), ('lee', 'tan')]


-- 데이터 삭제
-- > cur.execute("delete from mytable where name='lee'")
-- > cur.execute("select * from mytable;")
-- > rows = cur.fetchall()
-- > rows: [('Mary', 'dog'), ('John', 'cat'), ('Robert', 'bitt')]


/* (4) SQL shell
 * >>> PostgreSQL13 -> SQL shell(psql) 실행 <<<
 * Table의 상위인 DATABASE의 조회, 생성, 삭제 가능
 * command #로 들어가서
 * \l or \l+  # 조회, 또는 상세 조회
 * CREATE DATABASE hello;  # DB생성
 * DROP DATABASE hello;  # DB제거
 * 이미 만들어진 Retail 확인 가능
 */


/* (5) 이미지 파일의 저장(BYTEA)
 * > 아래 파이썬 명령 참고
 */
 

-- > cur.execute("CREATE TABLE IF NOT EXISTS cartoon(cartoonID INTEGER, name TEXT, cartoonImg BYTEA)")
-- > conn.commit()
-- > cartoonID = 1
-- > name = "Casper"
-- > file_path = 'test.jpg'
-- > drawing = open(file_path, 'rb').read()
-- >
-- > cur.execute("INSERT INTO cartoon (cartoonID,name,cartoonImg) " + "VALUES(%s,%s,%s)", (cartoonID, name, psycopg2.Binary(drawing)))
-- > conn.commit()


-- image가 저장 되었는지 확인 가능
select *
from cartoon;

2023년 1월 30일 월요일

Windows to ubuntu ssh (powershell - ssh) 연결

 1. ubuntu - ip 확인(내부의 ip주소)

> ip a


2. SSH server설치

# ssh 설치
> sudo apt update
> sudo apt install openssh-server

# ssh 상태 확인
> sudo systemctl status ssh

# ssh 실행
> sudo systemctl start ssh

# ssh 중지
> sudo systemctl stop ssh


3. SSH server port 확인

# ssh port 확인 (실제 서비스되고 있는 port 확인)
> sudo ss -tulpn | grep ssh


4. 우분투 방화벽 설정

# 우분투 방화벽 설정 해제
> sudo ufw allow ssh


5. SSH server 연결

# ssh 연결 (우분투에서 바로 해봄)
> sudo ssh username@내부_ip_address -p sshportnumber


6. 공유기(iptime) 포트포워딩

# iptime 접속
chrome: 192.168.0.1 ->login/pw

# Port forwarding
Advanced Setup->NAT/Routing->Port Forwarding
Internal IP, External port, Internal port값을 설정(실제 서비스되고 있는 port번호)


7. window powershell 접속(원격)

# ssh 연결
> ssh username@외부_ip_address -p sshportnumber



참고 자료


2022년 9월 4일 일요일

git 사용법

처음

1. github에 들어가서 New로 새로운 repository(이름을 Processor라고 하자)를
만듬 (생성후 나오는 명령셋 참조)
2. 적당한 위치에 폴더를 만들고, vscode로 이 폴더를 오픈함
3. 폴더에서 필요한 프로그램을 작성
4. vscode의 New Terminal로 터미날을 오픈

5. 아래의 명령을 차례로 입력 (처음 업로드)
git config user.email "djk*****@d***.net"
git config user.name "djk*****"
git init (".git" 라는 폴더가 생기고현재 폴더의 변화를 추적하기 시작함)
git add filename (or git add .): 전체를 업로드하거나 변화된 파일만
업로드를 위해 파일을 staging함
git commit -m "First upload"
git remote add origin "https://github.com/galmegy/Processor.git"
(github repository와 연결)
git status: staging 상태 확인
git push -u origin master: 업로드 실행


재 수정

파일 수정 후 업로드를 원하면
git add ...부터 끝까지만 반복하면 됨


새로운 Branch

git branch Detector
git switch Detector
git status (Detector branch에 와 있음을 알 수 있음)



2022년 1월 26일 수요일

Windows 10, Anaconda환경에서 Mujoco 설치

 1. https://mujoco.org/download 에서 v.2.1.0버전(windows x86_64)을 다운 받는다.

 - C:\Users\홈경로\.mujoco 폴더를 만들고 여기에 mujoco210폴더 아래 압축을 푼다.

2. https://www.roboti.us/license.html에서 Activation key를 찾아 다운 받는다 (mjkey.txt).

 - 파일을  C:\Users\홈경로\.mujoco\mujoco210, C:\Users\홈경로\.mujoco\mujoco210\bin 복사

 - bin폴더 내에서 

   > simulate ../model/humanoid.xml 실행하면

   창이 뜨고 사람이 쓰러지는 화면이 나오면 설치가 잘 된 것임.

3. conda의 가상환경 py38로 들어가서 경로를 설정 후 mujoco-py 설치.

  > set path=C:\Users\홈경로\.mujoco\mujoco210\bin;%PATH%

  > pip install mujoco-py=2.1 설치. (안되면 =2.1 제거하고 시도)

 4. python 실행하고, 아래 명령 실행하면 필요한 컴파일 진행 

   (import mujoco_py를 처음 실행 시에 여러가지 컴파일 자동 실행됨)

import mujoco_py
import os
mj_path = mujoco_py.utils.discover_mujoco()
xml_path = os.path.join(mj_path, 'model', 'humanoid.xml')
model = mujoco_py.load_model_from_path(xml_path)
sim = mujoco_py.MjSim(model)
print(sim.data.qpos)

sim.step()
print(sim.data.qpos)

[참조] 
1. MuJoCo 설치

2021년 11월 10일 수요일

Pyside2 기초

- QT: c/c++언어 기반의 gui 라이브러리

- PyQT: QT와 다른 회사서 만듬

- PySide2: QT 회사에서 만듬

-------------------------------

from PySide2.QtWidgets import *

# 기본 절차: (1) 응용프로그램(App) 시작, (2) window 생성, (3) layout 생성,
#           (4) 위젯(버턴, 라벨, ...) 만듬, (5) layout에 위젯 추가, 
#           (6) layout을 window에 넘김, (7) window 출력, (8) App 실행

app = QApplication([]) # 응용 프로그램 시작
window = QWidget() # window를 생성
layout = QVBoxLayout() # layout을 생성

button = QPushButton("I'm just a Button man") # button 하나 만듬
layout.addWidget(QLabel('Hello World!')) # label을 layout에 추가

layout.addWidget(button) # button을 layout에 추가
window.setLayout(layout) # layout을 window로 넘김

window.show() # window 화면 출력
app.exec_() # 응용 프로그램 실행


참고

1. Medium



2021년 9월 22일 수요일

Networks

- DHCP 서버는 유동 ip 주소를 자동으로 할당, 회수 해주는 서버

- DNS 서버는 숫자 ip와 문자 ip를 바꾸어 주는 서버

- 허브, 스위치, 라우터

  허브: 물리적 연결만 표현, 지능 없음. 들어오는 신호는 모든 연결부로 나감

  스위치: 허브와 유사. 지능 가짐, 입력 데이터는 필요한 곳으로만 나감

  라우터: 허브와 스위치는 내부망에 사용하나 라우터는 외부와 연결을 중계

     class A: 10.0.0.0~10.255.255.255
     class B: 172.16.0.0~172.31.255.255
     class C: 192.168.0.0~192.168.255.255
          사설망 주소는 모두 192.168.~  시작함.   

- 서브넷 마스크: ip 주소에 마스크를 씌워 네트워크 범위와 Host범위를 나누어줌

- 게이트웨이: iptime 공유기 주소

- DNS서버: 8.8.8.8(구글 DNS)