공학왕이될거야

face tracking 아두이노 코드

전공/Opencv
#include <Servo.h>
Servo myservo1;
Servo myservo2;
int pos1 =90;
int pos2 =90;
void setup(){
Serial.begin(9600);
myservo1.attach(9);
myservo2.attach(10);
}
void loop(){
if(Serial.available());
{
int a=(int)Serial.read();
if(a=='1')
{
pos1 = pos1 - 1;
pos2 = pos2 + 1;
myservo1.write(pos1);
myservo2.write(pos2);
Serial.println(a);
delay(10);
}
else if(a=='4')
{
pos1 = pos1;
pos2 = pos2 + 1;
myservo1.write(pos1);
myservo2.write(pos2);
Serial.println(a);
delay(10);
}
else if(a=='7')
{
pos1 = pos1 + 1;
pos2 = pos2 + 1;
myservo1.write(pos1);
myservo2.write(pos2);
Serial.println(a);
delay(10);
}
else if(a=='2')
{
pos1 = pos1 - 1;
pos2 = pos2;
myservo1.write(pos1);
myservo2.write(pos2);
Serial.println(a);
delay(10);
}
else if(a=='5')
{
pos1 = pos1;
pos2 = pos2;
myservo1.write(pos1);
myservo2.write(pos2);
Serial.println(a);
delay(10);
}
else if(a=='8')
{
pos1 = pos1 + 1;
pos2 = pos2;
myservo1.write(pos1);
myservo2.write(pos2);
Serial.println(a);
delay(10);
}
else if(a=='3')
{
pos1 = pos1 - 1 ;
pos2 = pos2 - 0.8;
myservo1.write(pos1);
myservo2.write(pos2);
Serial.println(a);
delay(10);
}
else if(a=='6')
{
pos1 = pos1;
pos2 = pos2 - 0.8;
myservo1.write(pos1);
myservo2.write(pos2);
Serial.println(a);
delay(10);
}
else if(a=='9')
{
pos1 = pos1 + 1;
pos2 = pos2 - 0.8;
myservo1.write(pos1);
myservo2.write(pos2);
Serial.println(a);
delay(10);
}
}
}

'전공 > Opencv' 카테고리의 다른 글

face tracking C 코드  (3) 2019.10.31
Face-tracking Robot 졸업작품  (18) 2018.01.29
저장된 사진 띄우기  (0) 2017.07.24
ubuntu 16.04 opencv 3.2.0 설치  (2) 2017.07.21
노트북 카메라 연동 얼굴 인식  (0) 2017.07.14

face tracking C 코드

전공/Opencv
#include "C:/Users/user/Desktop/opencv/build/include/opencv2/objdetect.hpp"
#include "C:/Users/user/Desktop/opencv/build/include/opencv2/videoio.hpp"
#include "C:/Users/user/Desktop/opencv/build/include/opencv2/highgui.hpp"
#include "C:/Users/user/Desktop/opencv/build/include/opencv2/imgproc.hpp"
#include "C:/Users/user/Desktop/opencv/build/include/opencv2/video/video.hpp"
#include "C:/Users/user/Desktop/opencv/build/include/opencv2/core/core.hpp"
#include "C:/Users/user/Desktop/opencv/build/include/opencv2/highgui/highgui.hpp"
#include <vector>
#include <iostream>
#include <stdio.h>
#include <string>
#include "serialcomm.h"
#include "Windows.h"
using namespace std;
using namespace cv;
/* Function Headers */
//void detectAndDisplay(Mat frame);
/* Global variables */
String window_name = "Capture - Face detection";
CSerialComm serialComm; //SerialComm 객체 생성
char detectStatus = '0';
char temp = '0';
int i;
/* @function main */
int main(int argc, char *argv[])
{
 cv::namedWindow("video", 1);
 cv::VideoCapture cap(0);
 if (!cap.isOpened())
 {
  std::cerr << "Could not open camera" << std::endl;
  return 0;
 }
 char buffer;
 if (!serialComm.connect("COM3")) //COM25번의 포트를 오픈한다. 실패할 경우 -1을 반환한다.
 {
  cout << "connect faliled" << endl;
  return -1;
 }
 else
  cout << "connect successed" << endl;
 const char* windowName = "Fingertip detection";
 while (true)
 {
  bool frame_valid = true;
  cv::Mat frame;
  try {
   cap >> frame;
  }
  catch (cv::Exception& e) {
   std::cerr << "Exception occurred. Ignoring frame... " << e.err << std::endl; frame_valid = false;
  }
  if (frame_valid) {
   try { // convert captured frame to gray scale & equalize
    //컬러 공간 변환 BGR->YCrCb
    //cv::Mat hsv;
    cv::Mat YCrCb;
    cvtColor(frame, YCrCb, CV_BGR2YCrCb);
    //각 채널별로 분리
    std::vector<cv::Mat> planes;
    cv::split(YCrCb, planes);
    cv::Mat mask = (128 < planes[1]) & (planes[1] < 170) & (73 < planes[2]) & (planes[2] < 158);
    erode(mask, mask, cv::Mat(3, 3, CV_8U, cv::Scalar(1)), cv::Point(-1, -1), 2);
    double radius;
    cv::Mat dst;
    distanceTransform(mask, dst, CV_DIST_L2, 5);
    //거리 변환 행렬에서 값(거리)이 가장 큰 픽셀의 좌표와, 값을 얻어온다.
    int maxIdx[2];
    minMaxIdx(dst, NULL, &radius, NULL, maxIdx, mask);
    cv::Point center = cv::Point(maxIdx[1], maxIdx[0]);
    cout << "중심점 좌표:" << center << ", 반지름:" << radius << endl;
    //손바닥 중심점 그리기
    cv::circle(frame, center, 2, cv::Scalar(0, 255, 0), -1);
    //손바닥 영역 그리기
    //cv::circle(frame, center, (int)(radius + 0.5), cv::Scalar(255, 0, 0), 2);
    //cv::imshow("windowName2", frame);
    //cv::Mat threshold_output;
    if (temp == '0') {
     //cout << "detect!!" << endl;
     if ((center.x > 0) && (center.x < 240))
     {
      
      for (int i = 0; i < 100000000; i++)
      {
      }
      if ((center.y > 0) && (center.y < 190))
      {
       serialComm.sendCommand('1');
      }
      else if ((center.y > 190) && (center.y < 310))
      {
       serialComm.sendCommand('4');
      }
      else if ((center.y > 310) && (center.y < 500))
      {
       serialComm.sendCommand('7');
      }
      
     }
     if ((center.x > 240) && (center.x < 360))
     {
      for (int i = 0; i < 100000000; i++)
      {
      }
      if ((center.y > 0) && (center.y < 190))
      {
       serialComm.sendCommand('2');
      }
      else if ((center.y > 190) && (center.y < 310))
      {
       serialComm.sendCommand('5');
      }
      else if ((center.y > 310) && (center.y < 500))
      {
       serialComm.sendCommand('8');
      }
      
     }
     if ((center.x > 360) && (center.x < 600))
     {
      for (int i = 0; i < 100000000; i++)
      {
      }
 if ((center.y > 0) && (center.y < 190))
      {
       serialComm.sendCommand('3');
      }
      else if ((center.y > 190) && (center.y < 310))
      {
       serialComm.sendCommand('6');
      }
      else if ((center.y > 310) && (center.y < 500))
      {
       serialComm.sendCommand('9');
      }
      
     }
    }
    else {
     detectStatus = '0';
     if (temp == '1') {
      //cout << "Unknown" << endl;
      serialComm.sendCommand('0');
      temp = '0';
     }
    }
    std::vector<std::vector<cv::Point> > contours;
    std::vector<cv::Vec4i> hierarchy;
    cv::findContours(mask, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0));
    size_t largestContour = 0;
    for (size_t i = 1; i < contours.size(); i++)
    {
     if (cv::contourArea(contours[i]) > cv::contourArea(contours[largestContour]))
      largestContour = i;
    }
    cv::drawContours(frame, contours, largestContour, cv::Scalar(0, 0, 255), 1);
    // Convex hull
    if (!contours.empty())
    {
     std::vector<std::vector<cv::Point> > hull(1);
     cv::convexHull(cv::Mat(contours[largestContour]), hull[0], false);
     cv::drawContours(frame, hull, 0, cv::Scalar(0, 255, 0), 3);
    }
    cv::imshow("humancamera", mask);
    cv::imshow(windowName, frame);
   }
   catch (cv::Exception& e)
   {
    std::cerr << "Exception occurred. Ignoring frame... " << e.err << std::endl;
   }
  }
  if (cv::waitKey(30) >= 0) break;
 }
 // VideoCapture automatically deallocate camera object 
 return 0;
}

