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
#include <iostream>
#include <sstream>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/videoio.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/video.hpp>
 
using namespace cv;
using namespace std;
 
int main(int argc, char* argv[])
{
    //create Background Subtractor objects
    Ptr<BackgroundSubtractor> pBackSub;
    pBackSub = createBackgroundSubtractorKNN();
 
    VideoCapture capture("test.mp4");
    if (!capture.isOpened()) {
        //error in opening the video input
        cerr << "Unable to open video " << endl;
        return 0;
    }
    Mat frame, fgMask;
    while (true) {
        capture >> frame;
        if (frame.empty())
            break;
        //update the background model
        pBackSub->apply(frame, fgMask);
 
        //get the frame number and write it on the current frame
        rectangle(frame, cv::Point(102), cv::Point(10020),
            cv::Scalar(255255255), -1);
        stringstream ss;
        ss << capture.get(CAP_PROP_POS_FRAMES);
        string frameNumberString = ss.str();
        putText(frame, frameNumberString.c_str(), cv::Point(1515),
            FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(000));
 
        //show the current frame and the fg masks
        imshow("Frame", frame);
        imshow("FG Mask", fgMask);
 
        //get the input from the keyboard
        int keyboard = waitKey(30);
        if (keyboard == 'q' || keyboard == 27)
            break;
    }
    return 0;
}
cs

