OpenCV tips

프로그래밍/OpenCV 2014. 3. 31. 20:56

Here are some useful tips which helped me a lot in programming with OpenCV and I recorded those here because I don't want to spend my time again to find such rare tips.


List


1. Problem which drawing primitives such as line, ellipse, text with certain NON-White scalar color on image of type cv::Mat produce only WHITE colored traces (RGB(255,255,255)). 


Recommendation: Firstly, check whether the input image type is CV_8UC4. If so, then converted the input to CV_8UC4 using cvtColor(). Look below example.


cvtColor(image, image, CV_RGBA2BGR);

Whole story can be founded here.


2. To be added later...


   

Posted by kevino
,

Useful commands used in Windows commands shell


As Unix script language is actually quit powerful to do manipulate text, files/directories and so on, on Windows machine, there are many ways to do the same jobs. Here some useful examples which can be used in normal Windows .bat or .cmd and are also quit helpful in many option menus supported in Visual Studio. For example, before actual compilation of a project, someone may want to copy or create resources necessary to build binary to certain location or add a time stamp string to many source code files. For this purpose, we can add custom commands in Pre-build Event options of Visual Studio property setting window. 


So hope these examples show you a guidance on that. Again this information were taken from various link which I cannot remember correctly.



1. Searching files having specific extension in its file name in current folder


for %%f in (*.java *.cmd) do echo  %%f


2. Searching files with .java extension recursively  


dir /b /s /a-d | findstr /i ".java$


3. Find and delete files with certain name recursivly

 i) In batch file,

    for /f "usebackq" %%i in (`dir /s /b ^| find "Makefile"`) do echo %%i

 ii) In command line,

    for /f "usebackq" %i in (`dir /s /b ^| find "Makefile"`) do echo %i


 ** Note: replace "echo" with "del" to delete file instead of echoing file name.


4. Create array containing file names with full path located in specific folder. Note: In Windows there seems a limitation in assigning array from command line with use of pipe. So this is different trial to do that.

setlocal enabledelayedexpansion enableextensions

set LIST=

for %%x in (javaSourceFolder\*.java) do set LIST= %%x

set LIST=%LIST:~1%


5. Compiling all java files located at specific folder

---- Assuming %LIST% having file list with full path  ---

for %%f in (%LIST%) do (

 "$(JDK_ROOT)\bin\javac.exe" -d $(IntDir)$(JavaOutputDir) -classpath $(IntDir)$(JavaOutputDir) -classpath $(AndroidSdkApiDir)/android.jar %%f

)


6. QT

When you need to decide which build configuration among 32bit and 64bit, don't forget to keep using only one configuration. For example, if you develop qt application using Visual Studio C/C++ 20xx and want to use command prompt to build it, you need to choose build environment among 32bit, 64bit and 64bit_opengl. Once you pick one among them, DON'T FORGET to call proper bat file for Visual Studio compilation setup.


If you want 32bit QT application, run below command after opening QT command prompt

call "C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\bin\vcvarsall.bat" x86


If you want 64bit QT application, run below command after opening QT command prompt

call "C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\bin\vcvarsall.bat" x64


7. later...


Posted by kevino
,

한국의 소득양극화가 개선될 조짐은 별로 보이지 않고 오히려 더 심화해지고 있다. 이것을 뒷받침하는 기사가 나왔길레 기록으로 남겨둔다.


돈, 가계보다 기업으로 풀렸다

서울 소공동 한국은행 본점에서 관계자가 각 금융기관으로 보낼 자금을 방출하는 작업을 하고 있다. <<연합뉴스DB>>

(서울=연합뉴스) 박수윤 기자 = 시중의 돈이 가계로 유입되는 속도보다 기업으로 흘러가는 속도가 더 빠른 것으로 나타났다.

8일 한국은행이 '통화 및 유동성' 자료에서 공개한 경제주체별 통화 통계를 보면, 지난해 11월 가계 및 비영리단체가 보유한 시중통화량(M2)은 전년 같은 달보다 4.1%(평잔·원계열) 증가하는 데 그쳤다.

반면 기업의 M2 증가율은 9.9%에 이르렀다. 가계의 2배를 훌쩍 넘는 수준이다.

M2는 언제라도 사용할 수 있는 현금과 금융자산을 의미한다. 현금과 요구불예금(M1), 2년 미만 정기 예·적금, 머니마켓펀드(MMF) 등 시장형 상품을 포괄하는 대표적인 유동성 지표다. M2 증가율이 높을수록 시중에 풀린 돈이 많아졌다는 의미다.

가계와 기업의 M2 증가율은 2010년 각각 8.0%, 10.9%로 격차가 크지 않았다.

그러나 2011년 가계가 4.1%, 기업이 7.5%로 떨어지고 2012년 각각 4.3%, 6.8%를 기록한 뒤 가계와 기업 간 차이가 벌어지고 있다.

2013년 하반기에는 7월(2.5%, 8.3%)에 견줘 9월(3.6%, 8.0%)엔 격차가 좁혀졌다가 11월(4.1%, 9.9%) 들어 다시 차이가 나는 모습이다.