졸업 시즌마다 코드 전문을 원하시는 분들이 계셔서 올려봅니다
팀원들과 공유했던 메일에 남아있던 코드이고 다시 돌려보진 않았어요
영상처리 오픈소스 서너 개를 짜깁이 해서 완성한 코드이기 때문에 사용된 함수들을 구글링하면 더 좋은 자료들 참고하실 수 있을 거예요
2017년 자료이니 그대로 배끼기보단 응용 시에 참고가 되길 바랍니다

'전공 > Opencv' 카테고리의 다른 글

face tracking 아두이노 코드  (1) 2019.11.07
Face-tracking Robot 졸업작품  (18) 2018.01.29
저장된 사진 띄우기  (0) 2017.07.24
ubuntu 16.04 opencv 3.2.0 설치  (2) 2017.07.21
노트북 카메라 연동 얼굴 인식  (0) 2017.07.14

Face-tracking Robot 졸업작품

전공/Opencv

졸업작품으로 아두이노와 웹캠을 활용한 얼굴추적로봇을 만들었어요.

 

MCU : Arduino UNO R3

Servo motor : MG996

Web Cam : Logitec

Interface : Visual Studio C++ 와 Arduino 시리얼통신 (Baud Rate 9600)

 

Hardware : 과학상자

 

 

 

 

 

영상처리는 OpenCV 3.1.0 버전을 사용하였고,

얼굴추적방식은 처음에는 Haar-Cascade 방식을 사용하였으나 좋은 사양의 컴퓨터를 사용하지 못하다보니까 버퍼링과 딜레이 문제가 발생해서 피부색인식 방식으로 수정하였어요.

 

1. 얼굴 후보영역(mask) 검출

2. 윤곽선 얻기

3. 얼굴영역 찾기

4. 얼굴 중심점 검출

 

 

이렇게 크게 4가지 순서로 진행됩니다.

 

그 후에 웹캠에서 얼굴이 인식되면 얼굴 중심점의 좌표에 따라 9개의 영역으로 분할하여 제어기로 전송합니다.

 

제어기에서는 9개의 영역마다 지정된 제어를 반복하여 얼굴 중심점이 화면의 중앙 영역인 5번 영역으로 들어오도록 합니다.

 

 

Visual Studio C++ 코드는 다음과 같습니다.

OpenCV Library 불러오기

Webcam 불러오기

ArduinoSerial 통신

피부색 mask 따기

mask contour 따기

ConvexHull 그리기

중심점 그리기

아두이노와 통신하는 제어기 알고리즘

 

Arduino 코드는 다음과 같습니다.

 

 

마지막으로 완성된 동영상입니다.

 

 

 

 

'전공 > Opencv' 카테고리의 다른 글