필요한 프로그램 다운로드

  - OpenCV 다운받기 (https://opencv.org/releases/)

  - OpenCV extra 모듈 다운로드 (https://github.com/opencv/opencv_contrib/releases)

  - Cmake 다운받기 (https://cmake.org/download/)

  - Cuda toolkit 다운받기 (https://developer.nvidia.com/accelerated-computing-toolkit)

 

Cuda 설치

  - 다음만 눌러서 기본경로에 설치

  - 환경변수에 cuda 경로 추가 Ex ) C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\bin

 

CMake 경로설정

  - 아래 그림과 같이 다운받은 OpenCV의 경로(적색 표시, CMakeLists.txt. 파일이 존재하는 경로)Visual Studio 프로젝트를 생성할 폴더(청색 표시, 새 폴더를 만들면 됨)를 설정하고 Configure.

  - 설정이 완료되면 본인의 Visual Studio 버전에 맞게 설정 후 플랫폼을 x64로 바꿔주고 Finish.

 

 

기타 설정 추가

  - 아래의 그림과 같이 CUDA, opencv_world에 체크

  - extra_module의 주소를 추가 후 다시 Configure.

 

 

프로젝트 빌드

  - ALL_BUILD -> INSTALL 순서로 빌드. (INSTALL 다시 빌드 누르면 ALL_BUILD때 한거 다시함. 오래걸림.)

  빌드가 끝나면 프로젝트 경로에 install 폴더가 생성되며, 그안에 inclued 폴더 및 dll, lib 파일이 모두 있음. .

 

1
2
std::string string = "string";
LPCSTR lpcString = lpcString.c_str();
cs


※ 프로젝트 속성 - 문자집합 -> 멀티바이트 문자 집합 사용



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
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <cmath>
#include <vector>
#include <queue>
#include <limits>
#include <string>
 
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/features2d.hpp>
#include <opencv2/cudafeatures2d.hpp>
#include <opencv2/core/cuda.hpp>
#include <opencv2/cudafilters.hpp>
#include <opencv2/cudaimgproc.hpp>
#include <opencv2/cudawarping.hpp>
 
using namespace cv;
using namespace std;
 
int main(int argc, char** argv)
{
 
    while (1)
    {
 
        Mat frameMat01 = imread("frame01.jpg");
        Mat frameMat02 = imread("frame02.jpg");
        
        clock_t beginend;
        begin = clock();
 
        cuda::GpuMat cuFrameMat01, cuFrameMat02;
        cuFrameMat01.upload(frameMat01);
        cuFrameMat02.upload(frameMat02);
        
        cuda::cvtColor(cuFrameMat01, cuFrameMat01, CV_BGR2GRAY);
        cuda::cvtColor(cuFrameMat02, cuFrameMat02, CV_BGR2GRAY);
 
        Ptr<cuda::ORB> orb = cuda::ORB::create(10001.2f, 83102, ORB::HARRIS_SCORE, 3120false);
 
        cuda::GpuMat cuMask01(frameMat01.rows, frameMat01.cols, CV_8UC1, cv::Scalar::all(1)); //330,215
        cuda::GpuMat cuMask02(frameMat02.rows, frameMat02.cols, CV_8UC1, cv::Scalar::all(1)); //315,235
 
        cuda::GpuMat cuKeyPoints01, cuKeyPoints02;
        cuda::GpuMat cuDescriptors01, cuDescriptors02;
 
        orb->detectAndComputeAsync(cuFrameMat01, cuMask01, cuKeyPoints01, cuDescriptors01);
        orb->detectAndComputeAsync(cuFrameMat02, cuMask02, cuKeyPoints02, cuDescriptors02); 
 
        Ptr<cuda::DescriptorMatcher> matcher = cv::cuda::DescriptorMatcher::createBFMatcher(cv::NORM_HAMMING);
        cuda::GpuMat gpuMatchesMat;
        matcher->knnMatchAsync(cuDescriptors01, cuDescriptors02, gpuMatchesMat, 2, noArray());
        vector<vector<DMatch>> knnMatchesVec;
        
 
        waitKey();
    }
 
 
    waitKey(0);
    return 0;
}
cs


◎ 필요한 프로그램 다운로드

opencv 다운받기 (https://opencv.org/releases.html)

Cmake 다운받기 (https://cmake.org/download/)

Cuda toolkit 다운받기 (https://developer.nvidia.com/accelerated-computing-toolkit)


◎ Cuda 설치

다음만 눌러서 기본경로에 설치

환경변수에 cuda 경로 추가 Ex ) C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\bin


◎ Cmake로 프로젝트 생성

Configure 클릭 후 자신의 비주얼 스튜디오 버전에 맞게 선택 후 Finish


cuda 관련 설정 확인


opencv_world 체크 (제일 중요, 안하면 프로젝트 만들때 피똥쌈)


체크 다했으면 다시 Configure 클릭

Configure 가 정상적으로 완료되었다면 Generate 클릭


◎ Cmake로 프로젝트 생성opencv 소스 빌드

mybuild2 경로안에 opencv 솔루션 파일 열기 (관리자 권한으로 열 것)

프로젝트 중 INSTALL 우클릭 - 빌드






먼저 c++에서는 decode jpeg를 쓸 수 없기 때문에 해당 기능을 이용하는 노드는 모두 잘라내 주어야 한다.


다행히 텐서플로 폴더 안에 이러한 노드와 학습 노드를 함께 잘라내 주는 strip 파일이 있다.


감사하게 이용한다.


1
2
3
4
5
6
7
bazel build tensorflow/python/tools:strip_unused && \
bazel-bin/tensorflow/python/tools/strip_unused \
  --input_graph=../trainOut/cars_graph.pb \
  --output_graph=../trainOut/cars_stripped_graph.pb \
  --input_node_names=Mul \
  --output_node_names=final_result \
  --input_binary=true
cs


1. Tensorflow_cc 설치 (Ubuntu 16.0.4) (참조 : https://github.com/FloopCZ/tensorflow_cc)


1) 필수 패키지 설치

1
2
3
sudo apt-get install build-essential curl git cmake unzip autoconf autogen libtool mlocate zlib1g-dev \
                     g++-5 python python3-numpy python3-dev python3-pip python3-wheel wget
sudo updatedb
cs


2) Bazel 설치 (*선택사항, shared library 빌드시 필요)

1
2
3
4
5
6
7
8
9
10
11
sudo apt-get install pkg-config zip g++ zlib1g-dev unzip python
 
# OS에 맞는 bazel 설치 스크립트 다운로드
# https://github.com/bazelbuild/bazel/releases
 
# bazel 설치 스크립트 실행
chmod +x bazel-<version>-installer-linux-x86_64.sh
./bazel-<version>-installer-linux-x86_64.sh --user
 
# 경로 추가
export PATH="$PATH:$HOME/bin"
cs


3) 라이브러리 빌드

- Tensorflow Lite 등의 모든 기능을 이용하려면 shared library 설치 필요.

1
2
3
4
5
6
7
cd tensorflow_cc
mkdir build && cd build
# for static library only:
cmake ..
# for shared library only (requires Bazel):
# cmake -DTENSORFLOW_STATIC=OFF -DTENSORFLOW_SHARED=ON ..
make && sudo make install
cs




2. opencv 설치


1) 필수 패키지 설치

1
2
3
4
5
6
7
8
9
10
11
12
sudo apt-get update
sudo apt-get upgrade
 
sudo apt-get install build-essential cmake
sudo apt-get install pkg-config
sudo apt-get install libjpeg-dev libtiff5-dev libjasper-dev libpng12-dev
sudo apt-get install libavcodec-dev libavformat-dev libswscale-dev libxvidcore-dev libx264-dev libxine2-dev
sudo apt-get install libv4l-dev v4l-utils
sudo apt-get install libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev 
sudo apt-get install libqt4-dev 
sudo apt-get install mesa-utils libgl1-mesa-dri libqt4-opengl-dev
sudo apt-get install libatlas-base-dev gfortran libeigen3-dev
cs


2) opencv 다운로드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 소스 임시 저장 경로
mkdir opencv && cd opencv
 
# opencv 라이브러리
wget -O opencv.zip https://github.com/opencv/opencv/archive/3.4.0.zip
unzip opencv.zip
 
# opencv extended 라이브러리 (선택)
wget -O opencv_contrib.zip https://github.com/opencv/opencv_contrib/archive/3.4.0.zip
unzip opencv_contrib.zip
 
# opencv 폴더 내부로 이동 및 빌드 디렉토리 생성
cd opencv
mkdir build && cd build
cs


3) cmake 설정

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
cmake -D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local \
-D WITH_TBB=OFF \
-D WITH_IPP=OFF \
-D WITH_1394=OFF \
-D BUILD_WITH_DEBUG_INFO=OFF \
-D BUILD_DOCS=OFF \
-D INSTALL_C_EXAMPLES=ON \
-D INSTALL_PYTHON_EXAMPLES=ON \
-D BUILD_EXAMPLES=OFF \
-D BUILD_TESTS=OFF \
-D BUILD_PERF_TESTS=OFF \
-D WITH_QT=ON \
-D WITH_OPENGL=ON \
-D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib-3.4.0/modules \
-D WITH_V4L=ON  \
-D WITH_FFMPEG=ON \
-D WITH_XINE=ON \
-D BUILD_NEW_PYTHON_SUPPORT=ON \
../
cs