한 달 전과 비교하더라도 가계 및 비영리단체의 보유 통화(평잔·계절조정계열)는 4조9천억원 늘어난 반면, 기업은 5조7천억원 늘어났다. 수출 대기업을 중심으로 일시여유자금 예치가 늘어나 기업 부문의 보유 통화가 증가했다는 게 한은의 설명이다.

실제로 우리나라 국민소득에서 노동소득이 차지하는 비중을 나타내는 노동소득분배율은 2006년 61.3%를 정점으로 2012년에는 59.7%로 감소했다.

경제협력개발기구(OECD) 회원국의 경우 2011년 기준으로 미국 67.3%, 영국 70.7%, 독일 66.9%, 일본 70.7% 등 한국보다 10%포인트가량 높다. 그만큼 기업이익 중 근로자 임금으로 돌아가는 몫이 크다는 의미다.

한은 관계자는 "기업의 M2 증가율이 더 높은 건 맞지만 가계, 기업 모두 꾸준히 안정적인 증가율을 보이고 있다"며 "가계의 보유통화 규모 자체가 기업보다 크기 때문에 증가율 자체는 낮을 수밖에 없다"고 말했다.

clap@yna.co.kr

<저작권자(c)연합뉴스. 무단전재-재배포금지.>2014/01/08 12:00 송고

Posted by kevino
,

이 글은 아래 나와있는 주소에서 퍼온 것임을 밝히고 펌이 문제시 될 경우 언제든지 삭제가 가능함.


 http://www.thisisgame.com/webzine/news/nboard/11/?n=51843.



[게임과 권력] ③ 뉴라이트와 게임규제 (1/2)

뉴라이트, 게임 규제에 공격적으로 뛰어들다

‘뉴라이트’를 혹시 아시나요? 그들과 게임은 어떤 사이일까요? 작은 궁금증에서 시작했는데, 꼬리가 꼬리를 물게 되더군요. 결국, 돈과 권력을 둘러싼 이야기입니다.

 

‘Shut down!’(문 닫어!)에서 ‘Show me the money!’(돈 내놔!)로 옮겨진 게임규제 이슈의 전환. 그 변화의 물꼬에는 ‘뉴라이트’가 있었습니다. /시몬

 

 

2011년 3월의 기억


2011년 3월 16일 오후 국회 소회의실, 이정선 의원(한나라당)과 민생경제정책연구소가 공동주최한 ‘인터넷중독 예방·치료 기금마련을 위한 기업의 역할’이라는 제목의 토론회.

 


 

이 행사는 두 가지 면에서 아직도 뚜렷이 기억됩니다.

 

1. 게임중독기금의 기업 부담


게임중독을 '수익자부담원칙'에 의해 기업 부담으로 해결하자는 주장이 공식적인 자리에서 처음으로 등장했습니다.


패널로 참가한 김춘식 경민대 교수는 "방송의 경우 방송발전기금을 조성하고 있는데, 금액은 매출액의 6% 이내에서 결정된다. 원인을 제공한 기업이 매출의 일정액을 기금으로 부담해야 하는 것은 당연하다”고 주장했습니다. 2010년 국내 게임시장 규모는 약 6조6,000억 원이었으니까, 방송의 경우를 적용할 때 약 4,000억 원의 기금을 걷자는 얘기였죠.

 

권장희 놀이미디어교육센터 소장도 "게임업계는 그 이익의 10% 이상을 중독 문제를 해결하고 아동 청소년들을 중독으로부터 예방하기 위해 출연해야 한다"고 주장했습니다. 당시 2조 원 가까이 됐던 게임산업 영업이익을 감안할 때 그가 기대하는 기금 규모는 2,000억 원 수준이었죠.


2,000억과 4,000억. 게임업계가 바짝 긴장할 수밖에 없었던 날이었습니다.


2. 짐승뇌


이날 권장희 소장이 이야기한 ‘짐승뇌’가 게이머들의 공분을 샀습니다.

 

권 소장은 "게임 중독에 빠진 아이들은 전두엽의 발달이 늦어져 모든 일에 반사적이고 공격적인 성향을 보이는 짐승과 비슷한 상태로 변한다. 지금 (한국의) 교실에는 게임 때문에 얼굴은 사람인데 뇌 상태가 짐승 같은 아이들이 있다"고 주장했습니다.


게임을 하면 전두엽에 문제가 생긴다는 주장은 2002년 일본에서 발간돼 화제가 됐던 <게임뇌의 공포>(모리 아키오, NHK 출판)와 흡사합니다. 체육학과 교수인 저자는 사람이 게임을 즐길 때의 뇌파가 치매 상태와 비슷하게 변해 전두엽 전부피질의 기능을 떨어뜨리는 현상을 발견했다고 주장했습니다.


현재 이 주장은 일본이나 전 세계적으로 ‘말도 안 되는 가설’로 취급받고 있습니다. 일본 신경과학학회 회장 출신인 츠모토 타카지 교수 교수는 ‘신경학에 대한 신뢰를 해친다’고 비판했고, 미국의 연구기관 Mind Research Network는 <테트리스>를 하면 오히려 전두엽 부위의 효율화가 진행된다는 연구결과를 발표했죠. 이에 관한 이야기는 이 시리즈 다음 꼭지에서 조금 더 다루기로 하고, 여기서는 패스.


