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

2014년 4월 21일 월요일

OpenCV에서 비디오 파일 읽기

스마트폰에서 촬영한 비디오 파일을 OpenCV에서 읽어 처리하려고 하는 도중 알게 된 살짝 어이없는 사실..

Video I/O API


OpenCV에서 비디오 파일을 처리하기 위해서는 cv::VideoCapture 클래스를 이용한다. 관련 예제들을 참고하면 이런 식이다.

#include "opencv2/opencv.hpp"
namespace cv;

VideoCapture vc;
if ( !vc.open( "path_to_video_file" ) )
    return -1;
namedWindow( "video" );
while (1)
{
    Mat frame;
    vc >> frame;
    imshow( "video", frame );
    if ( waitKey( 30 ) > = 0 ) break;
}

opencv_ffmpeg


위의 코드를 실행해보면 거의 비디오 파일을 열지 못한다. (아주 기초적인 codec만 가능한 것 같음). 이것은 OpenCV에서 AV codec 라이브러리로 사용하는 ffmpeg에 연결되지 못하기 때문인데 해결 방법은 역시 아주 간단하다. (32bit 환경 기준)

  1. OpenCV/3rdparty/ffmpeg 디렉터리에 있는 opencv_ffmpeg.dll 파일을 기존 opencv dll 파일이 있는 디렉터리에 복사한다. (또는 OpenCV/3rdparty/ffmpeg 디렉터리를 path로 지정한다)
  2. 자신이 사용하고 있는 OpenCV 버전을 이용하여 dll 파일명 뒤에 숫자를 붙인다. 예를 들어 OpenCV 2.4.6을 사용하고 있는 경우 opencv_ffmpeg246.dll로 파일명을 바꾸어 준다.

2014년 3월 31일 월요일

Ubuntu13.04에서 WPA2 Enterprise 연결하기

ROS Hydro를 사용하기 위해 어쩔 수 없이 Ubuntu 13.04에서 버전업하지 않고 사용 중. 모바일 로봇에 태우기 위해 제어기용 PC에 무선랜을 연결하기로 하였다.


Linux에 무선랜 연결하기

사용OS - Ubuntu 13.04
무선랜카드 - IPTime N150UA Solo



1. 케이스를 뜯고 안테나를 장착한 후 PC USB슬롯에 꼽는다.

2. 하드웨어를 인식하였는지 확인한다.
  $lsusb
ID 148f:7601에 Ralink Technology, Corp.항목이 있어야 한다.

3. 리눅스용 드라이버를 여기서 내려받는다.

4. 압축을 해제한 후 설치한다. 구글링을 하다보면 소스 몇 군데를 수정하라는 글도 있는데, 그냥 해도 되었다.

  $make
  $sudo make install
  $sudo modprobe mt7601Usta

5. 이제 화면 우측 상단위 네트워크 아이콘을 누르면 Wi-Fi 관련 메뉴가 추가되어 있다. 여기서 적당한 AP를 선택하고 연결하면 된다.

6. 문제는 여기까지는 별 어려움없이 없었지만, LAB에 설치한 사설AP는 잘 되면서 학교 전체에서 서비스하는 WPA2 Enterprise 네트워크에는 연결되지 않는다는 점이다. 설정을 제대로 입력하고 연결을 시도하면 끊임없이 WIFI 인증에 실패하였으니 암호를 다시 입력하라는 창이 나온다...

   여러 가지 자료를 찾아본 결과 우분투 13.4 커널에서의 버그인 것 같으며, 버그의 내용은 WiFi Security 입력 정보 중에 CA Certificate가 반드시 있어야만 연결이 가능하다는 설명이다. 보통 윈도우즈나 스마트폰에서는 CA Cert를 빈칸으로 놓고 잘 연결이 되었었는데 참으로 당혹스럽다.

   해결 방법은 간단한데, /etc/NetworkManager/system-connections 디렉터리에 있는 해당 설정 파일을 열고 system-ca-certs=true 라인을 지워주면 된다. 설정 파일은 앞에서 연결을 시도할 때 생성되며 파일 명은 SSID와 같다.


Windows에 무선랜 IP 알려주기

