코드:

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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
from tkinter import *
import openpyxl
from datetime import date
import pandas as pd
import xlrd
import bs4
import urllib.request
import requests
from bs4 import BeautifulSoup
 
today = date.today()
balance = 10000000
balance_2 = 10000000
get_loc = ("E:\\3_2\\python\\Tkinter\\stock_data\\" + str(today) + "_morning.xlsx")
get_wb = xlrd.open_workbook(get_loc)
get_sheet = get_wb.sheet_by_index(0)
write_loc = ("E:\\3_2\\python\\Tkinter\\stock_today\\" + str(today) + ".xlsx")
write_wb = openpyxl.Workbook()
write_sheet = write_wb.active
write_sheet.append(["company""price""balance"])
get_loc_2 = ("E:\\3_2\\python\\Tkinter\\company_list.xlsx")
df_2 = pd.read_excel(get_loc_2, sheetname=0, converters={'종목코드':str})
price_arr = []
 
def get_bs_obj(company):
    url = "https://finance.naver.com/item/main.nhn?code=" + company
    result = requests.get(url)
    bs_obj = BeautifulSoup(result.content, "html.parser")
    return bs_obj
 
def get_price(company):
    bs_obj = get_bs_obj(company)
    no_today = bs_obj.find("p", {"class""no_today"})
    blind_now = no_today.find("span", {"class""blind"})
    return blind_now.text
 