당시나 그 후, 게임매체를 포함한 주요 언론의 관심과 보도는 이 두 가지 이슈에 집중했습니다.


토론회 당시나 그 후, 게임매체를 포함한 주요 언론의 관심과 보도는 이 두 가지 이슈에 집중했습니다.

 

 

토론회 뒤의 큰 그림자 : 뉴라이트


최근 게임업계에 대한 각종 규제 법안이 넘쳐, 이 행사를 되짚어봤습니다. 그때는 잘 안 보였던 게 보였습니다.

 

토론회에 참석했던 인물들의 대단한 면모였죠.

 



1. 이상득 의원(한나라당): 이명박 대통령 정권 내내 '상왕'(上王)이라고 불릴 정도로 큰 영향력을 발휘했던 정치인입니다. '만사형통'(모든 일은 형을 통하면 된다)이라는 별명을 보면 어느 정도 힘이 셌는지 짐작할 수 있습니다.

 

2. 박희태 국회의장(한나라당): 금배지를 6번이나 단 관록의 정치인입니다. 2008년 정몽준 의원을 누르고 한나라당 대표로 선출됐고, 2010년 제18대 국회 후반기 국회의장이 됐습니다. 대통령, 대법원장과 함께 삼부요인이었죠.

 

3. 김무성 원내대표(한나라당): 당시 4선의 중진 국회의원이었습니다. 2007년 대선에서 이명박 선거대책위원회의 부위원장이었고, 그 해 11월 최고위원의 자리에 올랐죠. 공천 탈락 후 무소속으로 당선된 뒤 다시 한나라당으로 돌아와 원내대표까지 됐습니다.


4. 안경률 행정안전위원장(한나라당): 당시 3선의 중진 국회의원이었습니다. 한나라당 친이명박계 모임인 '함께 내일로'의 대표였죠. 토론회 당시 원내총무 경선을 준비하고 있었습니다.

 

깜짝 놀랐습니다. 역대 게임과 관련된 토론회나 공청회를 아무리 뒤져봐도, 이 정도의 인물들이 참석하는 경우는 없었습니다. 당대 최고 실세들의 등장. 도대체 왜 이랬을까요?


행사를 주최한 측을 살펴봤습니다. 이정선 의원. 큰 지명도나 영향력은 없던 초선의 비례대표 의원이었습니다. 패스.

 

민생경제정책연구소. 개인적으로 생소했습니다. 민생 경제를 염려하는 곳 같았습니다. 그런데, 이런 곳이 왜 이런 행사를 했을까, 어떤 영향력이 있어 거물들을 불렀을까 하는 의문이 생기더군요. 더 들여다봤습니다. ‘뉴라이트’라는 단어가 튀어나왔습니다. 민생경제정책연구소는 2008년 10월 ‘사단법인 뉴라이트’가 이름을 바꾼 곳이더군요.

 

이 연구소의 이사장인 김진홍 목사도 이날 행사에 참석했습니다. 의문이 풀렸습니다.


김 목사는 2007년 대선에 영향을 미친 뉴라이트 운동을 주도한 인물입니다. 당시 17만 명의 회원을 가진 뉴라이트 전국연합의 상임의장으로, 이명박 정권의 핵심 개국공신 중 한 명이었죠. 언론에선 ‘멘토’ 또는 ‘절친’이라는 수식어로 이 대통령과의 두터운 교감을 표현하곤 했습니다. 종교계의 반발에도 불구하고 청와대에 들어가 몇 차례 가족예배를 집전할 정도로 친밀한 사이였고요.


이런 인물이 뜨고, 이사장을 하고 있는 곳에서 주최한 행사이니, 당대 거물급 정치인들이 모여들 수밖에요.


※ 뉴라이트란?

 

일반적으로 뉴라이트 전국연합, 시대정신, 한반도선진화재단 출신 인사들을 뉴라이트로 분류합니다. 이 단체 출신이 아니어도 이승만·박정희 재평가, 국가 정체성, 북한 인권운동 등을 강조하는 세력을 포괄적으로 뉴라이트로 묶기도 하죠.

 

2004년 총선 패배 이후 행정부와 입법부를 빼앗긴 보수세력은 ‘뉴라이트’라는 이름으로 뭉쳤고, 2007년 대선에서 ‘이명박 정권 만들기’에 전력질주했습니다. 뉴라이트 전국연합은 박근혜 후보와의 당내 경선, 이회창 무소속 후보의 출마 국면에서 이 대통령을 전폭적으로 지지했죠. 이 대통령은 당선 직후인 2007년 12월 22일 뉴라이트전국연합 송년회에 참석했습니다.

 

이명박 정부 들어 뉴라이트의 많은 인사들이 정치권에 진입했습니다. 신지호, 조전혁, 박영아, 김성회, 장제원 등은 18대 총선에서 국회의원에 당선됐죠.