face tracking 아두이노 코드  (1) 2019.11.07
face tracking C 코드  (3) 2019.10.31
저장된 사진 띄우기  (0) 2017.07.24
ubuntu 16.04 opencv 3.2.0 설치  (2) 2017.07.21
노트북 카메라 연동 얼굴 인식  (0) 2017.07.14

저장된 사진 띄우기

전공/Opencv

사진을 저장하는데 어느 디렉토리에 해야하는 지 몰라서 그냥 home에 저장해봤는데 그때도 잘 출력되더라고요

 

#include <opencv2/opencv.hpp>


int main(void)

{

cv::Mat img = cv::imread("Lena.jpg", CV_LOAD_IMAGE_COLOR);

cv::namedWindow("Image", cv::WINDOW_AUTOSIZE);

cv::imshow("Image", img);

cv::waitKey(0);


return 0;

}

 

이렇게 코딩을 합니다.

 

코드에서 보이는 것처럼 저장할 그림 파일은 Lena.jpg 라는 파일명을 가져야 합니다.

 

 

 

저 코드를 imgview.cpp로 새 도큐먼트를 만들어서 저장합니다.

 

$ g++ -o imgview imgview.cpp $(pkg-config --libs --cflags opencv)

 

터미널창에 위와 같이 빌드해주고

 

$ ./imgview

 

컴파일해줍니다.

 

 

 

 

'전공 > Opencv' 카테고리의 다른 글

face tracking C 코드  (3) 2019.10.31
Face-tracking Robot 졸업작품  (18) 2018.01.29
ubuntu 16.04 opencv 3.2.0 설치  (2) 2017.07.21
노트북 카메라 연동 얼굴 인식  (0) 2017.07.14
Opencv 설치하기 / 우분투  (0) 2017.07.11

ubuntu 16.04 opencv 3.2.0 설치

전공/Opencv

먼저

 

sudo apt-get install g++
sudo apt-get install cmake


 

OpenCV 2.4대 버전이 설치되어 있으면 새로 설치하는 OpenCV 3.2 버전이 제대로 동작하지 않기 때문에 제거해주어야 합니다.

 

 

 

아래처럼 보이면 OpenCV 2.4대 버전이 설치안되어 있는 상태입니다.

다음 단계로 넘어가도  됩니다.


