중력에 대한 ODE를 Numerical analysis

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
t = 0 #변수, 상수 선언
g = 9.81
c = 12.5
m = 68.1
delta = 2.4
vel = 0


def velocity(t):
value = vel + (g - c * vel / m) * delta #식의 해
return value


print(t, vel)

for a in range(1, 100): #몇번 반복할지
vel = velocity(t)
t = t + delta
print(t, vel)
1
2
3
4
5
6
7
8
9
10
11
0 0
2.4 23.544
4.8 36.71619383259912
7.199999999999999 44.085659104581886
9.6 48.208663904325554
12.0 50.51536703017333
14.4 51.80590137811459
#중간생략 왼쪽이 시간, 오른쪽이 Velocity
232.80000000000038 53.44487999999999
235.2000000000004 53.44487999999999
237.6000000000004 53.44487999999999
Read more »

데이터 가공

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from selenium import webdriver
import os

browser = webdriver.Chrome('C:/Users/OHG/Downloads/chromedriver_win32/chromedriver') #Directory지정
browser.implicitly_wait(5) #암묵적으로 3초 딜레이
url = "https://www.youtube.com/watch?v=94YwFIJ-yR0&list=PL3Eb1N33oAXijqFKrO83hDEN0HPwaecV3&index=1"
browser.get(url)

for a in range(1, 2): #url의 개수
b = str(a)
os.mkdir(b + "번째 기사")
os.chdir(b + "번째 기사")
print(a, "번째 url open")
products = browser.find_elements_by_css_selector('#description > yt-formatted-string')
f = open("기사 대본.txt", 'w') #txt적기
for product in products:
Z = product.text
f.write(Z[:-117])
browser.save_screenshot("Website.png")
os.chdir("..")
browser.quit()
Read more »

Unreal Engine?

프로그래밍, 게임 기획, 사운드, 그래픽 수학, 효과, UI 등등 모두를 편하게 작업하게 해주는 게임 제작 툴


Unreal engine의 기능

  • 블루프린트 : 스크래치와 같이 프로그래밍 가능
  • C++ 소스 코드 제공
  • 시퀀서 : 영상 제작
  • 렌더링
  • 템플릿, 학습 자료
  • 마켓플레이스 : 모듈을 판매함
  • 멀티플레이어 프레임워크
  • 터레인, 폴리지
  • 고급 AI
Read more »

Docker로 부서진 멘탈을 복구시키고…

Selenium의 스크레이핑

Selenium을 import하기

1
from selenium import Webdriver

대응되는 Driver

1
2
3
4
5
6
Webdriver.Firefox
Webdriver.Chrome
Webdriver.Ie
Webdriver.Opera
Webdriver.PhantomJS
Webdriver.Remote

Selenium으로 DOM 요소 선택

74쪽

Read more »

Selenium

Javascript를 많이 사용하는 웹 사이트는 웹 브라우저를 사용하지 않으면 제대로 동작하지 않아 Requsest 모듈로 대처할 수 없다.

그래서 웹 브라우저를 원격을 조작할 수 있는 도구 Selenium을 사용한다.

  • 자동으로 URL을 열고 클릭할 수 있다
  • 스크롤하거나, 문자를 입력할 수 있다
  • 화면을 캡처해서 이미지로 저장하거나 HTML의 특정 부분을 꺼내는 것도 가능하다
  • 여러 다양한 조작을 자동화할 수 있다
  • 다양한 웹 브라우저에 대응한다
Read more »

HTTP 통신

웹 브라우저와 웹 서버는 HTTP라는 통신규약(프로토콜)을 사용해서 통신한다.

브라우저에서 서버로 요청(request), 서버에서 브라우저로 응답(response)할 때 어떻게 할지를 나타낸 규약이다.


쿠키

무상태(stateless) HTTP 통신으로는 회원제 사이트를 만들 수 없다.(stateless : 이전에 어떤 데이터를 가져갔는지 등에 대한 정보(상태 : state)를 전혀 저장하지 않는 통신)

방문하는 사람의 컴퓨터에 일시적으로 데이터를 저장하는 기능

하지만 1개의 쿠키4096byte의 데이터 크기 제한이 있다.
또한 쿠키HTTP 통신 헤더를 통해 읽고 쓸 수 있다. 따라서 방문자 혹은 확인자가 원하는 대로 변경할 수 있다.
하지만 위의 말대로 쉽게 변경이 가능하기에 비밀번호 등의 비밀 정보는 세션을 통해 다뤄진다.
새션쿠키를 사용해 데이터를 저장하는 점은 같다. 하지만, 방문자 고유 ID만을 저장하고, 실제로 모든 데이터는 웹 서버에 저장하므로 쿠키와는 다르게 저장할 수 있는 데이터에 제한이 없다.