뉴라이트 학자들이 주축이 된 교과서 포럼은 2008년 식민지 근대화론, 이승만·박정희 긍정적 재평가론이 담긴 <대안교과서>를 펴낸 데 이어, 2011년에는 <대안교과서>의 내용을 토대로 교육과학기술부에 ‘역사교육과정 수정 건의서’를 제출하기도 했죠.

 

 

뉴라이트의 게임중독에 대한 집착


그런데, 이게 처음이 아니었습니다. 민생경제정책연구소와  이정선 의원이 공동주최한 토론회가 전해에도 있었더군요. 2010년 1월 국회 헌정기념관 2층 대강당에서 ‘인터넷중독 예방과 치료관련 입법마련’이라는 제목의 토론회가 열렸습니다. 이날도 거물급 정치인들이 참석했죠. 정몽준 최고위원, 전재희 보건복지부 장관, 유인촌 문화관광부 장관 등.

 

‘수익자부담 원칙에 따른 인터넷중독 예방 재원 마련’이란 논리는 이 때부터 이미 등장했습니다. 패널로 참석한 김춘식 민생경제정책연구소 방송통신정책전문위원은 “청소년층의 인터넷중독을 예방하기 위한 본격적인 투자가 필요하며 재원은 수익자부담 원칙에 의해 인터넷 사업자가 부담해야한다”고 주장했습니다.


김춘식 위원. 어디서 들어봤나 했더니, 2011년 3월 토론회에서 4,000억 원의 기금조성을 주장했던 경민대 교수였습니다. ‘사업자 부담의 재원 마련’이라는 뉴라이트의 주장은 2010년부터 일관된 기조가 서 있었던 모양입니다.

 

이의 실현을 위해 민생경제연구소는 2010년 1월 상반기부터 활활 불타오릅니다.

 

1월 25일 논평


엔씨소프트 등 인터넷게임 사업자들에게 동일인의 자사게임 이용시간을 주당 15시간 이하로 제한하도록 할 것을 제안한다.

 

또한, 정부는 사행성이 있는 어떤 인터넷게임업체를 이용하더라도 종합하여 주당 15시간 이하로 인터넷게임 이용을 제한할 수 있는 컴퓨터서버를 도입하여 과도한 게임시간으로 발생할 수 있는 폐해를 최소화해야 할 것이다.


인터넷게임산업도 사행산업으로 규제해야 한다. 사행산업통합감독위원회는 인터넷게임도 사행산업으로 분류해 통합감독하여야 한다.

2월 22일 성명


친어머니 살해하게 한 인터넷게임업체는 공식 사과하라. 경찰은 비극적 인터넷게임의 명칭을 밝히고, 정부는 인터넷중독성 조사하라.

3월 2일 논평


게임중독, 대통령 직속기관에서 관리해야 할 심각한 문제다. 어린이, 청소년보호 특별법 제정하고, 모든 중독으로부터 보호해야 한다.

 

게임중독에 대해 공급자들에 대한 부담을 지워야함은 물론이고, 게임중독을 야기하지 못하도록 모든 법규를 동원해야 한다.

3월 7일 성명


문화부, 하루 10시간 게임해도 좋은지 입장을 밝혀라. 문화체육관광부와 게임사들과의 간담회에서 분명히 밝혀야 한다.

4월 1일 논평


문화체육관광부의 게임아이템 거래금지 검토, 환영한다. 폭력성, 사행성 게임은 육성해야 할 산업이 아니다.

1월에 꼭 집어 비판을 받았던 엔씨소프트는 1년이 지나 다시 지탄을 받습니다.


2011년 1월 19일 논평


게임중독 문제해결은 게임업체가 주도해야 한다. 사회적책임은 뒷전이며 프로야구 진출에만 매진하는 업체는 사회적 지탄을 받아야 마땅하다.

 

뉴라이트의 사정


민생경제정책연구소는 2010년 1월부터 줄기차게 인터넷게임 업체와 정부를 압박했습니다. 그리고, 중독 예방 재원 마련을 위한 게임회사의 책임을 강조했죠.

 

당시의 게임규제와 관련된 초미의 관심사는 ‘셧다운 제도’였습니다. 대부분의 규제 찬성론자들은 '청소년보호법' 개정을 통한 셧다운제 쟁취에 전력질주하고 있었던 형국이었죠. 그런데, 민생경제연구소는 왜 갑자기, 그리고 벌써 ‘쇼미더머니’를 외치고 있었던 걸까요?

 

이 시절 뉴라이트의 사정을 들여다봤습니다.

 

2008년 2월, 뉴라이트의 전폭적인 지원을 받은 이명박 정부가 출범했습니다. 집권 후 뉴라이트 측은 확실한 논공행상을 기대했을 겁니다. 대통령 당선자가 뉴라이트 전국연합 송년회까지 와서 감사 인사를 했을 정도니, 기대가 컸겠죠.

 

하지만, 떡고물이 그렇게 크지는 않았던 모양입니다. 정권의 최대관심사는 4대강이었고, 건설사나 지주와 달리 뉴라이트 측에서 이권에 직접 개입할 여지가 크지 않았을 테니까요.

 