webnautes@webnautes-note:~$ pkg-config --modversion opencv
Package opencv was not found in the pkg-config search path.
Perhaps you should add the directory containing `opencv.pc'
to the PKG_CONFIG_PATH environment variable
No package 'opencv' found

 

 

 

OpenCV 2.4대 버전이 설치되어 있는 경우에는 OpenCV  2.4 버전이 출력됩니다.

 

webnautes@webnautes-note:~$ pkg-config --modversion opencv
2.4.9.1

 

 

 

다음 명령으로 OpenCV 라이브러리 설정 파일을 포함해서 기존에 설치된 OpenCV 패키지를 삭제하고 진행해야 합니다.

 

$ sudo apt-get purge  libopencv* python-opencv
$ sudo apt-get autoremove

 

 

2. 기존 설치된 패키지 업그레이드

OpenCV 3.2를 설치해주기 전에 기존에 설치된 패키지들을 업그레이드 해주기 위한 작업입니다.

오래 걸리더라도 해주는 것이 좋습니다.

 

 

Ubuntu 저장소(repository)로부터 패키지 리스트를 업데이트합니다.

기존에 설치된 패키지들의 새로운 버전이 저장소에 있다면 리스트를 업데이트 하기위해 실행합니다.

 

$ sudo apt-get update

 

 

 

기존에 설치된 패키지의 새로운 버전이 있으면 업그레이드를 진행합니다.

 

$ sudo apt-get upgrade

 

 

 

3. OpenCV 컴파일 전 필요한 패키지 설치

 

OpenCV를 컴파일하는데 사용하는 것들이 포함된 패키지들을 설치합니다.

build-essential 패키지에는 C/C++ 컴파일러와 관련 라이브러리, make 같은 도구들이 포함되어 있습니다.

cmake는 컴파일 옵션이나 빌드된 라이브러리에 포함시킬 OpenCV 모듈 설정등을 위해 필요합니다.

 

$ sudo apt-get install build-essential cmake

 

 

 

pkg-config는 프로그램 컴파일 및 링크시 필요한 라이브러리에 대한 정보를 메타파일(확장자가 .pc 인 파일)로부터 가져오는데 사용됩니다.

터미널에서 특정 라이브러리를 사용한 소스코드를 컴파일시 필요한 컴파일러 및 링커 플래그를 추가하는데 도움이 됩니다.  

 

$ 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
$ sudo apt-get install libxvidcore-dev libx264-dev libxine2-dev

 

 

 

Video4Linux 패키지는 리눅스에서 실시간 비디오 캡처를 지원하기 위한 디바이스 드라이버와 API를 포함하고 있습니다.

 

$ sudo apt-get install libv4l-dev v4l-utils

 

 

 

GStreamer는 비디오 스트리밍을 위한 라이브러리입니다.

$ sudo apt-get install libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev

 

 

 

OpenCV에서는 highgui 모듈을 사용하여 자체적으로 윈도우 생성하여 이미지나 비디오들을 보여줄 수 있습니다.

윈도우 생성 등의 GUI를 위해 gtk 또는 qt를 선택해서 사용가능합니다.  

여기서는 qt4를 지정해주었습니다. QImage와 Mat 간의 변환에는 영향을 주지 않습니다.

 

$ sudo apt-get install libqt4-dev

 

 

그외 선택 가능한 패키지는 다음과 같습니다.

libgtk2.0-dev
libgtk-3-dev

libqt5-dev

 

 

 

OpenGL 지원하기 위해 필요한 라이브러리입니다.

$ sudo apt-get install mesa-utils libgl1-mesa-dri libqt4-opengl-dev

 

 

 

OpenCV 최적화를 위해 사용되는 라이브러리들입니다.

$ sudo apt-get install libatlas-base-dev gfortran libeigen3-dev

 



python2.7-dev와 python3-dev 패키지는 OpenCV-Python 바인딩을 위해 필요한 패키지들입니다.

Numpy는 매트릭스 연산등을 빠르게 처리할 수 있어서 OpenCV에서 사용됩니다.

 

$ sudo apt-get install python2.7-dev python3-dev
$ sudo apt-get install python-numpy python3-numpy

 

 

4. OpenCV 설정과 컴파일 및 설치

 

소스 코드를 저장할 임시 디렉토리를 생성하여 이동 후.. 진행합니다.

 

webnautes@webnautes-note:~$ mkdir opencv
webnautes@webnautes-note:~$ cd opencv
webnautes@webnautes-note:~/opencv$

 

 

 

OpenCV 3.2.0 소스코드를 다운로드 받아 압축을 풀어줍니다.

$ wget -O opencv.zip https://github.com/Itseez/opencv/archive/3.2.0.zip
$ unzip opencv.zip

 

 

 

opencv_contrib(extra modules) 소스코드를 다운로드 받아 압축을 풀어줍니다.

SIFT, SURF 등을 사용하기 위해 필요합니다.

 

$ wget -O opencv_contrib.zip https://github.com/Itseez/opencv_contrib/archive/3.2.0.zip
$ unzip opencv_contrib.zip

 

 

 

다음처럼 두 개의 디렉토리가 생성됩니다.

 

webnautes@webnautes-note:~/opencv$ ls -d */
opencv-3.2.0/  opencv_contrib-3.2.0/

 

 

 

opencv-3.2.0 디렉토리로 이동하여 build 디렉토리를 생성하고 build 디렉토리로 이동합니다.

컴파일은 build 디렉토리에서 이루어집니다.

 

webnautes@webnautes-note:~/opencv$ cd opencv-3.2.0/
webnautes@webnautes-note:~/opencv/opencv-3.2.0$ mkdir build
webnautes@webnautes-note:~/opencv/opencv-3.2.0$ cd build
webnautes@webnautes-note:~/opencv/opencv-3.2.0/build$

 

 

 

cmake를 사용하여 OpenCV 컴파일 설정을 해줍니다.

 

$ 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 ENABLE_NEON=ON \
-D WITH_QT=ON \
-D WITH_OPENGL=ON \
-D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib-3.2.0/modules \
-D WITH_V4L=ON  \
-D WITH_FFMPEG=ON \
-D WITH_XINE=ON \
-D BUILD_NEW_PYTHON_SUPPORT=ON \
../

 

 

 

다음과 같은 메시지가 보이면 정상적으로 된 것입니다.

 

-- Configuring done
-- Generating done
-- Build files have been written to: /home/webnautes/opencv/opencv-3.2.0/build

 

 

 

설정한 결과입니다.

 

-- General configuration for OpenCV 3.2.0 =====================================
--   Version control:               unknown
--
--   Extra modules:
--     Location (extra):            /home/webnautes/opencv/opencv_contrib-3.2.0/modules
--     Version control (extra):     unknown
--
--   Platform:
--     Timestamp:                   2017-06-09T14:35:28Z
--     Host:                        Linux 4.8.0-53-generic x86_64
--     CMake:                       3.5.1
--     CMake generator:             Unix Makefiles
--     CMake build tool:            /usr/bin/make
--     Configuration:               RELEASE
--
--   C/C++:
--     Built as dynamic libs?:      YES
--     C++ Compiler:                /usr/bin/c++  (ver 5.4.0)
--     C++ flags (Release):         -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wno-narrowing -Wno-delete-non-virtual-dtor -Wno-comment -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -msse -msse2 -mno-avx -msse3 -mno-ssse3 -mno-sse4.1 -mno-sse4.2 -ffunction-sections -fvisibility=hidden -fvisibility-inlines-hidden -O3 -DNDEBUG  -DNDEBUG
--     C++ flags (Debug):           -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wno-narrowing -Wno-delete-non-virtual-dtor -Wno-comment -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -msse -msse2 -mno-avx -msse3 -mno-ssse3 -mno-sse4.1 -mno-sse4.2 -ffunction-sections -fvisibility=hidden -fvisibility-inlines-hidden -g  -O0 -DDEBUG -D_DEBUG
--     C Compiler:                  /usr/bin/cc
--     C flags (Release):           -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wno-narrowing -Wno-comment -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -msse -msse2 -mno-avx -msse3 -mno-ssse3 -mno-sse4.1 -mno-sse4.2 -ffunction-sections -fvisibility=hidden -O3 -DNDEBUG  -DNDEBUG
--     C flags (Debug):             -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wno-narrowing -Wno-comment -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -msse -msse2 -mno-avx -msse3 -mno-ssse3 -mno-sse4.1 -mno-sse4.2 -ffunction-sections -fvisibility=hidden -g  -O0 -DDEBUG -D_DEBUG
--     Linker flags (Release):
--     Linker flags (Debug):
--     ccache:                      NO
--     Precompiled headers:         YES
--     Extra dependencies:          /usr/lib/x86_64-linux-gnu/libQtOpenGL.so /usr/lib/x86_64-linux-gnu/libQtGui.so /usr/lib/x86_64-linux-gnu/libQtTest.so /usr/lib/x86_64-linux-gnu/libQtCore.so /usr/lib/x86_64-linux-gnu/libpng.so /usr/lib/x86_64-linux-gnu/libz.so /usr/lib/x86_64-linux-gnu/libtiff.so /usr/lib/x86_64-linux-gnu/libjasper.so /usr/lib/x86_64-linux-gnu/libjpeg.so gstbase-1.0 gstreamer-1.0 gobject-2.0 glib-2.0 gstvideo-1.0 gstapp-1.0 gstriff-1.0 gstpbutils-1.0 xine avcodec-ffmpeg avformat-ffmpeg avutil-ffmpeg swscale-ffmpeg dl m pthread rt /usr/lib/x86_64-linux-gnu/libGLU.so /usr/lib/x86_64-linux-gnu/libGL.so
--     3rdparty dependencies:       libwebp IlmImf libprotobuf
--
--   OpenCV modules:
--     To be built:                 core flann imgproc ml photo reg surface_matching video dnn fuzzy imgcodecs shape videoio highgui objdetect plot superres xobjdetect xphoto bgsegm bioinspired dpm face features2d line_descriptor saliency text calib3d ccalib datasets rgbd stereo tracking videostab xfeatures2d ximgproc aruco optflow phase_unwrapping stitching structured_light python2 python3
--     Disabled:                    world contrib_world
--     Disabled by dependency:      -
--     Unavailable:                 cudaarithm cudabgsegm cudacodec cudafeatures2d cudafilters cudaimgproc cudalegacy cudaobjdetect cudaoptflow cudastereo cudawarping cudev java ts viz cnn_3dobj cvv freetype hdf matlab sfm
--
--   GUI:
--     QT 4.x:                      YES (ver 4.8.7 EDITION = OpenSource)
--     QT OpenGL support:           YES (/usr/lib/x86_64-linux-gnu/libQtOpenGL.so)
--     OpenGL support:              YES (/usr/lib/x86_64-linux-gnu/libGLU.so /usr/lib/x86_64-linux-gnu/libGL.so)
--     VTK support:                 NO
--
--   Media I/O:
--     ZLib:                        /usr/lib/x86_64-linux-gnu/libz.so (ver 1.2.8)
--     JPEG:                        /usr/lib/x86_64-linux-gnu/libjpeg.so (ver )
--     WEBP:                        build (ver 0.3.1)
--     PNG:                         /usr/lib/x86_64-linux-gnu/libpng.so (ver 1.2.54)
--     TIFF:                        /usr/lib/x86_64-linux-gnu/libtiff.so (ver 42 - 4.0.6)
--     JPEG 2000:                   /usr/lib/x86_64-linux-gnu/libjasper.so (ver 1.900.1)
--     OpenEXR:                     build (ver 1.7.1)
--     GDAL:                        NO
--     GDCM:                        NO
--
--   Video I/O:
--     DC1394 1.x:                  NO
--     DC1394 2.x:                  NO
--     FFMPEG:                      YES
--       avcodec:                   YES (ver 56.60.100)
--       avformat:                  YES (ver 56.40.101)
--       avutil:                    YES (ver 54.31.100)
--       swscale:                   YES (ver 3.1.101)
--       avresample:                NO
--     GStreamer:                   
--       base:                      YES (ver 1.8.3)
--       video:                     YES (ver 1.8.3)
--       app:                       YES (ver 1.8.3)
--       riff:                      YES (ver 1.8.3)
--       pbutils:                   YES (ver 1.8.3)
--     OpenNI:                      NO
--     OpenNI PrimeSensor Modules:  NO
--     OpenNI2:                     NO
--     PvAPI:                       NO
--     GigEVisionSDK:               NO
--     Aravis SDK:                  NO
--     UniCap:                      NO
--     UniCap ucil:                 NO
--     V4L/V4L2:                    NO/YES
--     XIMEA:                       NO
--     Xine:                        YES (ver 1.2.6)
--     gPhoto2:                     NO
--
--   Parallel framework:            pthreads
--
--   Other third-party libraries:
--     Use IPP:                     NO
--     Use IPP Async:               NO
--     Use VA:                      NO
--     Use Intel VA-API/OpenCL:     NO
--     Use Lapack:                  NO
--     Use Eigen:                   YES (ver 3.2.92)
--     Use Cuda:                    NO
--     Use OpenCL:                  YES
--     Use OpenVX:                  NO
--     Use custom HAL:              NO
--
--   OpenCL:                        <Dynamic loading of OpenCL library>
--     Include path:                /home/webnautes/opencv/opencv-3.2.0/3rdparty/include/opencl/1.2
--     Use AMDFFT:                  NO
--     Use AMDBLAS:                 NO
--
--   Python 2:
--     Interpreter:                 /usr/bin/python2.7 (ver 2.7.12)
--     Libraries:                   /usr/lib/x86_64-linux-gnu/libpython2.7.so (ver 2.7.12)
--     numpy:                       /usr/lib/python2.7/dist-packages/numpy/core/include (ver 1.11.0)
--     packages path:               lib/python2.7/dist-packages
--
--   Python 3:
--     Interpreter:                 /usr/bin/python3 (ver 3.5.2)
--     Libraries:                   /usr/lib/x86_64-linux-gnu/libpython3.5m.so (ver 3.5.2)
--     numpy:                       /usr/lib/python3/dist-packages/numpy/core/include (ver 1.11.0)
--     packages path:               lib/python3.5/dist-packages
--
--   Python (for build):            /usr/bin/python2.7
--
--   Java:
--     ant:                         NO
--     JNI:                         NO
--     Java wrappers:               NO
--     Java tests:                  NO
--
--   Matlab:                        Matlab not found or implicitly disabled
--
--   Tests and samples:
--     Tests:                       NO
--     Performance tests:           NO
--     C/C++ Examples:              NO
--
--   Install path:                  /usr/local
--
--   cvconfig.h is in:              /home/webnautes/opencv/opencv-3.2.0/build
-- -----------------------------------------------------------------
--
-- Configuring done
-- Generating done
-- Build files have been written to: /home/webnautes/opencv/opencv-3.2.0/build

 

 

 

Python 2 라이브러리 항목이 보이지 않는 경우에는   

다음 붉은색 줄처럼 해당 경로들을 직접 적어줘야 합니다.

 

$ 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 ENABLE_NEON=ON \
-D WITH_QT=ON \
-D WITH_OPENGL=ON \
-D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib-3.2.0/modules \
-D WITH_V4L=ON  \
-D WITH_FFMPEG=ON \
-D WITH_XINE=ON \
-D BUILD_NEW_PYTHON_SUPPORT=ON \
-D PYTHON_INCLUDE_DIR=/usr/include/python2.7 \
-D PYTHON_INCLUDE_DIR2=/usr/include/x86_64-linux-gnu/python2.7 \
-D PYTHON_LIBRARY=/usr/lib/x86_64-linux-gnu/libpython2.7.so \
../

 

 

 

컴파일을 시작하기 전에 사용 중인 컴퓨터의 CPU 코어수를 확인합니다.

$ cat /proc/cpuinfo | grep processor | wc -l
4

 

 //저는 1이 나와서 -j1로 했어요

 

make 명령을 사용하여 컴파일을 시작합니다.

-j 다음에 위에서 확인한 숫자를 붙여서 실행해줍니다.

컴파일시 걸리는 시간을 확인하기 위해 명령 앞에 time을 붙여주어 실행했습니다.

webnautes@webnautes-note:~/opencv/opencv-3.2.0/build$ time make -j4

 

 

i5-7200U CPU에서 OpenCV 컴파일 완료까지 7분정도 걸렸습니다.

 



컴파일 결과물을 설치합니다.

webnautes@webnautes-note:~/opencv/opencv-3.2.0/build$ sudo make install

 

 

 

/etc/ld.so.conf.d/ 디렉토리에 /usr/local/lib를 포함하는 설정파일이 있는지 확인합니다.

 

webnautes@webnautes-note:~/opencv/opencv-3.2.0/build$ cat /etc/ld.so.conf.d/*
/usr/lib/x86_64-linux-gnu/libfakeroot
# libc default configuration
/usr/local/lib
# Multiarch support
/lib/x86_64-linux-gnu
/usr/lib/x86_64-linux-gnu
/usr/lib/x86_64-linux-gnu/mesa-egl
/usr/lib/x86_64-linux-gnu/mesa
# Legacy biarch compatibility support
/lib32
/usr/lib32

 

 

 

/usr/local/lib이 출력되지 않았다면 다음 명령을 추가로 실행해야합니다.

 

webnautes@webnautes-note:~/opencv/opencv-3.2.0/build$ sudo echo '/usr/local/lib' > /etc/ld.so.conf.d/opencv.conf

 

 

/usr/local/lib을 찾은 경우나 못찾아서 추가한 작업을 한 경우 모두 컴파일시 opencv  라이브러리를 찾을 수 있도록 다음 명령을 실행합니다.

 

webnautes@webnautes-note:~/opencv/opencv-3.2.0/build$ sudo ldconfig

 



5. OpenCV 설치 결과 확인

5.1. C/C++

C/C++를 위해 OpenCV 라이브러리 사용가능 여부를 확인합니다.

문제 없으면 설치된 OpenCV 라이브러리의 버전이 출력됩니다.

 

webnautes@webnautes-note:~/opencv/opencv-3.2.0/build$ pkg-config --modversion opencv

3.2.0

 

 

 

아래처럼 opencv를 찾을 수 없다고 나오면  추가 작업이 필요합니다.

 

webnautes@webnautes-note:~/opencv/opencv-3.2.0/build$ pkg-config --modversion opencv
Package opencv was not found in the pkg-config search path.
Perhaps you should add the directory containing `opencv.pc'
to the PKG_CONFIG_PATH environment variable
No package 'opencv' found

 

 

 