Ubuntu 머신은 로봇에 태우고 움직이고 다니기 때문에 그 앞을 따라 다니면서 작업을 하기가 쉽지 않다. 작업은 윈도우 데스크탑에서 터미널을 열어 하는 것이 좋겠는데, 문제는 WIFI로 학교의 Enterprise 네트워크에 연결시키다보니 IP주소가 바뀌게 되어 아주 귀찮게 되었다. 이참에 한 가지 더 작업을 하였다. Ubuntu에서 WIFI에 연결이 될 때마다 받은 IP 주소를 작업용 윈도우 데스크탑에 알려주도록 스크립트를 추가하였다.

/etc/NetworkManager/dispatcher.d 디렉터리에 적당한 이름의 파일을 아래와 같이 추가한다.

#!/bin/sh -e
# Script to dispatch NetworkManager events
#
# Runs ifupdown scripts when NetworkManager fiddles with interfaces.
# See NetworkManager(8) for further documentation of the dispatcher events.

if [ "$1" = "ra0" ] && [ "$2" = "up" ]; then
        hostname | nc -u -q 1 foo.bar 9999
fi

당연히 윈도우 머신은 고정 IP 이거나 DNS에 등록된 것이어야 한다. 그 주소를 위 스크립트의 foo.bar 위치에 쓰고 UDP 9999번 포트로 자신(Ubuntu)의 호스트명을 전송하게 한다. 위 스크립트는 WIFI가 연결되어 인터페이스 ra0 이 UP 상태가 될 때마다 실행하도록 한 것이다.

윈도우 쪽에는 9999번 UDP 포트를 리스닝하고 있다가 이를 감지해서 hosts 파일을 업데이트해주는 service를 제작하여 등록해 놓는다. (이건 쉽게 만들 수 있으므로 자세한 설명은 생략^^;)

2014년 3월 22일 토요일

VS2010 MFC App에서 OpenCV 메모리 누수 문제

MFC App에 OpenCV를 링크에서 사용할 때 Debug 모드에서 프로그램 종료 시 메모리 누수(memory leak) 리포트를 볼 수 있다. 증상을 보면 실제 메모리가 누수되는 것이 아니고 _CrtDumpMemoryLeaks()가 호출되는 시점이 OpenCV DLL이 정리되는 시점보다 빨라서 발생하는 false alarm으로 보인다. 따라서 무시하고 개발을 강행하고 나서 Release build를 사용해도 되겠으나 그렇게 하면 내가 작성한 코드에서의 버그에 의해 발생하는 메모리 누수를 디버깅하기 어렵게 된다.

이 문제에 대해 검색을 해보니 제시되고 있는 해결 방법은 아래와 같이 3가지로 요약된다.

  1. MFC DLL을 링크하도록 OpenCV를 rebuild하여 사용한다. (opencv_core에 afx.h를 include하는 등의 약간의 소스 수정 포함 - 자료 출처)
  2. MFC를 static library로 사용한다.
  3. OpenCV를 delay load로 사용한다.
위의 방법들을 실제로 시도해보았으나 OpenCV 이외의 함께 사용하는 3rd party library들의 상황에 따라 여의치 않은 문제가 있다. 그래서 가장 변경 범위가 적은 3번 방법을 사용하여 보았으나 그래도 메모리 누수 리포트가 발생한다.

하나하나 원인을 점검하다 보니, Visual Studio에서 default로 만든 MFC Application이 유니코드로 되어 있어 C런타임이 MSCVR?UD.dll 로 연결되나, OpenCV는 MSVCR?D.dll로 연결되기 때문이 아닌가 싶다. OpenCV를 유니코드 프로젝트로 다시 빌드하는 것은 std::string 부분에서 많은 에러가 나서 포기하고, 어쩔 수 없이 내 MFC Application을 MBCS로 전환하니 메모리 누수 (리포트) 현상이 사라졌다. 요약하면,
  
  1. OpenCV를 사용하기 위해 Unicode App로 작성하는 것을 포기
  2. opencv_core 등의 dll을 링커(Linker)/입력(Input) 항목의 '지연 로드된 DLL(Delay Loaded DLLs)'에 등록한다.