집권 1년 뒤, 이런 기사(일부 인용)가 나왔습니다.

뉴라이트 "왜 후원않나" 기업명단 공개 (한겨레신문, 2009년 2월 24일) [기사 원문 보기]

보수 성향 시민단체를 대표하는 ‘뉴라이트전국연합’의 핵심 간부가 자기 단체에 후원금을 내지 않은 기업들의 실명을 거론하며 공개 비판해 논란을 빚고 있다.


임헌조 뉴라이트전국연합 사무처장은 24일 오후 서울 태평로 프레스센터에서 열린 ‘이명박 정부 출범 1년 기념 토론회’에서 “에스케이(SK), 포스코, 롯데 등은 (지난 정권 때) 좌파 단체 쪽에 수십억원에서 백억원이 넘는 자금을 지원했고, 한국전력·석유공사·토지공사·가스공사 등 공기업들은 수백만원에서 수천만원을 지원했다”며 “아이러니컬하게도 이들 기업들은 지난해 보수우파 시민단체가 주최한 공동 후원행사에 단 1원도 지원하지 않았다”고 말했다. 


뉴라이트전국연합 등 100여개 보수 성향 시민단체들은 지난해 12월19일 세종문화회관에서 공동 후원행사를 열고, 행사에 앞서 기업체 100여곳에 후원금 입금 계좌를 적어 넣은 초청장을 보내 논란을 빚은 바 있다. 당시 뉴라이트전국연합은 “지금 시대에 어떤 기업이 이것(초청장)을 ‘압력’으로 받아들이겠느냐”고 해명한 바 있다.


이런 상황에서 뉴라이트는 인터넷과 게임을 '수익창출'의 타깃으로 봤을 가능성이 높습니다. 2010년 상반기 우르르 쏟아졌던 논평과 성명들은 분위기 조성을 위한 밑밥입니다. 2010년과 2011년 연초에 진행한, 정치권의 실세들이 출동한 토론회는 '수익모델의 입법화'를 위한 무력시위였을 거고요.

 

이는 단순히 추측만은 아닙니다. 뉴라이트는 게임 말고도 다른 분야에서도 이미 그런 수익모델을 확인했으니까요. 위에서 언급했듯, '사단법인 뉴라이트'는 2008년 10월 '민생경제연구소'로 이름을 바꿨습니다. 개명(改名)에는 나름의 그럴 만한 사정이 읽혀집니다.

 


뉴라이트의 수익모델과 이후의 경과에 대해서는 다음 꼭지에서 이어서 다루겠습니다.

 


Posted by kevino
,

MODBUS is a communication protocol over a variety of  networks such as RS232 and Ethernet which was designed by Modicon.

It has been used widely since last several ten years and FreeMODBUS is a free implementation of this popular MODBUS protocol. 


Recently I wanted to have a tool to share data between some embedded devices over serial connection or ethernet and heard MODBUS can be a starting point for such purpose. So this is the outcome.


This MBServer ( a sample MODBUS TCP server) supports Qt5 but for now no GUI. Later I will put some GUI on it to talk with devices which can support MODBUS. For someone with interests on this can find source tree in the following link.  


https://github.com/seetime/freeMBServer/


How to build:


You need to have Cmake to generate Visual studio C++ project file.


First download source file and enter the root folder


cd <MBServer_root_dir>

mkdir build

cd build

cmake ..


With the project file generated, open it in Visual studio IDE and build and run.

 

For test, I used a MODBUS Diagnostick tool such as Modsak.  



Conclusion.


If someone need to develop application to talk with remote device over serial or Ethernet, MODBUS can be a option for such. This post could be helpful for someone searching or wanting to develop a basic MODBUS server tool. 


Posted by kevino
,

This article is written to show how CMake can be used to build OpenCL related application.

The sample code used here was grabbed from here and its main job is to apply simple Gaussian blur filter on test input image and saving output into a file. For better understanding about how OpenCL code works for Gaussian blur filtering, refer to the above link. I just wanted to build it on my machine to know how OpenCL application work so all credit on the source code should be given to Anteru which can be reached via https://anteru.net/2012/11/05/2022/.



Tested environment


1. Windows 7 with AMD OpenCL SDK

2. Windows 7 with Intel OpenCL SDK

3. MAC OSX 10.7


Below is CMakeLists.txt file used in this project.


CMakeLists.txt


As you can see, it is simple and no description on kernel CL source code because exe file will seek and compile it on run time. Please note that exe file should be located in the same folder with main source code to be able to read test input image and kernel CL code file.


For ones seeking zip file, use this file.

Anteru-opencltutorial.7z




Posted by kevino
,

QEMU can be very useful tool in developing wide range of software from simple application to even linux kernel itself for arm based embedded system. Here is to show how developing and debugging simple application for virtual arm based platform with QEMU is actually easy to people who are lazy so hate to move his/her finger to turn on real board and for poor people who do not have any real hardware.


Note: This post assume Host system is fairly new Ubuntu machine(For my case, its ubuntu 12.04 64bit)