4) 빌드 및 설치

1
2
3
4
5
6
make
sudo make install
 
# 경로 설정
sudo sh -'echo '/usr/local/lib' > /etc/ld.so.conf.d/opencv.conf'
sudo ldconfig
cs





3. cmake 파일 생성 및 빌드


1) CMakeLists.txt 작성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
cmake_minimum_required(VERSION 3.3 FATAL_ERROR)
add_executable(example example.cpp)
 
# try the shared tensorflow library first
find_package(TensorflowCC COMPONENTS Shared)
if(TensorflowCC_Shared_FOUND)
  target_link_libraries(example TensorflowCC::Shared)
# fallback to the static library
else()
  find_package(TensorflowCC REQUIRED COMPONENTS Static)
  target_link_libraries(example TensorflowCC::Static)
endif()
 
# link cuda if it is available
find_package(CUDA)
if(CUDA_FOUND)
  target_link_libraries(example ${CUDA_LIBRARIES})
endif()
 
find_package( OpenCV REQUIRED )
target_link_libraries( example ${OpenCV_LIBS} )
cs


2) example.cpp 작성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include "opencv2/core/utility.hpp"
#include <opencv2/imgproc.hpp>
#include <opencv2/features2d.hpp>
#include <opencv2/highgui.hpp>
 
#include <tensorflow/core/platform/env.h>
#include <tensorflow/core/public/session.h>
#include <iostream>
using namespace std;
using namespace tensorflow;
 
int main()
{
    Session* session;
    Status status = NewSession(SessionOptions(), &session);
    if (!status.ok()) {
        cout << status.ToString() << "\n";
        return 1;
    }
    cout << "Session successfully created.\n";
}
cs


3) 빌드 디렉토리 생성 및 빌드