Read more »

새로운 파이썬 파일에 bs4 추가하기(PyCharm)



bs4를 검색하여 찾은 후 install한다.


HTML 구조 확인하기

크롬에서 Ctrl+Shift+i키를 눌러서 개발자 도구를 열어서 확인할 수 있다.
요소 선택 아이콘을 통해 DOM요소 확인
개발자 도구 팝업 메뉴에서 Copy > Copy selector을 사용하면 선택한 요소의 CSS 선택자가 클립보드에 복사된다.

Read more »

첫 업로드

1
2
3
4
5
6
$ git init
$ git remote add origin https://github.com/Zerohertz/Hexo_Blog.git (github의 주소)
$ git add .
$ git remote -v (확인)
$ git commit -m "내용" (주석)
$ git push origin master

수정, 추가 업로드

1
2
3
$ git add .
$ git commit -m "내용"
$ git push origin master

DOM 요소의 속성 추출

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
C:\Users\OHG>python
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from bs4 import BeautifulSoup
>>> soup=BeautifulSoup(
... "<p><a href='a.html'>test</a></p>",
... "html.parser")
>>> soup.prettify()
'<p>\n <a href="a.html">\n test\n </a>\n</p>'
>>> a=soup.p.a
>>> type(a.attrs)
<class 'dict'>
>>> 'href' in a.attrs
True
>>> a['href']
'a.html'
Read more »

라즈베리 파이란?

위 그림과 같이 생긴 보드이며, 아두이노의 상위 호환이라고 볼 수 있다. 특히, Linux기반의 OS가 구동이 가능하여 진짜 컴퓨터처럼 사용할 수 있다. 또한 GPIO를 통한 IOT를 만들 수 있다.

Read more »

크레인 알고리즘

1
2
3
4
5
6
7
8
9
10
11
12
13
if(IR센서가 트랜스포터를 감지){
모터로 줄을 늘임;
전자석을 킴;
모터로 줄을 당김;
모터(바퀴)로 위치를 옮김;
모터로 줄을 늘임;
전자석을 끔;
모터로 줄을 당김;
모터(바퀴)로 원위치로 돌아가게 함;
}
else{
모두 정지;
}
Read more »

변수 선언

1
2
3
4
5
6
7
8
int LED = 11;

int LED;
LED = 11;

#define LED 11 (메모리 사용 X) //define, const는 setup위에 종종 쓴다

const int LED = 11;
Read more »

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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
#include <iostream>
#include <raspicam/raspicam_cv.h>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