Below is list for bullet items which this post focus.


1. How to build simple c application with a assembly library which can be callable in c function.

2. How to run the executable in Qemu

3. Debugging it with gdb



Phase 0. TOOL Setup


Before delving into programming, we need to check all necessary tools ready. Please refer to below command to install all of them. 


First install linaro image tools.


host$ sudo apt-get install linaro-image-tools


To get qemu to work with, there are two ways to building from source code and using apt-get but here I used apt-get as like below.


host$ sudo add-apt-repository ppa:linaro-maintainers/tools
host$ sudo apt-get update
host$ sudo apt-get install qemu-user-static qemu-system

To be able to compile c and assembly, we need to install crosstool chain for arm.


host$ sudo apt-get install gcc-arm-linux-gnueabi


Phase 1. Creating a simple application made up of c and assembly combination 


I wrote some articles in this site how to create CMake project so here I would like to show only source code without detailed explanation about it and why it is needed.


There are 4 files required in the project. 

1. main.c                                          # main c source code including main()

2. square.s                                       # assembly file containing functions callable in main() 

3. CMakeLists.txt                               # main cmake project file

4. toolchain-for-qemuarm.cmake          # cmake module used for cross compilation for arm target system


So just create below all 4 files in a $(EXAMPLE) directory.


main.c


square.s


CMakeLists.txt



toolchain-for-qemuarm.cmake


Note: Here I used gcc toolchain from Freescale site but you may use other popular toolchain also.


One you have those file, it is easy to build binary which will be run on qemu.


host$ mkdir build; cd build

host$ cmake -DCMAKE_TOOLCHAIN_FILE=../toolchain-for-qemuarm.cmake ..


Now you can check arm executable created correctly

host$ arm-linux-gnueabi-readelf ./program -a | more

ELF Header: Magic: 7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 Class: ELF32 Data: 2's complement, little endian Version: 1 (current) OS/ABI: UNIX - System V ABI Version: 0 Type: EXEC (Executable file) Machine: ARM Version: 0x1 Entry point address: 0x8538 Start of program headers: 52 (bytes into file) Start of section headers: 3592 (bytes into file) Flags: 0x5000002, has entry point, Version5 EABI

For source codes, download this. 

cassemtest.tar.gz



Phase 2. Test with QEmu

The built program depends on external libary called ld-linux.so.3 and this is arm side shared libary. So qemu need to know where to find correct shared library for this arm friendly executable. In below, I informed /usr/arm-linux-gnueabi which was created when I installed cross-toolchain mentioned in phase 0. ( FYI, when I used one included in freescale toolchain, system got corrupted for uncertain reason)

host$ qemu-arm-static -L /usr/arm-linux-gnueabi ./program

sum(1, 100) = 101 Hello, ARM World!

The printed message above shows that program ran as intended.


Phase 3. Debugging with Qemu + gdb

With gdb, user can debug application in source level. I already gave option "SET(CMAKE_BUILD_TYPE debug)" to include debug symbol in the executable by including one line in CMakeList.txt so the executable should contain symbol table in itself.

host$ qemu-arm-static -g 1234 -L /usr/arm-linux-gnueabi ./program


With -g 1234 option in the above command, qemu is waiting for gdb connection via port 1234 of localhost.

host$ sudo apt-get install gdb-multiarch

host$ gdb-multiarch

...

(gdb) file program

Reading symbols from /home/<user>/work/qemu/linaro/examples/cassemtest/build/program...done.

(gdb) target remote localhost:1234

Remote debugging using localhost:1234 [New Remote target] warning: Unable to find dynamic linker breakpoint function. GDB will be unable to debug shared library initializers and track explicitly loaded dynamic code. [Switching to Remote target] 0xf67dfc40 in ?? ()

(gdb) b main

Breakpoint 1 at 0x85f0: file /home/<user>/work/qemu/linaro/examples/cassemtest/main.c, line 8.

(gdb) c

Continuing. warning: Could not load shared library symbols for 2 libraries, e.g. /lib/libc.so.6. Use the "info sharedlibrary" command to see the complete listing. Do you need "set solib-search-path" or "set sysroot"? Breakpoint 1, main () at /home/<user>/work/qemu/linaro/examples/cassemtest/main.c:8 8 int a=1, b =100;


Conclusion


So far showed how simple application debugging with qemu can be done and hope this post will help app development for embedded system under qemu sandbox which will throw away any worry to break system due to SW bug.

   



Posted by kevino
,

On Mac, it was hard to find out how to capture web camera input to me and this is to share what i found in dealing with gstreamer to capture live webcam input on my Macbook running OS X 10.7.5.



To use GStreamer, the necessary package should be installed and the following link shows how to install it.


http://docs.gstreamer.com/display/GstSDK/Installing+on+Mac+OS+X


Before running gst-launch, few more steps are needed because the path containing the gst binaries may not be included in PATH env variable. I recommend that few symbolic links to gst binaries be created in /usr/bin/ path.

For example, at command line, run below command to create those files.