ClearPath Protocol Tester

ClearPath사의 무인 자동차 플랫폼인 Husky A200를 실험용으로 사용하였다.


제조사에서는 C++ 및 Python으로 배포되는 SDK를 이용하거나 ROS 공식 빌드에 포함된 Husky 관련 패키지를 사용하도록 안내하고 있다. 하지만 실험 내용과 실험용으로 개발하는 소프트웨어 구성 및 사용하는 센서들의 조합 등의 문제 때문에 Husky를 직접 제어하는 것이 필요하게 되었다.

ClearPath 홈페이지에 등록하여 내려받을 수 있는 직렬 통신 규약(clearpath_control_protocol_v1.1)에서 규정된 모든 command/request/data 메시지를 주고 받을 수 있도록 tool을 제작하였다.




사용법은 설명이 따로 필요없을 것 같다. Request Message의 경우 Hz 값에 0을 넣으면 1회 조회, 1~65534는 해당 주기로 반복 조회 설정, 65535는 반복 조회 해제가 된다.

MS Office 내에서 수식편집기 입력방법

파워포인트/워드에서 수식 입력할 때 Toolbar(리본) 버튼을 누르면서 작업을 하면 마우스와 키보드를 오가면서 시간이 많이 낭비된다.
구글링을 통해 키보드만으로 수식을 입력하는 방법을 찾아보았다. 이상하지만, 아무리 찾아도 오피스의 수식 입력기 단축키에 대해 공식적으로 정리된 매뉴얼은 없는 것 같다...

수식 입력기 호출하기

Alt키를 눌러 리본 메뉴에 표시되는 내용을 확인해도 알 수 있지만, Alt+N+E+I 단축키로 수식입력기를 호출한다.(워드의 경우) 그러나, 파워포인트의 경우 미리 정의된 몇 가지 수식들을 선택하는 팝업까지 표출될 뿐 결국 마우스를 사용해야 했다.

발견된 몇 가지 원칙

  1. 직관적으로 납득이 갈 만한 수학 기호들을 사용한다.
  2. 항목 별로 수식 모양을 완성하기 위해서는 스페이스 바를 누른다. 앞서 입력한 내용이 수식 완성에 해당하는 것이라면 공백 문자가 추가되지 않고 수식 모양이 바뀐다.
  3. 탈출문자(esacpe character)로 역슬래시(backslash)를 사용한다.
위의 원칙을 가지고 이런 저런 시도를 해보면 어렵지 않게 익숙해지게 된다.

간단한 수식 만들기

※ 아래의 □는 스페이스바를 누르는 것을 의미한다

  • 분수: x/y□  (x+a)/(y+c)□
  • 아래 첨자: x_y□
  • 위 첨자: x^y□
  • 제곱근: \sqrt□ \sqrt(x+y)□
  • 적분: \int□
  • 시그마: \sum□
  • 삼각함수: \sin□  \sin^-1□ 등
  • 행렬: \matrix□ \matrix(@&)□ [\matrix(@&)]□

특수 기호 입력하기

  • 악센트: \hat□□  \dot□□ \ddot□□ \vec□□ \tilde□□
  • 그리스문자: \Alpha□ \alpha□ 등
  • 기타기호: \pm□ \infty□ \ne□ \times□ \div□ \bullet□ 등

등호(=)를 기준으로 정렬하기


연립 방정식과 같이 수식을 여러 줄 표시할 때 등호를 기준으로 가로 정렬을 하고 싶을 경우에는
  1. 함께 정렬할 수식에서 줄 바꿈할 때 Shift+Enter를 사용한다. 이것은 아래 줄의 수식을 위 줄과 같은 그룹으로 인식한다.
  2. 정렬할 등호 앞에 &(ampersand)를 추가한다. 즉, A &= 1 와 같이 입력한다.
  3. 수식을 Professional type으로 변경한다. 이것은 수식 리본 메뉴에서 [도구]의 [2차원 형식] 버튼을 사용하거나, 수식 위를 우클릭하여 나타나는 팝업 메뉴에서 [수학옵션][전문가용] 메뉴를 사용한다.


출처