pkg-config 명령이 /usr/local/lib/pkgconfig 경로에 있는 opencv.pc 파일을 찾을 수 있도록 해줘야 합니다.

 

$ sudo echo 'PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig' >> '/etc/bash.bashrc'
$ sudo echo 'export PKG_CONFIG_PATH' >> '/etc/bash.bashrc'
$ source ~/.bashrc

 

 

 

다시 확인했을 때,  OpenCV 버전이 출력되야 합니다.

 

webnautes@webnautes-note:~/opencv/opencv-3.2.0/build$ pkg-config --modversion opencv

3.2.0

 

 

 

pkg-config --libs --cflags opencv 명령을 실행했을 때 다음처럼 나오면 문제없이 설치가 완료된 것입니다.

 

 

 

 

/usr/local/share/OpenCV/samples/  경로에 OpenCV 예제코드들이 설치됩니다.

 

 

 

예제 코드를 하나 가져와서 컴파일 해보겠습니다.

 

$ cp /usr/local/share/OpenCV/samples/cpp/facedetect.cpp ./

 

 

 

컴파일 후, 실행시켜 봅니다.

 

$ g++ -o facedetect facedetect.cpp $(pkg-config --libs --cflags opencv)  

$ ./facedetect --cascade="/usr/local/share/OpenCV/haarcascades/haarcascade_frontalface_alt.xml" --nested-cascade="/usr/local/share/OpenCV/haarcascades/haarcascade_eye_tree_eyeglasses.xml " --scale=1.3

 

 //저는 왜 안될까요...

 