$ sudo ln -s /Library/Frameworks/GStreamer.framework/Versions/Current/bin/gst-launch-0.10 /usr/bin/gst-launch

$ sudo ln -s /Library/Frameworks/GStreamer.framework/Versions/Current/bin/gst-inspect-0.10 /usr/bin/gst-inspect


Now we can test whether gstreamer is working properly.


Example 1: Testing with pre-made video source in gstreamer and displaying it in a window.


$ gst-launch videotestsrc ! osxvideosink


Example 2: Displaying webcam input in a window


$ gst-launch autovideosrc ! osxvideosink



Example 3: Grabbing one frame from webcam and saving it as jpeg


$ gst-launch -v -e autovideosrc num-buffers=1 ! jpegenc ! filesink location=capture1.jpeg


So far, all examples above are shown as command line use case.

Before completing this post, here come a sample c source code with cmake script which will ease developing user application for one's own use. The source file is taken from gstreamer tutorial page at http://docs.gstreamer.com/pages/viewpage.action?pageId=327735 so if details about it is required, then you can check it also in the link.


This project source was tested with my macbook.



gst-example-prj.tar.7z


 

Posted by kevino
,

이번 글은 리눅스 커널 3.6버전 부터 공식적으로 지원하는 device tree 에 관련된 몇가지 유용한 정보를 담고 있다.


우선 device tree에 대한 것을 최대한 간단히 설명하면 하드웨어를 기술하는 데이터 구조라고 www.devicetree.org에 나와 있는데 좀더 자세한 내용은 그쪽 사이트를 참조하도록 하고 여기에서는 개인적으로 이해하고 있는 내용을 그때 그때 추가해놓았다. 사실 devicetree는 방대한 개념이어서 이것을 모두 설명하기는 힘드니 필요할때마다 여기에 추가해서 갱신하고자 한다.


첫째, device tree는 범용적으로 하드웨어를 기술할 수 있는 데이터 구조만을 정의해놓아서 수만 수천가지의 장치에 대해 모두 동일하게 작성한다는 것이 불가능하기에 그때 그때 상황에 맞추어서 작가가 나름의 구조를 고안해서 작성하게 된다. 그래서 플랫폼마다 독자적인 개성을 가진 구조를 가지게 되고 그것을 접해보지 못한 작가가 만들어 놓은 device tree script(이하 dts )를 그대로 이용하려는 경우 적용이 불가능하게 되는 경우도 생겨서 이런 것들을 지원하려다 보면 부득이하게 새로운 구조라든지 device tree compiler(이하 dtc)에서 지원하는 새로운 키워드라든지 문구를 새로 만들기도 한다. 


beaglebone black(이하 BBB)에서도 마찬가지로 인터넷에서 떠돌아다니는 dts를 받아다 기본적으로 설치되어 있는 dtc로 컴파일하려하면 컴파일 오류를 만들어 내는 경우가 있을 수 있다. 이런 경우에는 기본설치된 dtc가 해당 dts에서 지원하는 문법을 지원하지 못하기에 발생하는 문제인데 이런 경우는 새로운 dtc 소스를 받아다가 몇몇 패치를 적용해서 만들어진 dtc를 이용하면 문제가 해결된다. 아래 방법을 보였는데 필요한 경우 원소스를 밝히니 참고하기 바란다.



우선 BBB에서 동작하는 dts가 필요한데 여기서는 다음링크에 있는 dts를 참고하기로 한다.


http://hipstercircuits.com/capture-input-events-via-gpio-on-beaglebone-black/


/dts-v1/;
/plugin/;

/ {
    compatible = "ti,beaglebone", "ti,beaglebone-black";

    /* identification */
    part-number = "BB-GPIO-KEYS";
    version = "00A0";

    fragment@0 {
        target = <&am33xx_pinmux>;
        __overlay__ {
            end_stop_pins: pinmux_end_stop_pins{
                pinctrl-single,pins = <
                    0x090 0x37 // P8_7  = End stop X1  = GPIO2_2
                    0x070 0x37 // P9_11 = End stop Y1  = GPIO0_30
                    0x074 0x37 // P9_13 = End stop Z1  = GPIO0_31
                    0x158 0x37 // P9_18 = End stop Z2  = GPIO0_4
                    0x1AC 0x37 // P9_25 = End stop Y2  = GPIO3_21
                    0x180 0x37 // P9_26 = End stop X2  = GPIO0_14
                >;
            };
        };
    };

    fragment@1 {
        target = <&ocp>;
        __overlay__ {            
            #address-cells = <1>;
            #size-cells = <1>;                            

            gpio_keys {
                compatible = "gpio-keys";
                pinctrl-names = "default";
                pinctrl-0 = <&end_stop_pins>;
                #address-cells = <1>;
                #size-cells = <0>;

                switch_x1 {
                    label = "End-stop-X1";
                    debounce_interval = <50>;
                    linux,code = <1>;
                    gpios = <&gpio3 2 0x5>;
                    gpio-key,wakeup;
                };                
                switch_x2 {
                    label = "End-stop-X2";
                    debounce_interval = <50>;
                    linux,code = <2>;
                    gpios = <&gpio1 14 0x5>;
                    gpio-key,wakeup;
                };
                switch_y1 {
                    label = "End-stop-Y1";
                    debounce_interval = <50>;
                    linux,code = <3>;
                    gpios = <&gpio1 30 0x5>;
                    gpio-key,wakeup;
                };                
                switch_y2 {
                    label = "End-stop-Y2";
                    debounce_interval = <50>;
                    linux,code = <4>;
                    gpios = <&gpio4 21 0x5>;
                    gpio-key,wakeup;
                };                
                switch_z1 {
                    label = "End-stop-Z1";
                    debounce_interval = <50>;
                    linux,code = <5>;
                    gpios = <&gpio1 31 0x5>;
                    gpio-key,wakeup;
                };                
                switch_z2 {
                    label = "End-stop-Z2";
                    debounce_interval = <50>;
                    linux,code = <6>;
                    gpios = <&gpio1 4 0x5>;
                    gpio-key,wakeup;
                };                
            };
        };
    };
};