1
2
3
4
mkdir build && cd build
cmake ..
make
./example
cs


Manifest.xml 파일에서 반투명을 적용하고 싶은 액티비티를 아래와 같이 수정

1
2
<activity android:name=".marryPopup"
            android:theme="@style/Theme.AppCompat.Translucent"></activity>
cs

.java 파일 수정

1
2
3
4
5
6
7
8
9
10
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
        
   WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
   layoutParams.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND;
   layoutParams.dimAmount = 0.6f; // 투명도 0 ~ 1
   getWindow().setAttributes(layoutParams);
 
   setContentView(R.layout.activity_marry_popup);
}
cs


잘 쓰던 피파온라인 정보 앱들이 개발자분들의 개인 사정으로 업데이트가 끊기면서


에라.. 없으면 내가 만들어 써야겠다 다짐하고 잠깐 작업을 했더니 새로운 앱이 나와 처박아버렸다.


혹시 필요하신분은 가져다 쓰시길..



위 캡쳐는 실행 화면.


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
public class MainActivity extends AppCompatActivity {
 
    private String htmlPageUrl = "http://fifaonline3.nexon.com/datacenter/player/list.aspx?strpynm=";
    private String search;
    private TextView textviewHtmlDocument;
    private String htmlContentInStringFormat;
    private String searchResult01 = "", searchResult02 = "", searchResult03 = "", searchResult04 = "", searchResult05 = "", searchResult06 = "", searchResult07 = "", searchResult08 = "", searchResult09 = "", searchResult10 = "", searchResult11 = "";
    final ArrayList<String> items = new ArrayList<String>() ;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, items);
        final ListView listview = (ListView) findViewById(R.id.listView) ;
        listview.setAdapter(adapter) ;
 
        textviewHtmlDocument = (TextView)findViewById(R.id.textView);
        textviewHtmlDocument.setMovementMethod(new ScrollingMovementMethod());
 
        Button htmlTitleButton = (Button)findViewById(R.id.button);
        final EditText editText=(EditText)findViewById(R.id.editText);
        htmlTitleButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String playername = editText.getText().toString();
                search = htmlPageUrl + playername;
                JsoupAsyncTask jsoupAsyncTask = new JsoupAsyncTask();
                jsoupAsyncTask.execute();
                try {Thread.sleep(3000);} catch (InterruptedException e) { }
                adapter.notifyDataSetChanged();
            }
        });
    }
 
    private class JsoupAsyncTask extends AsyncTask<Void, Void, Void> {
 
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
 
        @Override
        protected Void doInBackground(Void... params) {
            try {
                Document doc = Jsoup.connect(search).get();
                Elements links = doc.select(".name");
 
                for (Element link : links) {
                    htmlContentInStringFormat += (link.attr("abs:href"+ "("+link.text().trim() + ")\n");
 
                    Elements linkelements = link.getElementsByTag("td");
                    int elesize = linkelements.size();
 
                }
 
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
 
        @Override
        protected void onPostExecute(Void result) {
            textviewHtmlDocument.setText("검색결과");
            items.clear();
            textviewHtmlDocument.setText(htmlContentInStringFormat);
        }
    }
 
}
cs


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
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.vrlab.fifa3simulation.MainActivity">
 
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Search"
        android:id="@+id/button"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true" />
 
    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:text=""
        android:ems="10"
        android:layout_alignBottom="@+id/button"
        android:layout_alignParentStart="true"
        android:id="@+id/editText"
        android:layout_toStartOf="@+id/button" />
 
    <TextView
        android:text="TextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText"
        android:layout_centerHorizontal="true"
        android:id="@+id/textView" />
 
    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/listView"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/textView" />
 
</RelativeLayout>
 
cs


개발환경

○ JSP, CSS, mysql

○ 소스코드 : https://github.com/IkHyunJo/tennis



구현결과

01234567891011

01234567891011121314

01234



'Computer > Coding' 카테고리의 다른 글

[Android] 반투명 액티비티  (0) 2017.05.13
[Android] 피파온라인 선수 검색 예제  (0) 2017.04.12
[Processing] particle/interaction project  (0) 2017.03.30
[opencv] Simple lane detection  (0) 2017.03.30
[opencv] Line matching  (0) 2017.03.30