jpg 파일만 가져왔음

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <string>
#include <vector>
#include <io.h>
 
using namespace std;
 
int main()
{
    string path = "backImg\\*.jpg";
 
    struct _finddata_t fd;
    intptr_t handle;
    if ((handle = _findfirst(path.c_str(), &fd)) == -1L)
        cout << "No file in directory!" << endl;
    do
    {
        cout << fd.name << endl;
    } while (_findnext(handle, &fd) == 0);
    _findclose(handle);
 
    return 0;
}
cs

◎ 검출 (Detection)
- 영상에서 대상을 찾는 것

 

 

◎ 인식 (Recognition)
- 대상이 무엇인지 식별하는 것


◎ 추적 (Tracking)
- 연속된 영상에서 대상의 위치변화를 추적하는 것

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

MQTT 프로토콜 정리  (0) 2022.01.04
[Vehicle detection] CCTV 자동차 검출  (0) 2018.09.04
[Stereo Vision] 스테레오 매칭  (0) 2017.05.02
[Line feature descriptor] LBD descriptor  (0) 2017.03.29
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


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

 배경 제거 (Background subtraction)

○ 자동차가 없는 도로의 영상을 기반으로 도로 위의 움직이는 객체를 검출

○ 검출된 객체를 인지하는 과정이 없음 -> 자동차가 아닌 물체도 구분해낼수 없음

○ 배경의 변화에 매우 민감 (시간에 따른 밝기 변화, 카메라의 흔들림, 순간적인 밝기 변화 등)

○ 주로 배경 모델의 학습을 최근 n프레임 누적을 통해 생성하는데 해당 방법을 이용한 경우에는 장시간 움직이지 않는 차량을 검출하는데 문제가 있음.



 특징 기반 탐색 (Feature based detection)

○ 생김새 정보인 feature를 이용한 차량 검출 방법

○ Hog feature가 차량 검출에 널리 사용됨

- HOG는 대상 영역을 일정 크기의 셀로 분할하고, 각 셀마다 edge 픽셀(gradient magnitude가 일정 값 이상인 픽셀)들의 방향에 대한 히스토그램을 구한 후 이들 히스토그램 bin 값들을 일렬로 연결한 벡터.

- 외곽선이 뚜렷하고 내부 패턴이 단순한 객체의 검출에 용이한 특징이며 템플릿 매칭이 주로 사용됨.


○ Sliding window를 이용한 탐색

- 일정 크기의 윈도우를 이미지 전체에 옮겨가며 hog를 이용하여 미리 학습된 분류기를 통한 차량 검출

- 단점 : 느리다!

○ 관심 영역 설정을 통한 탐색

- 배경학습 등을 통해 관심영역을 설정하고 해당 영역에 대해서만 분류기를 통한 분류 작업 진행

- 단점 : 관심영역 지정 실패 = 검출 실패!




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