위의 dts를 보면 두번째줄 /plugin/문구가 있는데 이것을 기본설치된 dtc로 컴파일하면 오류가 나면서 실패하게 된다. 이를 해결하기 위해서는 다음과 같이 패치된 dtc를 이용해야 한다.(출처:http://derekmolloy.ie/beaglebone/beaglebone-gpio-programming-on-arm-embedded-linux/)


$ git clone git://www.jdl.com/software/dtc.git
$ cd dtc
$ git checkout 27cdc1b16f86f970c3c049795d4e71ad531cca3d
$ wget https://github.com/beagleboard/meta-beagleboard/raw/master/common-bsp/recipes-kernel/dtc/dtc/0001-dtc-Dynamic-symbols-fixup-support.patch
$ patch -p1 < 0001-dtc-Dynamic-symbols-fixup-support.patch
$ make

위의 결과로 만들어진 dtc로 컴파일 하면 위의 dts가 정상적으로 컴파일될수 있다. 여기서 만들어진 dtbo를 리눅스 커널에 적재하려면 위의 언급된 사이트에 기술된 내용대로 하면 된다. 물론 위의 dts는 기본 BBB와 별도의 키입력용으로 만들어진 확장 보드를 동작시키기 위한 파일로 기본 BBB만 가지고는 실행할수 있는 있되 기능동작확인은 되지 않는 점을 밝혀둔다.



Posted by kevino
,

In Qt5, writing Cmake project for building Qt5 opengl app with optional shader seems to be little complicated comparing to previous Qt version(i.e Qt v5.0.2) and took time to figure out how to configure all necessary things. After many hours on this issue, I found one configuration to make possible to building Qt5 opengl app with Cmake and this post is to describe what I did with helps from various internet sources which will be listed below accordingly.


First thing to tell is preconditions before writing sources.


Precondition


1. OS: MS Windows 7

2. Qt version and toolkit: prebuilt Qt 5.1.0 msvc2010_opengl

3. Visual studio 2010

4. Windows SDK should be installed properly. : ie) c:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Lib\

5. CMake 2.8.11


If your system is different with the above precondition, CMakeLists.txt should be changed properly. Refer to the example CMakeLists.txt in this post. You can get a hint about how to edit.


Now it is time to introduce source code for building a simple Qt5 opengl shader app. 


Because main purpose to write up this post is to show how to create CMakeLists.txt to compile existing source codes, just copy and create all 3 files referring to this link:  http://qt-project.org/doc/qt-5.0/qtgui/openglwindow.html


And last file CMakeLists.txt.


CMakeLists.txt


Now we have all files to build up Qt5 shader app showing rotating triangle and time to run cmake to create visual studio project file for this app. If you are lucky to complete compilation and launching this app, then you will see a rotating triangle with help of Opengl shader in a window.



One last thing I want to note is that CMAKE_PREFIX_PATH in CMakeLists.txt MUST include proper paths in order to succeed compilation. As you can see in the above example, there are two paths are included.

First path is the location to find all neccessary Qt5 tools and must be same with the path in below picture. Below picture shows Qt Options dialog box in Visual studio 2010 through "Qt5" -> "Qt5 options" which is enabled if you installed visual studio addin for Qt5





Second path in CMAKE_PREFIX_PATH is required to compile with OpenGL library: glu32.lib and opengl32.lib. These files are included in Windows SDK so make sure this before starting compilation and also don't forget to include TARGET_LINK_LIBRARIES in the above example. Otherwise, opengl libraries will not be included in the project file generated by cmake.


Added 2013-09-23.


You may notice below error message on compilation.

Error message=> module machine type 'x64' conflicts with target machine type 'X86'


This error message happens when you create visual studio project file for 32 bit binary and try to compile against 64 bit library. The default behavior of running "cmake .." on 64 bit machine usually generates 32 bit project instead of 64 bit project file so this may cause compilation error.


Solution. Try to generate 64 bit visual studio project file using below command and compile binary with it.

cmake -G "Visual Studio 11 Win64" ..


Below is source code for your convenience.


qt5shader.7z


Posted by kevino
,