ROS 시작하기

ROS Tutorial(http://wiki.ros.org/ROS/Tutorials/)에 있는 용어 및 필수 개념에 대해 요약

노드(nodes) 다른 노드와 통신을 하기 위해 ROS를 사용하는 실행 파일
메시지(messages) 토픽(topic)에 가입(subscribe) 혹은 게시(publish)할 때 사용되는 ROS의 데이터 형식
토픽(topic) 노드 사이에서 메시지를 주고 받게 해 주는 매개체
서비스(services) 요청(request)을 다른 노드에 보내거나, 다른 노드로부터 응답(response)을 받음
마스터(master) 노드에 이름으로 지정할 수 있게 해주는 서비스

rospack 패키지에 대한 정보 조회
find 패키지가 설치된 위치의 디렉터리 경로를 표시
roscd 패키지나 스택의 디렉터리로 이동
rosls 절대 경로를 지정하지 않고 패키지 디렉터리에서 ls 실행
roscp [package_name] [file_to_copy_path] [copy_path]

rosout ROS에서 stdout/stderr 역할을 함
roscore 마스터 + rosout + 파라미터 서버
rosnode 노드에 대한 정보 표시 도구
ping 노드에 대한 연결 테스트
list 활성화된 노드 목록 표시
info 노드에 대한 상세 정보 표시
machine 특정 기계에서 실행 중인 노드 목록을 표시하거나, 기계 자체 목록 표시
kill 실행 중인 노드를 종료 시킴
cleanup 연결이 끊어진 노드에 대해 등록된 정보를 삭제
rosrun (패키지에 대한 경로를 지정할 필요 없이) 소속된 패키지 이름과 노드 명 만으로 노드를 실행시킴
rostopic 토픽에 대한 정보 조회
bw 토픽에서 사용 중인 밴드폭 표시
echo 메시지를 화면에 표시
hz 토픽의 게시 주기를 표시
list 활성화된 토픽들의 목록 표시
pub 토픽에 데이터 게시
type 토픽의 형식 표시
rosmsg ROS 메시지 형식에 대한 정보 표시 도구
show 메시지 설명 표시
list 모든 메시지 목록 표시
md5 메시지의 md5 체크섬 표시
package 패키지 내의 메시지 목록 표시
packages 메시지를 포함하는 패키지 목록 표시
rosservice
list 활성화된 서비스에 대한 정보 표시
call 인자(argument)와 함께 서비스를 호출
type 서비스 형식을 표시
find 서비스 형식으로 서비스를 찾음
uri 서비스의 ROSRPC uri를 표시
rosparam ROS 파라미터 서버에 데이터를 저장하거나 조작한다
set
get
load
dump
delete
list
roslaunch 노드를 launch file에서 정의된 바에 의해 실행
rosed 절대 경로를 지정하지 않고 패키지 디텍터리 내의 파일을 편집

msg ROS 메시지의 필드를 기술하는 텍스트 파일. 서로 다른 언어에서 메시지에 대한 소스 코드를 생성하는데 사용한다.
srv 서비스를 기술하는 파일. 요청과 응답 2가지 부분으로 구성된다.

rosbag 토픽의 내용을 로그로 기록 및 재생한다.
roswtf ROS 관련 오류를 분석하여 표시한다.

행렬의 선형대수 용어

논문을 읽을 때나 쓸 때나 사용되는 수식의 대부분은 행렬 연산이다. 방법은 알아도 행렬 연산과 관련된 용어가 기억나지 않아서 곤란하게 된다. 학부 때 공부했던 Advanced Engineering Mathematics Chapter 6~7 (Erwin Kreyszig)의 내용 중에서 행렬의 기본적인 용어에 대해 공부해보자.

  • matrix - rectangular array of numbers enclosed in brackets
  • row - horizontal line in matrix
  • column - vertical line in matrix
  • row|column vector - matrix which consists of a single row|column
  • square matrix - matrix which has as many rows as columns
  • rectangular matrix - matrix that is not square
  • main(principal) diagonal - diagonal entries a11, a22, a33, ..., ann of square matrix
  • transposition - transpose of A of mxn matrix [ajk] is nxm matrix that has the first row of A is as its first column, the second row of A as its second column, and so on.
  • matrix addition - for matrices A and B of the same size, A+B is obtained by adding the corresponding entries
  • scalar multiplication - product of mxn matrix A and any scalar c, written cA, is obtained by multiplying each entry in A by c
  • zero matrix - matrix with all entries zero
  • matrix multiplication - product C=AB(in this order) of an mxn matrix A and an rxp matrix B is defined if and only if r=n and is defined as the mxp matrix C with entries cjk=aj1b1k+aj2b2k+...+ajnbnk. "multiplication of rows into columns". The matrix B is premultiplied, or multiplied from the left, by A. A is postmultiplied, or multiplied from the right, by B
  • triangular matrix - upper triangular matrices are square matrices that can have nonzero entries only on and above the main diagonal, whereas any entry below the diagonal must be zero. lower triangular matrices can have nonzero entris only on and below the main diagonal.
  • diagonal matrix - square matrix that can have nonzero entries only on the main diagonal
  • scalar matrix - all the diagonal entries of a diagonal matrix S are equal
  • unit(identity) matrix - scalar matrix whose entries on the main diagonal are all 1
  • inner product - single entry given by matrix multiplication if a is a row vector and b a column vector, both with n components
  • stochastic matrix - a square matrix with nonnegative entries and row sums all equal to 1
  • Markov process - a stochastic process for which the probability of entering a certain state depends only on the last state occupied (and on the matrix governing the process)
  • linear system - a linear system of m equations in n unknowns x1, x2, ..., xn is a set of equations of ai1x1 + ... ainxn=bi
  • coefficients - number ajk of the system
  • homogeneous system - linear system if the bi are all zero
  • nonhomogenouse system - linear system if at least one bi is not zero
  • solution - a set of numbers x1, ..., xn that satisfies all the m equations
  • solution vector - a vector x whose components constitute a solution of linear system
  • augmented matrix - augmenting coefficients matrix A by the column b
  • Gauss elimination - a systematic elimination process and a standard method for solving linear systems
  • pivot equation - an equation used in eliminating the other equations by Gauss's method
  • partial pivoting - exchanging the order of equations
  • total pivoting - the order of the equations and unknowns are changed
  • back substitution
  • elementary row operation - interchange of two rows, addition of a constatnt multiple of one row to another row, multiplication of a row by a nonzero constant c
  • row-equivalent system - a linear system S1 is row-equivalent to a linear system S2 if S1 can be obtained from S2 by elementary row operations
  • overdetermined - if a linear system has more equations than unknowns
  • determined - if a linear system has as many equations as unknowns
  • underdetermined - if a linear system has fewer equations than unknowns
  • echelon form - the form of the system and of the matrix in the last step of the Gauss elimination
  • linearly independent - vectors a(1), ..., a(n) is linearly independent if it has the only m-tuple of scalars with all cj's zero that holds the equation of linear combination c1a(1)+c2a(2)+...+cma(m)=0
  • linearly depdenent - vectors a(1),,,,a(n) can be expressed at least one of them as a linear combination of the others
  • rank of matrix - the maximum number of lineraly independent row vectors of a matrix
  • vector space - a nonempty set V of vectors such that with any two vectors a and b in V all their linear combinations αa+βb are elements of V, and these vectors satisfy the laws - commutative, distributive, associative.
  • dimension of vector space - the maximum number of lineary independent vectors in a vector space
  • basis - a linearly independent set in vector space V consisting of a maximum possible number of vectors in V
  • span - the set of all linear combinations of given vectors a(1),...,a(p) with the same number of components
  • subspace - a nonempty subset of vector space V that itself forms a vector space with respect to the two algebraic operations defined for the vectors of V
  • row|column space - the span of the row|column vectors of a matrix
  • solution(null) space - vector space (of dimension n-r) formed by solutions of homogeneous linear system(mxn) whose rank is r
  • nullity - dimension of null space of linear homogeneous system
  • determinant - a scalar associated with an nxn matrix A, D=aj1Cj1+aj2Cj2+...+ajnCjn=a1kC1k+a2kC2k+...+ankCnk where Cjk=(-1)^(j+k)*Mjk
  • submatrix - matrix Mjk is obtained from matrix A by deleting the row and column of the entry ajk
  • minor - submatrix Mjk in determinant D
  • cofactor - Cjk in determinant D
  • inverse - inverse of an nxn matrix A=[ajk] is denoted by A^-1 and is an nxn matrix such that A*A^-1=A^-1*A=I where I is the nxn unit matrix. inverse of A exists if and only if rank A=n or det A≠0
  • nonsingular matrix - matrix which has an inverse
  • singular matrix - matrix which has no inverse
  • mapping(transformation or operator) - To each vector x in vector space X, a unique vector y in vector space Y can be assigned
  • image - the vector y in Y assigned to vector x in X
  • linear mapping(linear transformation) - if for all vectors v and x in X and scalars c, F(v+x)=F(v)+F(x) and F(cx)=cF(x)
  • eigenvalue(characteristic value) - a scalar value λ for which a solution x≠0 of the vector equation Ax=λx. The eigenvalues of a square matrix A are the roots of the characteristic equation of A.
  • eigenvector(characteristic vector) - a vector solution x≠0 of the vector equation Ax=λx
  • spectrum - the set of the eigenvalues
  • spectral radius - the largest absolute values of the eigenvalues
  • eigenspace - a vector space formed by the set of all eigenvectors corresponding to an eigenvalue, together with 0
  • eigenvalue problem - the problem of determining the eigenvalues and eigenvectors of a matrix
  • characteristic determinant(characteristic polynomial) - D(λ)=det(A-λI)
  • characteristic equation - D(λ)=0
  • algebraic multiplicity - the order Mλ of an eigenvalue λ as a root of the characteristic polynomial
  • geometric multiplicity - the number mλ of linear independent eigenvectors corresponding to λ
  • defect - the difference Δλ=Mλ-mλ
  • symmetric matrix - square matrix whose transpose equals the matrix : A^T=A
  • skew-symmetric matrix - square matrix whose transpose equals the minus matrix : A^T=-A
  • orthogonal - square matrix if its transposition gives the inverse of itself : A^T=A^-1
  • orthogonal transformation - y=Ax with A an orthogonal matrix. orthogonal transformation preserves the value of inner product of vectors and also the length or norm of a vector
  • similarity transformation - A=P^-1AP where P is nonsingular nxn matrix

어안렌즈 카메라 모델링

일반적으로 많이 사용하는 pin hole camera model은 광선의 직진성을 가정하며, 대부분의 camera calibration tool들은 이를 기반으로 동작한다. 이러한 경우 perspective projection을 모델링한 camera matrix 및 렌즈/센서의 제조 상 오차를 반영한 distortion coefficient로 수식화 할 수 있다.

어안 렌즈(Fish eye lens)의 경우 광선이 직진하지 않고 굴절하기 때문에 distortion coefficient 중의 radial distortion 만으로 정확한 calibration 결과를 얻기 어렵다.

 

위의 그림에서 어안 렌즈를 대표적인 수식으로 표현하면 d = f * θ 가 되는데 이를 f-theta 모델이라고 한다. pin hole 카메라는 d = f * tanθ 로 나타낼 수 있다.

f-theta 모델의 어안 렌즈로 촬영한 영상을 가공하기 위해서는 위의 식을 기반으로 모델 좌표와 이미지 좌표의 대응 관계를 유도해야 한다. 예를 들어, 수평 방향으로 촬영한 영상으로부터 top view를 얻기 위해서는

 

Focal length가 f인 어안 렌즈로 촬영된 이미지 상의 점 m과, 카메라의 지면으로부터의 높이가 R일 때 대응하는 지면 상의 점 M과의 관계는, m과 M의 3차원 좌표가 각각 m(u,f,v) M(x,y,R)이라 할 때,

F-theta 모델
에서, d는 이미지 평면 원점에서 (u,v)까지의 거리이고 theta는 좌표 원점과 M 및 M'으로 이루어지는 삼각형을 이용하면
를 알 수 있고 이를 대입하여 풀면,
와 같이 구할 수 있다.
홈