다음처럼 검출시간이 표시되면서 카메라 영상에 얼굴이 검출된 결과를 얻을 수 있습니다.

 

webnautes@webnautes-note:~/opencv/opencv-3.2.0/build$ ./facedetect --cascade="/usr/local/share/OpenCV/haarcascades/haarcascade_frontalface_alt.xml" --nested-cascade="/usr/local/share/OpenCV/haarcascades/haarcascade_eye_tree_eyeglasses.xml " --scale=1.3
Video capturing has been started ...
detection time = 61.4535 ms
init done
opengl support available
detection time = 51.8766 ms
detection time = 41.1699 ms
detection time = 46.1556 ms
detection time = 35.5041 ms

 

 

5.2. Python

python 2.x와 python 3x에서 opencv 라이브러리를 사용가능한지는 다음처럼 확인합니다.

각각 OpenCV 버전이 출력되어야 합니다.

webnautes@webnautes-note:~/opencv/opencv-3.2.0/build$ python
Python 2.7.12 (default, Nov 19 2016, 06:48:10)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>> cv2.__version__
'3.2.0'
>>>

 

 

webnautes@webnautes-note:~/opencv/opencv-3.2.0/build$ python3
Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>> cv2.__version__
'3.2.0'
>>>

 

 

 

예제 코드를 실행해봅니다.

 