using namespace std;
using namespace cv;
typedef struct {
unsigned char r;
unsigned char g;
unsigned char b;
} Color;
typedef struct PosList {
int x;
int y;
struct PosList *next;
} PosList;
int colordiff(Color a, Color b)
{ int dr, dg, db;
dr = (int)((a.r < b.r) ? (b.r - a.r) : (a.r - b.r));
dg = (int)((a.g < b.g) ? (b.g - a.g) : (a.g - b.g));
db = (int)((a.b < b.b) ? (b.b - a.b) : (a.b - b.b));
return dr + dg + db;
}PosList* newnode(int x, int y)
{ PosList *pos;
pos = (PosList *)malloc(sizeof(PosList));
pos->x = x;
pos->y = y;
pos->next = NULL;
return pos;
}void delnode(PosList **pos)
{ free(*pos);
*pos = NULL;
}void pl_push(PosList **list, PosList *pos)
{ pos->next = *list;
*list = pos;
}PosList* pl_pop(PosList **list)
{ PosList *pos;
pos = *list;
*list = (*list)->next;
return pos;
}void dellist(PosList **list)
{ PosList *a, *b;
a = *list;
while (a != NULL) {
b = a->next;
delnode(&a);
a = b;
}
}int contains(PosList *list, int x, int y)
{ while (list != NULL) {
if (list->x == x && list->y == y)
return 1;
list = list->next;
}
return 0;
}void rgrow(IplImage *source, IplImage *dest, Color color, int threshold)
{ PosList *list_n;
PosList *node_r;
PosList *list_r;
Color curcolor;
int x, y;
int sx, sy;
int dx, dy;
int offset;
int mindiff, curdiff;
mindiff = 255 * 3;
for (y = 0; y < source->height; y++) {
for (x = 0; x < source->width; x++) {
offset = y * source->width * 3 + x * 3;
curcolor.b = source->imageData[offset];
curcolor.g = source->imageData[offset + 1];
curcolor.r = source->imageData[offset + 2];
curdiff = colordiff(color, curcolor);
if (curdiff < mindiff) {
sx = x;
sy = y;
mindiff = curdiff;
}
dest->imageData[y * dest->width + x] = 0;
}
}
list_n = newnode(sx, sy);
list_r = NULL;
int* map = new int[source->width*source->height];
for (int i = 0; i<source->width*source->height; i++)
map[i] = 0;
map[sy*source->width + sx] = 1;
while (list_n != NULL)
{
sx = list_n->x;
sy = list_n->y;
pl_push(&list_r, pl_pop(&list_n));
for (dy = -1; dy <= 1; dy++)
{
for (dx = -1; dx <= 1; dx++)
{
if (dx == 0 && dy == 0)
continue;
if (dx != 0 && dy != 0)
continue;
if (sx + dx == -1 || sx + dx == source->width ||
sy + dy == -1 || sy + dy == source->height)
continue;
if (map[(sy + dy)*source->width + sx + dx] == 1)
continue;
offset = (sy + dy) * source->width * 3 + (sx + dx) * 3;
curcolor.b = source->imageData[offset];
curcolor.g = source->imageData[offset + 1];
curcolor.r = source->imageData[offset + 2];
curdiff = colordiff(color, curcolor);
if (curdiff <= threshold)
{
pl_push(&list_n, newnode(sx + dx, sy + dy));
map[(sy + dy)*source->width + sx + dx] = 1;
}
}
}
}
delete [] map;
node_r = list_r;
while (node_r != NULL) {
dest->imageData[node_r->y * dest->width + node_r->x] = 255;
node_r = node_r->next;
}
dellist(&list_r);
}float sum1(std::vector<float>* x, std::vector<float>* y, float yCurr)
{ float sum = 0;
for (int i = 0; i < x->size(); i++)
{
sum += ((*x)[i] * ((*y)[i] - yCurr));
}
return sum / x->size()*-2;
}float sum2(std::vector<float>* x, std::vector<float>* y, float yCurr)
{ float sum = 0;
for (int i = 0; i < x->size(); i++)
{
sum += ((*y)[i] - yCurr);
}
return sum / x->size()*-2;
}void linearRegression(std::vector<float>* x, std::vector<float>* y, int nbData, float& b0, float& b1)
{ float xave = 0;
float yave = 0;
for (int i = 0; i < nbData; i++)
{
xave += (*x)[i];
yave += (*y)[i];
}
xave /= (float)nbData;
yave /= (float)nbData;
float a1 = 0;
float a2 = 0;
for (int i = 0; i < nbData; i++)
{
a1 += ((*x)[i] - xave)*((*x)[i] - xave);
a2 = a2 + ((*x)[i] - xave)*((*y)[i] - yave);
}
b1 = a2 / a1;
b0 = yave - b1*xave;
}void rgrow(Mat *source, Mat *dest, Color color, int threshold)
{ PosList *list_n;
PosList *node_r;
PosList *list_r;
Color curcolor;
int x, y;
int sx, sy;
int dx, dy;
int offset;
int mindiff, curdiff;
int width = source->cols;
int height = source->rows;
mindiff = 255 * 3;
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
offset = y * width * 3 + x * 3;
curcolor.b = source->data[offset];
curcolor.g = source->data[offset + 1];
curcolor.r = source->data[offset + 2];
curdiff = colordiff(color, curcolor);
if (curdiff < mindiff) {
sx = x;
sy = y;
mindiff = curdiff;
}
dest->data[y * width + x] = 0;
}
}
list_n = newnode(sx, sy);
list_r = NULL;
int* map = new int[width*height];
for (int i = 0; i<width*height; i++)
map[i] = 0;
map[sy*width + sx] = 1;
while (list_n != NULL)
{
sx = list_n->x;
sy = list_n->y;
pl_push(&list_r, pl_pop(&list_n));
for (dy = -1; dy <= 1; dy++)
{
for (dx = -1; dx <= 1; dx++)
{
if (dx == 0 && dy == 0)
continue;
if (dx != 0 && dy != 0)
continue;
if (sx + dx == -1 || sx + dx == width ||
sy + dy == -1 || sy + dy == height)
continue;
if (map[(sy + dy)*width + sx + dx] == 1)
continue;
offset = (sy + dy) * width * 3 + (sx + dx) * 3;
curcolor.b = source->data[offset];
curcolor.g = source->data[offset + 1];
curcolor.r = source->data[offset + 2];
curdiff = colordiff(color, curcolor);
if (curdiff <= threshold)
{
pl_push(&list_n, newnode(sx + dx, sy + dy));
map[(sy + dy)*width + sx + dx] = 1;
}
}
}
}
delete[] map;
node_r = list_r;
while (node_r != NULL) {
dest->data[node_r->y * width + node_r->x] = 255;
node_r = node_r->next;
}
dellist(&list_r);
}void findCenterLine(Mat* img, Vec4i& l)
{ int imageHeight=img->rows;
int imageWidth=img->cols;
Mat dist(img->rows, img->cols, CV_8UC1);
Mat dist1(img->rows, img->cols, CV_8UC1);
distanceTransform(*img, dist, DIST_C, CV_DIST_MASK_PRECISE);
normalize(dist, dist, 0.0, 1.0, NORM_MINMAX);
std::vector<float> array;
if (dist.isContinuous())
{
array.assign((float*)dist.datastart, (float*)dist.dataend);
}
else
{
for (int i = 0; i < dist.rows; ++i) {
array.insert(array.end(), dist.ptr<float>(i), dist.ptr<float>(i) + dist.cols);
}
}
double max = 0;
for (int i = 0; i < imageHeight*imageWidth; i++)
{
if (array[i]>max)
{
max = array[i];
}
}
std::vector<float> x;
std::vector<float> y;
for (int i = 0; i < imageHeight; i++)
{
for (int j = 0; j < imageWidth; j++)
{
if (array[i*imageWidth+j]>max*0.1)
{
dist1.data[i*imageWidth + j]=255;
x.push_back((float)j);
y.push_back((float)i);
}
else
{
dist1.data[i*imageWidth + j] = 0;
}
}
}
float b0, b1;
linearRegression(&x, &y, x.size(), b0, b1);
//printf("%f %f\n",b0,b1);
l[0] = 0; l[1] = b0 + b1*l[0];
if(l[1]<=0)
{
l[1]=0;
l[0]=(l[1]-b0)/b1;
}
if(l[1]>=imageHeight)
{
l[1]=imageHeight;
l[0]=(l[1]-b0)/b1;
}
l[2] = imageWidth; l[3] = b0 + b1*l[2];
if(l[3]<=0)
{
l[3]=0;
l[2]=(l[3]-b0)/b1;
}
if(l[3]>=imageHeight)
{
l[3]=imageHeight;
l[2]=(l[3]-b0)/b1;
}
imshow("Dist", dist);
//imshow("Dist1", dist1);
}
int main (void)
{ int imageWidth = 640;
int imageHeight = 480;

raspicam::RaspiCam_Cv Camera;
Camera.set( CV_CAP_PROP_FORMAT, CV_8UC3);
Camera.set( CV_CAP_PROP_FRAME_WIDTH, imageWidth);
Camera.set( CV_CAP_PROP_FRAME_HEIGHT, imageHeight);
Mat orgImg;
Mat cvEdge;
Mat filteredImg(imageHeight, imageWidth, CV_8UC1);

if (!Camera.open()) {cerr<<"Error opening the camera"<<endl;return -1;}
while(1)
{
Camera.grab();
Camera.retrieve(orgImg);
CV_Assert(orgImg.data);
blur(orgImg, orgImg, Size(10,10));
int threshold = 250;
Color color; color.r = 255; color.g = 0; color.b = 0;
rgrow(&orgImg, &filteredImg, color, threshold);

//Canny Edge detector
Canny(orgImg, cvEdge, 10, 10*3, 3);
//Fine center line
Vec4i lineSeg;
findCenterLine(&filteredImg, lineSeg);
line(orgImg, Point(lineSeg[0], lineSeg[1]), Point(lineSeg[2], lineSeg[3]), Scalar(255, 0, 255), 3, CV_AA);

imshow("Org", orgImg);
imshow("Filtered", filteredImg);
imshow("Edge", cvEdge);

if ( waitKey(20) == 27 )break; //ESC키 누르면 종료
}

Camera.release();
}

BeautifulSoup란?

HTML과 XML을 분석해주는 라이브러리.


find_all() 메서드로 <a> 태그 추출하기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from bs4 import BeautifulSoup

html = """
<html><body>
<ul>
<li><a href="http://www.naver.com">naver</a></li>
</ul>
</body></html>
"""

soup = BeautifulSoup(html, 'html.parser')

links = soup.find_all("a")

for a in links:
href = a.attrs['href']
text = a.string
print(text, ">", href)