레이블이 read인 게시물을 표시합니다. 모든 게시물 표시
레이블이 read인 게시물을 표시합니다. 모든 게시물 표시

2017년 11월 26일 일요일

python, read txt line-by-line

list = open(FILENAME).read().splitlines()

만약 한글이 있어서,
UnicodeDecodeError: 'cp949' codec can't decode byte 0xa7 in position 55: illegal multibyte sequence
이라면, 다음으로 대체

import codecs
list = codecs.open(FILENAME, 'r', 'utf-8').read().splitlines()

그럼에도 아래와 같은 에러가 생긴다면
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb0 in position
다음으로 대체

'utf-8' -> 'euc-kr'

2017년 9월 20일 수요일

python으로 list를 line-by-line으로 read와 write하자.

문제:
python으로 list를 line-by-line으로 read와 write하자.

해결:
def read_list_linebyline(fname):
    with open(fname) as fid:
        content = fid.readlines()
    content = [item.rstrip('\n') for item in content]

    return content


def write_list_linebyline(fname, thelist):
    fid = open(fname, 'w')

    for item in thelist:
        fid.write('%s\n' % (item))

    fid.close()



2016년 11월 16일 수요일

matlab text file read

문제
matlab에서 text file을 읽을 때, 처음 몇 줄을 skip하고 읽고 싶은 경우.
ex) in READ.txt
_____________________________
ID    ADDR     TEL(no blank)
int   char[]      int
1     abcd       012345
3     zzzz        012454
...
_____________________________

해결
textread()함수 이용
[id, addr, tel] = textread(strfilename, '%d %s %d', 'headerlines', 2);

기타 textscan, dlmread 들도 가능함.


2016년 4월 20일 수요일

opencv Mat 저장하기 (CV32FC1과 같이 UINT가 아닌 경우)

opencv에서 보통은 아래와같이 읽고, 저장한다.
Mat matImage = imread("asdf.png", IMREAD_UNCHANGED);
imwrite("asdf.png", matImage);

그런데 위의 경우는 주로 Mat의 element가 uint인 경우이다(depth는 1, 2, 3이든...)

하다보면 float인 경우가 있는데 이럴 때는
1. Mat의 포맷은 uint로 바꾸거 위 방법으로 저장하든,
2. FileStorage Class를 사용해야한다.

2의 방법을 사용하는 법은 아래와 같다. 이때는 이미지 포맷이 아닌 xml 혹은 yaml로 저장해야한다(확장자가).

저장할 때,
cv::FileStorage fs_w("asdf.xml", cv::FileStorage::WRITE);
fs_w << "matImage" << matImage; 
fs_w.release();
// fs_w << "matImage" << matImage << "변수명" << 변수 <<... // 만약 변수가 더있다면

불러올 때,
cv::FileStorage fs_r("asdf.xml", cv::FileStorage::READ);
// 방법1(Mat이 아닌 type인 경우).
int a = (int)fs_r["a"];
// 방법2(Mat인 경우).
Mat matImage;
fs_r["matImage"] >> matImage;
fs_r.release();

<출처: http://docs.opencv.org/2.4/modules/core/doc/xml_yaml_persistence.html>

사실 위 기능은 iostream과도 유사한데 속도면에서 더 빠르다고 한다.(약 50~60%정도)
<출처: http://stackoverflow.com/questions/16312904/how-to-write-a-float-mat-to-a-file-in-opencv>