$  python /usr/local/share/OpenCV/samples/python/facedetect.py --cascade "/usr/local/share/OpenCV/haarcascades/haarcascade_frontalface_alt.xml" --nested-cascade "/usr/local/share/OpenCV/haarcascades/haarcascade_eye_tree_eyeglasses.xml" /dev/video0

 

 

다음처럼  터미널에 표시되면서 카메라 영상에 얼굴이 검출된 결과를 얻을 수 있습니다.

 

webnautes@webnautes-note:~/opencv/opencv-3.2.0/build$  python /usr/local/share/OpenCV/samples/python/facedetect.py --cascade "/usr/local/share/OpenCV/haarcascades/haarcascade_frontalface_alt.xml" --nested-cascade "/usr/local/share/OpenCV/haarcascades/haarcascade_eye_tree_eyeglasses.xml" /dev/video0

face detection using haar cascades

USAGE:
   facedetect.py [--cascade <cascade_fn>] [--nested-cascade <cascade_fn>] [<video_source>]

init done
opengl support available

 

 

 

이제 필요 없어진 컴파일에 사용했던 opencv 소스코드 디렉토리를 삭제합니다.

 

webnautes@webnautes-note:~/opencv/opencv-3.2.0/build$ cd
webnautes@webnautes-note:~$ rm -rf opencv

 

//삭제했을때 전부 다 삭제되어서 opencv 가 깔린건 확인했는데 예제 파일들 때문에 다시 설치했어요.. 다른 방법이 있을 것 같긴 한데 뭐 암것도 모르니까 ㅠㅠ

'전공 > Opencv' 카테고리의 다른 글

Face-tracking Robot 졸업작품  (18) 2018.01.29
저장된 사진 띄우기  (0) 2017.07.24
노트북 카메라 연동 얼굴 인식  (0) 2017.07.14
Opencv 설치하기 / 우분투  (0) 2017.07.11
Opencv 설치하기  (1) 2017.07.07

노트북 카메라 연동 얼굴 인식

전공/Opencv



#include <iostream>

#include <opencv2/opencv.hpp>


#include <stdlib.h>

#include <stdio.h>


using namespace std;

using namespace cv;



/* @ function main */

int main(int argc, char *argv[])

{


   // open the default camera

   cv::VideoCapture cap(0);


   // check if we succeeded

   if (!cap.isOpened()) {

      std::cerr << "Could not open camera" << std::endl;

      return -1;

   }


   // create a window

   cv::namedWindow("webcam", 1);


   // face detection configuration

   cv::CascadeClassifier face_classifier;


   face_classifier.load("C:/opencv/sources/data/haarcascades/haarcascade_frontalface_alt.xml");


   cv::Mat frame;


   while(1) {

      bool frame_valid = true;


      try {


         // get a new frame from webcam

         cap >> frame;


      }

      catch (cv::Exception& e) {


         std::cerr << "Exception occurred. Ignoring frame... " << e.err << std::endl;

         frame_valid = false;


      }


      if (frame_valid) {

         try {

            // convert captured frame to gray scale & equalize

            cv::Mat grayframe;

            cv::cvtColor(frame, grayframe, CV_BGR2GRAY);

            cv::equalizeHist(grayframe, grayframe);


            // -------------------------------------------------------------

            // face detection routine


            // a vector array to store the face found

            std::vector<cv::Rect> faces;


            face_classifier.detectMultiScale(grayframe, faces,

               1.1, // increase search scale by 10% each pass

               3,   // merge groups of three detections

               CV_HAAR_FIND_BIGGEST_OBJECT | CV_HAAR_SCALE_IMAGE,

               cv::Size(30, 30)

            );


            // -------------------------------------------------------------

            // draw the results

            for (int i = 0; i < faces.size(); i++) {

               cv::Point lb(faces[i].x + faces[i].width, faces[i].y + faces[i].height);

               cv::Point tr(faces[i].x, faces[i].y);


               cv::rectangle(frame, lb, tr, cv::Scalar(0, 255, 0), 3, 4, 0);

            }


            // print the output

            cv::imshow("webcam", frame);


         }

         catch (cv::Exception& e) {

            std::cerr << "Exception occurred. Ignoring frame... " << e.err << std::endl;

         }

      }


      if (cv::waitKey(30) == 10) break;

   }


   // VideoCapture automatically deallocate camera object

   return 0;


}



'전공 > Opencv' 카테고리의 다른 글

Face-tracking Robot 졸업작품  (18) 2018.01.29
저장된 사진 띄우기  (0) 2017.07.24
ubuntu 16.04 opencv 3.2.0 설치  (2) 2017.07.21
Opencv 설치하기 / 우분투  (0) 2017.07.11
Opencv 설치하기  (1) 2017.07.07