def get_up_10():
    left_balance = balance
    for i in range(111):
        left_balance -= int(get_sheet.cell_value(i, 1)) * 10
        write_sheet.append([get_sheet.cell_value(i, 0), get_sheet.cell_value(i, 1)])
 
    write_sheet['C2'= left_balance
    show_balance.configure(text="balance = " + str(left_balance))
    return
 
def get_rate_down_10():
    left_balance = balance
    for i in range(309319):
        left_balance -= int(get_sheet.cell_value(i, 1)) * 10
        write_sheet.append([get_sheet.cell_value(i, 0), get_sheet.cell_value(i, 1)])
 
    write_sheet['C3'= left_balance
    show_balance_2.configure(text="balance = " + str(left_balance))
    return
 
 
def sell_up_10():
    df = pd.read_excel(write_loc, sheetname=0)
    company = df['company'].tolist()
    for j in range(010):
        for i in df_2.index:
            if company[j] == df_2['회사명'][i]:
                company[j] = df_2['종목코드'][i]
    left_balance = df.iloc[02]
    for i in range(010):
        left_balance += int(get_price(company[i]).replace(",""")) * 10
    show_balance.configure(text="balance = " + str(left_balance))
    return
 
 
def sell_rate_down_10():
    df = pd.read_excel(write_loc, sheetname=0, )
    company = df['company'].tolist()
    for j in range(1020):
        for i in df_2.index:
            if company[j] == df_2['회사명'][i]:
                company[j] = df_2['종목코드'][i]
    print(company)
    left_balance = df.iloc[12]
    for i in range(1020):
        left_balance += int(get_price(company[i]).replace(",""")) * 10
    show_balance_2.configure(text="balance = " + str(left_balance))
    return
 
 
 
root = Tk()
root.title("stock program")
root.geometry("250x250")
 
show_today = Label(root, text = today)
up_10 = Button(root, text="buy up 10", command=get_up_10)
rate_down_10 = Button(root, text="buy rate down 10", command=get_rate_down_10)
show_balance = Label(root, text="balance = " + str(balance))
show_balance_2 = Label(root, text="balance = " + str(balance))
sell_up_10 = Button(root, text="sell up 10", command=sell_up_10)
sell_rate_down_10 = Button(root, text="sell rate down 10", command=sell_rate_down_10)
 
show_today.place(x = 150, y = 10)
up_10.place(x=10, y=100)
show_balance.place(x=10, y = 180)
show_balance_2.place(x=10, y = 200)
sell_up_10.place(x=140, y=100)
 
root.mainloop()
 
 
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

실행결과:

주식을 사기 전 각각 천만원의 계좌(balance)의 잔액이 있다.

엑셀파일이 생성,

산 주식들의 회사명과 주가, 남은 계좌의 잔액이 입력되어있다.

 

주식을 팔고 난 뒤의 계좌의 잔액을 확인할 수 있다. (포스팅 날짜는 주말이라 주가 변동이 없음)

 

설명:

get_loc = ("E:\\3_2\\python\\Tkinter\\stock_data\\" + str(today) + "_morning.xlsx")

get_wb = xlrd.open_workbook(get_loc)

get_sheet = get_wb.sheet_by_index(0)

xlrd라이브러릴 이용해서 해당 디렉토리의 엑셀파일을 가져오는 모습.

 

write_loc = ("E:\\3_2\\python\\Tkinter\\stock_today\\" + str(today) + ".xlsx")

write_wb = openpyxl.Workbook()

write_sheet = write_wb.active

write_sheet.append(["company""price""balance"])

상승주를 가져와서 엑셀파일에 저장. 아래 포스팅 참고.

Python,crawling, bs4, openpyxl, datetime, string, 상승주 가져오기

 

Python,crawling, bs4, openpyxl, datetime, string, 상승주 가져오기

코드: 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 import bs4 import urllib.reque..

coding-0830.tistory.com

 

df_2 = pd.read_excel(get_loc_2, sheetname=0, converters={'종목코드':str})

작성하 엑셀파일을 다시 ead_excel()로 읽는다. converters={'종목코드':str}를 한 이유는 0으로 시작하는 종목코드를 그대로 가져오면 앞에 0이 사라지기 때문.

 

def get_bs_obj(company):

    url = "https://finance.naver.com/item/main.nhn?code=" + company

    result = requests.get(url)

    bs_obj = BeautifulSoup(result.content, "html.parser")

    return bs_obj

 

def get_price(company):

    bs_obj = get_bs_obj(company)

    no_today = bs_obj.find("p", {"class""no_today"})

    blind_now = no_today.find("span", {"class""blind"})

    return blind_now.text

주가를 가져오는 함수, 기본적인 크롤링 방법, 아래 포스팅 참고

Python,crawling, bs4,인기검색어 가져오기

 

Python,crawling, bs4,인기검색어 가져오기

코드 : 1 2 3 4 5 6 7 8 9 import bs4 import urllib.request url = "http://naver.com" html = urllib.request.urlopen(url) bsobj = bs4.BeautifulSoup(html, "html.parser") realtime_hotkeyword = bsobj.find_..

coding-0830.tistory.com

def get_up_10():

    left_balance = balance

    for i in range(111):

        price_arr.append(get_sheet.cell_value(i, 1))

        left_balance -= int(get_sheet.cell_value(i, 1)) * 10

        write_sheet.append([get_sheet.cell_value(i, 0), get_sheet.cell_value(i, 1)])

 

    write_sheet['C2'= left_balance

    write_wb.save(write_loc)

    show_balance.configure(text="balance = " + str(left_balance))

    return

위에 따로 올린 상승주 가져오기 포스팅 코드를 이용해서 미리 다운받은 엑셀파일에서 상위 열개의 주가를 가져와 각10씩 사서 balance에서 빼는 모습. 그 balance는 새로 작성하는 엑셀파일의 C2자리에 넣는다.

 

def sell_up_10():

    df = pd.read_excel(write_loc, sheetname=0)

    company = df['company'].tolist()

    for j in range(010):

        for i in df_2.index:

            if company[j] == df_2['회사명'][i]:

                company[j] = df_2['종목코드'][i]

    left_balance = df.iloc[02]

    for i in range(010):

        left_balance += int(get_price(company[i]).replace(",""")) * 10

    show_balance.configure(text="balance = " + str(left_balance))

    return

다시 되파는 코드, 상당히 골치 아팠다. 아침에 검색할 때와 장 마감후 검색하는 급등주는 서로 다르기 때문에 아침에 검색해서 샀던 주식을 따로 일일이 검색하여 가격을 받아와야하기 때문.

일단 미리 다운받았던 상장주식의 정보가 모두 들어있는 엑셀파일에 있는 회사명과 내가 산 주식의 회사명이 일치 한다면 해당 회사명을 종목코드로 바꿔주는 작업을 한 뒤, get_price()를 이용하여 주가를 가져온다.

이 때 주가는 86,000 처럼 중간에 콤마가 붙어있기 때문에 replace()함수를 이용하여 콤마를 없애준다. 

그 후 다시 10주씩 판다는 가정하에, 잔액에 더해준다. 그리고 라벨을 업데이트된 잔액으로 바꾼다. 이는 아래 포스팅 참고.

Python, Tkinter, 화씨에서 섭씨로 바꾸기

 

Python, Tkinter, 화씨에서 섭씨로 바꾸기

코드: 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 from tkinter import* #function which actions when the button is pushed def convert(): f = float(ent.get()) tmp = float(5 *..

coding-0830.tistory.com

 이 하 코드는 기본적인 Tkinter라이브러리 사용방법이니 바로 위 포스팅 다시 참고.

 

'Python > Tkinter' 카테고리의 다른 글

Python, Tkinter, 현재 주가 가져오기  (0) 2019.10.04
Python, Tkinter, 화씨에서 섭씨로 바꾸기  (0) 2019.10.04

코드:

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
import bs4
import urllib.request
import openpyxl
from datetime import date
import string
 
today = date.today()
= []
= []
= []
def get_company():
    url = "https://finance.naver.com/sise/sise_rise.nhn?sosok=1"
    html = urllib.request.urlopen(url)
    bsobj = bs4.BeautifulSoup(html, "html.parser")
    tltle = bsobj.find_all("a", {"class""tltle"})
    for i in tltle:
        a.append(i.text)
    return
 
def get_price():
    url = "https://finance.naver.com/sise/sise_rise.nhn?sosok=1"
    html = urllib.request.urlopen(url)
    bsobj = bs4.BeautifulSoup(html, "html.parser")
    price = bsobj.find_all("td", {"class""number"})
    for i in price:
        b.append(i.text)
    for index, value in enumerate(b):
        if index%10 == 0:
            c.append(value.replace(","""))
    return
 
 
def upload_every_morning():
    get_company()
    get_price()
    wb = openpyxl.Workbook()
    sheet = wb.active
    sheet.append(["company""price"])
    for i in range(0320):
        sheet.append([a[i], c[i]])
    wb.save("E:\\3_2\\python\\Tkinter\\stock_data\\" + str(today) + "_morning.xlsx")
    return
 
def upload_every_final():
    get_company()
    get_price()
    wb = openpyxl.Workbook()
    sheet = wb.active
    sheet.append(["company""price"])
    for i in range(0320):
        sheet.append([a[i], c[i]])
    wb.save("E:\\3_2\\python\\Tkinter\\stock_data\\" + str(today) + "_final.xlsx")
    return
 
upload_every_morning()
upload_every_final()
 
cs

 

실행결과:

 

 

설명:

today = date.today()

today()함수를 이용하여 오늘 날짜를 today변수에 저장

 

get_company()

get_price()

회사명과 주가를 크롤링. 자세한 설명은 아래 포스팅 참고

Python,crawling, bs4,pandas,주식 엑셀로 가져오기

 

Python,crawling, bs4,pandas,주식 엑셀로 가져오기

한국 거래소에 올라와 있는 엑셀파일을 다운받는 것을 구현해보았다. 코드: 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 import requests imp..

coding-0830.tistory.com

wb = openpyxl.Workbook()

openpyxl.Workbook()함수를 이용하여 엑셀 작업 시작 (엑셀을 만드는 작업)

 

sheet = wb.active

뭔말인지 모름

 

sheet.append(["company""price"])

append()함수를 이용하여 엑셀 파일에서 이미 입력이 되어있는 셀 바로 밑 줄에 내용 추가, 현재는 빈 상태이기 때문에 가장 윗줄에 입력이 됨.

 

for i in range(0320):

      sheet.append([a[i], c[i]])

회사명이 저장되어있는 a배열과 주가가 저장되어있는 c배열의 내용을 입력.

 

wb.save("E:\\3_2\\python\\Tkinter\\stock_data\\" + str(today) + "_final.xlsx")

save()함수를 이용하여 해당 주소에 파일 저장.

 

 

코드:

 

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
from tkinter import*
import requests
from bs4 import BeautifulSoup
 
def get_bs_obj(company_code):
    url = "https://finance.naver.com/item/main.nhn?code=" + company_code
    result = requests.get(url)
    bs_obj = BeautifulSoup(result.content, "html.parser")
    return bs_obj
#bs_obj를 받아서 price를 return
def get_price(company_code):
    bs_obj = get_bs_obj(company_code)
    no_today = bs_obj.find("p", {"class""no_today"})
    blind_now = no_today.find("span", {"class""blind"})
    return blind_now.text
 
#company_codes = ["005930","000660"]
def get_Price_from_ent():
    f = ent.get();
 
    lbl_2.configure(text = str(get_price(f)))
    return
 
root = Tk()
root.title("Stock Program ")
root.geometry("540x280")
 
 
lbl_1 = Label(root, text = "Company Number")
ent = Entry(root)
lbl_2 = Label(root, text = "0")
btn = Button(root, text = "Search", command = get_Price_from_ent)
 
lbl_1.place(x = 20, y = 30)
ent.place(x = 150, y = 30)
btn.place(x = 150, y = 70)
lbl_2.place(x = 150, y = 120)
 
 
root.mainloop()
cs

실행결과:

설명:

005930은 삼성전자의 번호이다.

 

위 코드는 Python,crawling, bs4,인기검색어 가져오기

 

Python,crawling, bs4,인기검색어 가져오기

코드 : 1 2 3 4 5 6 7 8 9 import bs4 import urllib.request url = "http://naver.com" html = urllib.request.urlopen(url) bsobj = bs4.BeautifulSoup(html, "html.parser") realtime_hotkeyword = bsobj.find_..

coding-0830.tistory.com

 

Python, Tkinter, 화씨에서 섭씨로 바꾸기

 

Python, Tkinter, 화씨에서 섭씨로 바꾸기

코드: 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 from tkinter import* #function which actions when the button is pushed def convert(): f = float(ent.get()) tmp = float(5 *..

coding-0830.tistory.com

두 개의 내용을 합친 것이다.

코드:

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
from tkinter import*
 
#function which actions when the button is pushed
def convert():
    f = float(ent.get())
    tmp = float(5 * (f - 32/ 9)
    #print(tmp)
    lbl_2.configure(text = str(tmp))
    return
 
root = Tk()
root.title("temperature program")
root.geometry("230x120")
 
lbl_1 = Label(root, text = "Fahrenheit")
ent = Entry(root)
lbl_2 = Label(root, text = "Celsius")
btn = Button(root, text = "change to Celsius", command = convert)
 
lbl_1.place(x = 10, y = 20)
ent.place(x = 50, y = 20)
btn.place(x = 50, y = 40)
lbl_2.place(x = 50, y = 80)
 
root.mainloop()
 
cs

 

실행결과:

 

설명:

root = Tk()

위도우를 만들어서 root변수에 저장.

 

root.title("temperature program")

만든 윈도우에 이름을 지정.

 

root.geometry("230x120")

윈도우 창의 크기

 

lbl_1 = Label(root, text = "Fahrenheit")

Lable()함수를 이용해서 라벨 생성

 

ent = Entry(root)

Entry()함수를 이용해서 입력창 생성

 

btn = Button(root, text = "change to Celsius", command = convert)

Button()함수를 이용해서 버튼 생성, 함수는 command로 호출한다.

 

def convert():

    f = float(ent.get())

    tmp = float(5 * (f - 32/ 9)

    #print(tmp)

    lbl_2.configure(text = str(tmp))

    return

함수 생성부분,  lbl_2.configure(text = str(tmp)) configure()함수를 이용해서 두번째 라벨의 내용을 결과값으로 바꾸는 함수다.

 

lbl_1.place(x = 10, y = 20)

place()함수를 이용해서 해당 좌표에 라벨을 붙이는 코드.

 

 

 

코드:

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
package CIrcle;
 
class Circle{
    int radius;
    public Circle(int radius) {
        this.radius = radius;
    }
    public double getArea() {
        return 3.14*radius*radius;
    }
}
public class Circle_Array {
 
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Circle[] c;
        c = new Circle[5];
 
        for(int i = 0; i < c.length; i++) {
            c[i] = new Circle(i);
        }
        for(int i = 0; i < c.length; i++) {
            System.out.println((int)c[i].getArea() + " ");
        }
    }
 
}
 
cs

 

실행결과:

 

설명:

 Circle[] c;

 c = new Circle[5];

변수 c에 5개의 Circle 객체를 저장했다.

위쪽에 만든 것이 Circle의 클래스이고 메인 함수에서 Circle객체를 만드는 코드이다.

'Java' 카테고리의 다른 글

Java, String(2)  (0) 2019.10.04
Java, String(1)  (0) 2019.10.04
Java, Interger.parseInt(), 예외처리  (0) 2019.09.25
Java, Array  (0) 2019.09.25
Java, for-while, continue, Scanner  (0) 2019.09.25

코드:

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
#include <iostream>
#include <opencv2/opencv.hpp>
 
using namespace std
using namespace cv;
void detectHScolor(const cv::Mat&  image, double minHue,
    double maxHue, double minSat, double  maxSat, Mat&  mask);
 
int main() {
    Mat image = imread("girl.jpg");
    Mat mask;
    detectHScolor(image, 1601025166, mask);
    Mat detected(image.size(), CV_8UC3, Scalar(000));//하얗게 주려면 255,255,255
    image.copyTo(detected, mask);
    imshow("Girl", image);
    imshow("Detected", detected);
    waitKey(0);
}
 
 
 
void detectHScolor(const Mat&  image, double minHue, double maxHue, double minSat, double  maxSat, Mat&  mask) {
    //detect by hue(minHue~maxHue), saturate(minSat~maxSat) 
    Mat hsv;
    cvtColor(image, hsv, COLOR_BGR2HSV); //conver BGR to HSV
 
    vector<Mat>  channels;
    split(hsv, channels);    //split channels
    double minVal = 0, maxVal = 0;
    minMaxLoc(channels[0], &minVal, &maxVal, 00);
    cout << "min= " << minVal << " max= " << maxVal << endl//min=0, max=179
    Mat  mask1;   //maxHue 이하는 255, 이상은 0
    threshold(channels[0], mask1, maxHue, 255, THRESH_BINARY_INV);
    Mat  mask2; //minHue 이하는 0, 이상은 255   
    threshold(channels[0], mask2, minHue, 255, THRESH_BINARY);
    Mat hueMask;
    if (minHue < maxHue)  hueMask = mask1 & mask2;
    else hueMask = mask1 | mask2;
    //색상 범위가 0을 포함할 때 즉 160 ~ 10 사이 색상
 
    //채도 마스크
    threshold(channels[1], mask1, maxSat, 255, THRESH_BINARY_INV);
    threshold(channels[1], mask2, minSat, 255, THRESH_BINARY);
 
    Mat satMask;
    satMask = mask1 & mask2;
    //0와 255로 구성된 mask: 255인 곳이 얼굴 영역: 이영역만 원본 영상에서 copy
    mask = hueMask & satMask;
}
 
cs
실행결과:

 

설명:

 

 

 

 

 

'C,C++ > Opencv, c++' 카테고리의 다른 글

Opencv, c++, cvtColor(), split(), merge()  (0) 2019.10.04
Opencv, c++, imshow, imwrite  (0) 2019.10.04
Opencv, c++, video 출력  (0) 2019.09.22
Opencv, c++, Rectangle 출력  (0) 2019.09.22

코드:

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
#include <iostream>
#include <opencv2/opencv.hpp>
 
using namespace std;
using namespace cv;
 
int main() {
    Mat image = imread("boldt.jpg"); //read a image
    Mat hsv;
    cvtColor(image, hsv, COLOR_BGR2HSV); //convert BGR to HSV
    vector<Mat>  channels;
    split(hsv, channels); //split to h,s,v
    //channels[0] 색상(H),  channels[1]  채도(S),  channels[2]  명도(V)
    //각 채널 출력
    imshow("Original", image); //original
    imshow("Hue", channels[0]); //hue
    imshow("Saturate", channels[1]); //saturate
    imshow("Value", channels[2]); //value
    channels[2= 255//value to max
    merge(channels, hsv); //merge h,s,v
    Mat newImage;
    cvtColor(hsv, newImage, COLOR_HSV2BGR); //convert HSV to BGR
    imshow("Fixed Value Image", newImage);
    waitKey(0);
 
    return 0;
}
 
cs

 

실행결과:

 

설명:

cvtColor(image, hsv, COLOR_BGR2HSV); 

눈치가 빠르다면 단번에 코드의 의미를 파악할 수 있다. cvtColor()함수를 이용하여 COLOR_BGR2HSV 즉 BGR이미지에서 HSV이미지로 변환시키는 코드.

 

    vector<Mat>  channels;

    split(hsv, channels); 

개인적으로 신기했던 코드. Mat형식의 벡터를 만든다음 split()함수를 이용하여 각 벡터에 H, S, V의 이미지를 저장.

 

이후 코드는 이해가능할 것이다.

'C,C++ > Opencv, c++' 카테고리의 다른 글

Opencv, c++, threshold()  (0) 2019.10.04
Opencv, c++, imshow, imwrite  (0) 2019.10.04
Opencv, c++, video 출력  (0) 2019.09.22
Opencv, c++, Rectangle 출력  (0) 2019.09.22

코드:

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
#include <iostream>
#include <opencv2/opencv.hpp>
 
using namespace std;
using namespace cv;
 
int main() {
    vector<int> params_jpg, params_png;
    params_jpg.push_back(IMWRITE_JPEG_QUALITY);          //JPG로 화질 설정
    params_jpg.push_back(95);
    params_png.push_back(IMWRITE_PNG_COMPRESSION);       //PNG 압축레벨 저장
    params_png.push_back(3);
 
    Mat image = imread("puppy.bmp");
    if (image.empty()) {
        cout << "Image unloaded" << endl;
        return 0;
    }
 
    imwrite("output.jpg", image, params_jpg); //puppy.bmp->output.jpg
    Mat image_1 = imread("output.jpg");
    if (image_1.empty()) {
        cout << "Image unloaded" << endl;
        return 0;
    }
 
    imwrite("output2.png", image, params_png); //puppy.bmp->output2.png
    Mat image_2 = imread("output2.png");
    if (image_2.empty()) {
        cout << "Image unloaded" << endl;
        return 0;
    }
 
    imshow("original image", image);
    imshow("output image", image_1);
    imshow("output image2", image_2);
 
    waitKey(0);
 
 
 
}
 
cs

실행결과:

 

설명:

    vector<int> params_jpg, params_png;

    params_jpg.push_back(IMWRITE_JPEG_QUALITY);          //JPG로 화질 설정

    params_jpg.push_back(95);

    params_png.push_back(IMWRITE_PNG_COMPRESSION);       //PNG 압축레벨 저장

    params_png.push_back(3);

imwrite에 매개변수로 벡터를 넣기 위해 벡터를 만드는 과정.

이저 버전에서는 

imwrite("output.jpg", image, IMWRITE_JPEG_QUALITY, 95)

이런식으로 코드를 짜도 실행이 됐었지만 현재 최신 버전에서는 에러로 뜬다. 

그래서 위에 코드처럼 벡터를 따로 만들어서 벡터값을 매개변수로 넣어야함...

 

    Mat image = imread("puppy.bmp");

    if (image.empty()) {

        cout << "Image unloaded" << endl;

        return 0;

    }

imread 이미지를 가져오는 코드

 

    imwrite("output.jpg", image, params_jpg); //puppy.bmp->output.jpg

    Mat image_1 = imread("output.jpg");

    if (image_1.empty()) {

        cout << "Image unloaded" << endl;

        return 0;

    }

원본 이미지를 jpg로 압축하여 저장하고 다시 불러와서 image_1이라는 변수에 저장.

 

    imwrite("output2.png", image, params_png); //puppy.bmp->output2.png

    Mat image_2 = imread("output2.png");

    if (image_2.empty()) {

        cout << "Image unloaded" << endl;

        return 0;

    }

마찬가지로 png로 압축한 뒤 불러오기.

 

    imshow("original image", image);

    imshow("output image", image_1);

    imshow("output image2", image_2);

이미지 보여주기.

 

'C,C++ > Opencv, c++' 카테고리의 다른 글

Opencv, c++, threshold()  (0) 2019.10.04
Opencv, c++, cvtColor(), split(), merge()  (0) 2019.10.04
Opencv, c++, video 출력  (0) 2019.09.22
Opencv, c++, Rectangle 출력  (0) 2019.09.22

오버로딩이란 객체 생성시 생성자 함수를 같은 이름으로 여러개 정의함으로써

각기 다른 매개변수를 받으면서 같은 이름의 함수를 호출하는 것을 의미함.

 

코드:

 

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
 
public class Book {
    String title;
    String author;
    void show() {
        System.out.println(title + "/" + author);
    }
 
    public Book() {
        this("","");
        System.out.println("생성자 1호출됨");
    }
    public Book(String title) {
        this(title, "작자미상");
        System.out.println("생성자 2호출됨");
    }
    public Book(String title, String author) {
        this.title = title;
        this.author = author;
        System.out.println("생성자 3호출됨");
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Book littlePrince = new Book("어린왕자""생텍쥐페리");
        Book loveStory = new Book("춘향전");
        Book emptyBook = new Book();
        littlePrince.show();
        loveStory.show();
        emptyBook.show();
    }
 
}
 
cs

 

실행결과:

 

설명:

위의 book함수를 보면

public Book()

public Book(String title)

public Book(String title, String author)

이렇게 세 개의 생성자 함수를 갖고 있다.

 

Book littlePrince = new Book("어린왕자""생텍쥐페리");

이 코드는 세번째 생성자 함수를 호출했다.

 

Book loveStory = new Book("춘향전");

두번째 생성자 함수를 호출한 코드인데 실행 결과를 보면 생성자 3이 먼저 호출 된것을 알 수있다.

이유는 

    public Book(String title) {

        this(title, "작자미상");

        System.out.println("생성자 2호출됨");

    }

두번째 생성자 함수를 호출하면 this()함수를 이용하여 자기 자신을 또 호출하게 되는데, 이 때 

 this(title, "작자미상");

String매개변수를 두개 받으므로 이는 세번째 생성자 함수이다. 그래서 생성자3이 호출된 것이다.

 

밑에도 마찬가지.

 

코드:

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
 
public class String_4 {
 
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String str = "sring compare is complete";
        String key = new String("complete!");
        int result;
        result = key.compareTo(str);
        System.out.println("result = " + result);
 
        String s1 = "java";
        String s2 = "java";
        String s3 = "JAVA";
        String s4 = "good";
        System.out.println(s1.equals(s2));
        System.out.println(s1.equals(s3));
        System.out.println(s1.equals(s4));
        System.out.println(s1.equalsIgnoreCase(s3));
        
        String s11 = "java";
        String s22 = new String(s11);
        System.out.println(s1.equals(s22));
        System.out.println(s11 == s22);
        
        String a[];
        String s = "This    is   a   String";
        a = s.split(" +");
        String s111;
        s111 = s.toLowerCase();
        System.out.println(s111);
        s111 = s.toUpperCase();
        System.out.println(s111);
        s111 = s.trim();
        System.out.println(s111); 
        System.out.println(a.length); 
        
    }
 
}
 
cs

 

실행결과:

설명:

key.compareTo(str)

compareTo()함수를 이용해서 key와 str을 비교. 아스키 코드상으로 차이나는 만큼의 값을 반환.

 

System.out.println(s1.equals(s2));

equals()함수를 통해서 두 String의 값이 같은지 반환. s1 == s2 이런식으로 하면 안됨. 

 

= s.split(" +");

공백을 이용하여 단어들을 따로 구분지음. +를 써주면 공백이 여러번 이어져도 하나의 공백으로 취급

 

s111 = s.toLowerCase();

System.out.println(s111);

s111 = s.toUpperCase();

System.out.println(s111);

String을 대문자 또는 소문자로 바꿈.

 

s111 = s.trim();

맨 앞과 맨 뒤의 공백 제거 함수.

 

 

 

 

'Java' 카테고리의 다른 글

Java, 클래스 생성  (0) 2019.10.04
Java, String(1)  (0) 2019.10.04
Java, Interger.parseInt(), 예외처리  (0) 2019.09.25
Java, Array  (0) 2019.09.25
Java, for-while, continue, Scanner  (0) 2019.09.25

+ Recent posts