Opencv 설치하기 / 우분투

전공/Opencv

OpenCV 설치


일단 기본 라이브러리 설치


$ sudo apt-get update


$ sudo apt-get install libopencv-dev build-essential checkinstall cmake pkg-config yasm libtiff4-dev libjpeg-dev libjasper-dev libavcodec-dev libavformat-dev libswscale-dev libdc1394-22-dev libxine-dev libgstreamer0.10-dev libgstreamer-plugins-base0.10-dev libv4l-dev python-dev python-numpy libtbb-dev libqt4-dev libgtk2.0-dev libfaac-dev libmp3lame-dev libopencore-amrnb-dev libopencore-amrwb-dev libtheora-dev libvorbis-dev libxvidcore-dev x264 v4l-utils ffmpeg 


ffmpeg이 설치가 안되면 


$ sudo add-apt-repository ppa:mc3man/trusty-media

$ sudo apt-get update

$ sudo apt-get dist-upgrade

$ sudo apt-get install ffmpeg


차례대로 해준다.


지금은 3.1 까지 나와있지만

나는 2.x 대로 작업하기 때문에 2.4.13 을 설치한다.


git으로 다운받으면 항상 최신버전이기 때문에 나는 직접 다운을 받는다. 


git clone 다운 시

$ git clone https://github.com/Itseez/opencv/



https://github.com/Itseez/opencv/archive/2.4.13.zip


링크로 다운받을 수 있다.


다운받으면 보통은 ~/Downloads 에 저장된다.


$ cd ~/Downloads

$ unzip opencv-2.4.13.zip 


cmake 가 없는 경우

$ sudo apt-get install cmake


$ cd opencv-2.4.13

$ mkdir release

$ cd release

$ cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D WITH_TBB=ON -D BUILD_NEW_PYTHON_SUPPORT=ON -D WITH_V4L=ON -D INSTALL_C_EXAMPLES=ON -D INSTALL_PYTHON_EXAMPLES=ON -D BUILD_EXAMPLES=ON -D WITH_QT=ON -D WITH_OPENGL=ON -D ENABLE_FAST_MATH=1 -D CUDA_FAST_MATH=1 -D WITH_CUBLAS=1  -DBUILD_TIFF=ON ..


를 한다.

QT가 없는 경우 QT옵션은 뺀다. (WITH_QT=ON 제외)

//저는 여기서 계속 에러가 났는데 버전 에러인 것 같기도 하고, 옵션 에러인 것 같기도 하고..

이것 저것 해보면서 성공했기때문에

뭐 때문에 에러가 풀렸는지는 잘 모르겠습니다 ㅠㅠ

1. qmake 에러가 발생해서 sudo apt-get install qt4-qmake 이렇게 해결해주었습니다.
2. sudo apt-get install qt5-default
이렇게 qt를 설치해주었는데 이때 오히려 에러가 더 많이 발생하였습니다.

3. release 폴더에 있는 CMakeCache.txt 를 삭제해주고 qt가 없는 옵션으로 다시 설치해주었습니다.
//

$ make

-j 옵션을 써서 속도를 향상시킬 수 있다.


make에 사용될 코어의 수이다.


ex) make -j4 => cpu 코어 4개 사용

ex) make -j8 => cpu 코어 8개 사용


저는 -j8을 해주었습니다. 시간이 꽤 오래 걸려요


// pkg-config --modversion opencv opencv 버전 확인하기//

$ sudo make install


anaconda를 사용하는 경우

$ cd ~/anaconda/lib/python2.7/site-packages/

$ ln -s /usr/local/lib/python2.7/site-packages/cv2.so cv2.so


를 추가로 해준다.



출처: http://hanmaruj.tistory.com/13 [하늘마루 이야기]

'전공 > Opencv' 카테고리의 다른 글

Face-tracking Robot 졸업작품  (18) 2018.01.29
저장된 사진 띄우기  (0) 2017.07.24
ubuntu 16.04 opencv 3.2.0 설치  (2) 2017.07.21
노트북 카메라 연동 얼굴 인식  (0) 2017.07.14
Opencv 설치하기  (1) 2017.07.07

Opencv 설치하기

전공/Opencv

opencv 설치하기에 앞서 visual studio는 2013버전으로 설치해주었습니다.

 

C에서와 마찬가지로 프로젝트를 실행시켜주는데 .c가 아닌 원래의 .cpp로 프로젝트를 열어줍니다.

 

 

 

C에서 하듯이 source에 new item을 추가해주고, 프로젝트의 property를 열어줍니다.

 

 

C/C++ - General - Additional Included Directories에 opencv 폴더들을 추가해줍니다.

 

(opencv 파일이 필요하신 분은 댓글 남겨주세요)

 

 

Linker - General - Additional Library Directories 에 opencv 폴더의 x64 - lib를 추가해줍니다.

 

 

Linker - Input - Additional Dependencies에 필요한 opencv library들을 추가해줍니다.

 

 

debug를 해줍니다.

 

(코드가 필요하신 분은 댓글 남겨주세요)

 

 

dll 에러가 발생합니다.

 

 

Visual Studio 2013 - Projects - (프로젝트 명) 의 Source 파일이 있는 폴더에 opencv의 dll 파일들을 추가해줍니다.

 

다시 debug를 해주면 노트북의 영상을 따올 수 있습니다.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

'전공 > Opencv' 카테고리의 다른 글

Face-tracking Robot 졸업작품  (18) 2018.01.29
저장된 사진 띄우기  (0) 2017.07.24
ubuntu 16.04 opencv 3.2.0 설치  (2) 2017.07.21
노트북 카메라 연동 얼굴 인식  (0) 2017.07.14
Opencv 설치하기 / 우분투  (0) 2017.07.11