Programowanie w systemie UNIX/OpenCV

Z Wikibooks, biblioteki wolnych podręczników.
Przejdź do nawigacji Przejdź do wyszukiwania

Zależności[edytuj]

wymagane[edytuj]

  • GCC 4.4.x or later
  • CMake 2.8.7 or higher
  • Git
  • GTK+ ( 2.x or higher, including headers =libgtk2.0-dev )
  • pkg-config
  • Python 2.6 or later and Numpy 1.5 or later with developer packages (python-dev, python-numpy)
  • ffmpeg or libav development packages: libavcodec-dev, libavformat-dev, libswscale-dev

opcjonalne[edytuj]

  • libtbb2 libtbb-dev
  • libdc1394 2.x
  • libjpeg-dev, libpng-dev, libtiff-dev, libjasper-dev, libdc1394-22-dev
  • CUDA Toolkit 6.5 or higher

pliki[edytuj]

Lokalizacja[edytuj]

 pkg-config --cflags opencv

typowy wynik w Linuksie :

 -I/usr/include/opencv

Wersje[edytuj]

biblioteki[edytuj]

Sprawdzamy jaką mamy wersję:[1]

 pkg-config --modversion opencv

lub

 dpkg -l | grep libopencv


językowe[edytuj]

  • C++
  • python
  • java
  • c : "C API was present in OpenCV 1.x. Now it is supported for backward compatibility only. It is deprecated and may be removed in the future."[2]

Instalacja[edytuj]

git[edytuj]

Ściągnij kod: [3]

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

wersja[edytuj]

Sprawdzamy wersję [4]

  pkg-config --modversion opencv

Katalog :[5]

 pkg-config --cflags opencv

przykładowy wynik :

 -I/usr/include/opencv

inny sposób :

  pkg-config --libs opencv

Wynik :

/usr/lib/x86_64-linux-gnu/libopencv_calib3d.so -lopencv_calib3d /usr/lib/x86_64-linux-gnu/libopencv_contrib.so -lopencv_contrib /usr/lib/x86_64-linux-gnu/libopencv_core.so -lopencv_core /usr/lib/x86_64-linux-gnu/libopencv_features2d.so -lopencv_features2d /usr/lib/x86_64-linux-gnu/libopencv_flann.so -lopencv_flann /usr/lib/x86_64-linux-gnu/libopencv_gpu.so -lopencv_gpu /usr/lib/x86_64-linux-gnu/libopencv_highgui.so -lopencv_highgui /usr/lib/x86_64-linux-gnu/libopencv_imgproc.so -lopencv_imgproc /usr/lib/x86_64-linux-gnu/libopencv_legacy.so -lopencv_legacy /usr/lib/x86_64-linux-gnu/libopencv_ml.so -lopencv_ml /usr/lib/x86_64-linux-gnu/libopencv_objdetect.so -lopencv_objdetect /usr/lib/x86_64-linux-gnu/libopencv_ocl.so -lopencv_ocl /usr/lib/x86_64-linux-gnu/libopencv_photo.so -lopencv_photo /usr/lib/x86_64-linux-gnu/libopencv_stitching.so -lopencv_stitching /usr/lib/x86_64-linux-gnu/libopencv_superres.so -lopencv_superres /usr/lib/x86_64-linux-gnu/libopencv_ts.so -lopencv_ts /usr/lib/x86_64-linux-gnu/libopencv_video.so -lopencv_video /usr/lib/x86_64-linux-gnu/libopencv_videostab.so -lopencv_videostab

Funkcje[edytuj]

  • convexHull
  • isContourConvex
  • convexityDefects
  • Extreme Points means topmost, bottommost, rightmost and leftmost points of the object.


moduły[edytuj]

Przykłady[edytuj]

c[edytuj]

 #include "cv.h"
 #include "highgui.h"


  gcc opencv.c -o opencv `pkg-config --libs --cflags opencv` -ldl -lm

wersja[edytuj]

/*
 http://stackoverflow.com/questions/2422514/how-to-check-for-opencv-on-ubuntu-9-10/12449594#12449594
 g++ `pkg-config --cflags opencv` c.c `pkg-config --libs opencv` 
 gcc c.c  `pkg-config --cflags --libs opencv` 
*/

#include <stdio.h>
#include <cv.h>

int main(void)
{
    printf("%s\r\n", CV_VERSION);
    printf("%u.%u.%u\r\n", CV_MAJOR_VERSION, CV_MINOR_VERSION, CV_SUBMINOR_VERSION);
}


Przykładowy wynik:

2.4.9.1
2.4.9

gui i otwieranie obrazów[edytuj]

/*
http://www.cs.iit.edu/~agam/cs512/lect-notes/opencv-intro/

gcc h.c  `pkg-config --cflags --libs opencv`


OpenCV uses BGR as its default colour order for images,




*/
////////////////////////////////////////////////////////////////////////
//
// h.c
//
// This is a simple, introductory OpenCV program. The program reads an
// image from a file, inverts it, and displays the result. 
//
////////////////////////////////////////////////////////////////////////
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <cv.h>
#include <highgui.h> // // highgui_c.h


int main(int argc, char *argv[])
{
  IplImage* img = 0; 
  int height,width,step,channels;
  uchar *data;
  int i,j,k;

  if(argc<2){
    printf("Usage: main <image-file-name>\n\7");
    exit(0);
  }

  // load an image  
  img=cvLoadImage(argv[1],CV_LOAD_IMAGE_COLOR );
  if(!img){
    printf("Could not load image file: %s\n",argv[1]);
    exit(0);
  }

  // get the image data
  height    = img->height;
  width     = img->width;
  step      = img->widthStep;
  channels  = img->nChannels;
  data      = (uchar *)img->imageData;
  printf("Processing a %dx%d image with %d channels\n",height,width,channels); 

  // create a window
  cvNamedWindow("mainWin", CV_WINDOW_AUTOSIZE); 
  cvMoveWindow("mainWin", 100, 100);

  // invert the image
 // for(i=0;i<height;i++) for(j=0;j<width;j++) for(k=0;k<channels;k++)
  //  data[i*step+j*channels+k]=255-data[i*step+j*channels+k];

  // show the image
  cvShowImage("mainWin", img );

  // wait for a key
  cvWaitKey(0);

  // release the image
  cvReleaseImage(&img );
  
  
   printf("OpenCV version = %s\r\n", CV_VERSION);
  return 0;
}

mysz[edytuj]

/*
http://www.cs.iit.edu/~agam/cs512/lect-notes/opencv-intro/

gcc h.c  `pkg-config --cflags --libs opencv`



*/
////////////////////////////////////////////////////////////////////////
//
// h.c
//
// This is a simple, introductory OpenCV program. The program reads an
// image from a file, inverts it, and displays the result. 
//
////////////////////////////////////////////////////////////////////////
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <cv.h>
#include <highgui.h> // highgui_c.h


int height,width,step,channels;
 uchar *data;


// https://opencv-srf.blogspot.com/2011/11/mouse-events.html
// http://opencvexamples.blogspot.com/2014/01/detect-mouse-clicks-and-moves-on-image.html
// https://www.codeproject.com/Articles/526218/An-introduction-to-OpenCV-Part-II-Implementing-mou

void OnMouse(int event, int x, int y, int flags, void* param)
{

	IplImage* image = (IplImage*) param; // https://www.safaribooksonline.com/library/view/learning-opencv/9780596516130/ch04s04.html
	
     if  ( event == CV_EVENT_LBUTTONDOWN )
     {
          //cout << "Left button of the mouse is clicked - position (" << x << ", " << y << ")" << endl;
     }
     else if  ( event == CV_EVENT_RBUTTONDOWN )
     {
          //cout << "Right button of the mouse is clicked - position (" << x << ", " << y << ")" << endl;
     }
     else if  ( event == CV_EVENT_MBUTTONDOWN )
     {
          //cout << "Middle button of the mouse is clicked - position (" << x << ", " << y << ")" << endl;
     }
     else if ( event == CV_EVENT_MOUSEMOVE )
     {
         // cout << "Mouse move over the window - position (" << x << ", " << y << ")" << endl;
         printf(" x= %d ; y = %d B = %d G = %d R = %d\n ", x, y, data[y*step+x*channels+0],  data[y*step+x*channels+1],  data[y*step+x*channels+2]);
    	

     }
}




int main(int argc, char *argv[])
{
  IplImage* img = 0; 
  
 
  int i,j,k;
   
  
  

  if(argc<2){
    printf("Usage: main <image-file-name>\n\7");
    exit(0);
  }

  // load an image  
  img=cvLoadImage(argv[1],CV_LOAD_IMAGE_COLOR );
  if(!img){
    printf("Could not load image file: %s\n",argv[1]);
    exit(0);
  }
  
  
    

  // get the image data
  height    = img->height;
  width     = img->width;
  step      = img->widthStep;
  channels  = img->nChannels;
  data      = (uchar *)img->imageData;
  printf("Processing a %dx%d image with %d channels\n",height,width,channels); 

  // create a window
  cvNamedWindow("mainWin", CV_WINDOW_AUTOSIZE); 
  cvMoveWindow("mainWin", 100, 100);

  // invert the image
 // for(i=0;i<height;i++) for(j=0;j<width;j++) for(k=0;k<channels;k++)
  //  data[i*step+j*channels+k]=255-data[i*step+j*channels+k];

   //set the callback function for any mouse event
   // https://stackoverflow.com/questions/15570431/opencv-return-value-from-mouse-callback-function
   // 
  cvSetMouseCallback("mainWin", OnMouse, (void*) img);
  //  here 


  // show the image
  cvShowImage("mainWin", img );

  // wait for a key
  cvWaitKey(0);

  // release the image
  cvReleaseImage(&img );
  
  
   printf("OpenCV version = %s\r\n", CV_VERSION);
  return 0;
}

c++[edytuj]

 #include <opencv2/core/core.hpp>
 #include <opencv2/highgui/highgui.hpp>

pierwszy program, wersja[edytuj]

// https://www.solarianprogrammer.com/2014/04/21/opencv-beaglebone-black-ubuntu/
// Test to check the OpenCV version
// Build on Linux with:
 // g++ test_1.cpp -o test_1 -lopencv_core
 
#include <opencv2/opencv.hpp>
#include <iostream>
 
 int main() {
 	std::cout << "Hello, OpenCV version "<< CV_VERSION << std::endl;
 	return 0;
 }

Przykłądowy wynik :

 Hello, OpenCV version 2.4.9.1

otwieranie obrazów i gui[edytuj]


// http://docs.opencv.org/master/db/df5/tutorial_linux_gcc_cmake.html
// DisplayImage.cpp
#include <stdio.h>
#include <opencv2/opencv.hpp>
using namespace cv;
int main(int argc, char** argv )
{
    if ( argc != 2 )
    {
        printf("usage: DisplayImage.out <Image_Path>\n");
        return -1;
    }
    Mat image;
    image = imread( argv[1], 1 );
    if ( !image.data )
    {
        printf("No image data \n");
        return -1;
    }
    namedWindow("Display Image", WINDOW_AUTOSIZE );
    imshow("Display Image", image);
    waitKey(0);
    return 0;
}


CMakeLists.txt :

cmake_minimum_required(VERSION 2.8)
project( DisplayImage )
find_package( OpenCV REQUIRED )
include_directories( ${OpenCV_INCLUDE_DIRS} )
add_executable( DisplayImage DisplayImage.cpp )
target_link_libraries( DisplayImage ${OpenCV_LIBS} )


kompilacja :

cmake .
make

uruchomienie

 ./DisplayImage lena.jpg

Gradient[edytuj]

// original code by http://stackoverflow.com/users/951860/mevatron
// see http://stackoverflow.com/a/11157426/15485
// http://stackoverflow.com/users/15485/uvts-cvs added the code for saving x and y gradient component 

#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

#include <iostream>
#include <vector>

using namespace cv;
using namespace std;

Mat mat2gray(const cv::Mat& src)
{
    Mat dst;
    normalize(src, dst, 0.0, 255.0, cv::NORM_MINMAX, CV_8U);

    return dst;
}

Mat orientationMap(const cv::Mat& mag, const cv::Mat& ori, double thresh = 1.0)
{
    Mat oriMap = Mat::zeros(ori.size(), CV_8UC3);
    Vec3b red(0, 0, 255);
    Vec3b cyan(255, 255, 0);
    Vec3b green(0, 255, 0);
    Vec3b yellow(0, 255, 255);
    for(int i = 0; i < mag.rows*mag.cols; i++)
    {
        float* magPixel = reinterpret_cast<float*>(mag.data + i*sizeof(float));
        if(*magPixel > thresh)
        {
            float* oriPixel = reinterpret_cast<float*>(ori.data + i*sizeof(float));
            Vec3b* mapPixel = reinterpret_cast<Vec3b*>(oriMap.data + i*3*sizeof(char));
            if(*oriPixel < 90.0)
                *mapPixel = red;
            else if(*oriPixel >= 90.0 && *oriPixel < 180.0)
                *mapPixel = cyan;
            else if(*oriPixel >= 180.0 && *oriPixel < 270.0)
                *mapPixel = green;
            else if(*oriPixel >= 270.0 && *oriPixel < 360.0)
                *mapPixel = yellow;
        }
    }

    return oriMap;
}

int main(int argc, char* argv[])
{
    Mat image = Mat::zeros(Size(320, 240), CV_8UC1);
    circle(image, Point(160, 120), 80, Scalar(255, 255, 255), -1, CV_AA);

    imshow("original", image);

    Mat Sx;
    Sobel(image, Sx, CV_32F, 1, 0, 3);

    Mat Sy;
    Sobel(image, Sy, CV_32F, 0, 1, 3);

    Mat mag, ori;
    magnitude(Sx, Sy, mag);
    phase(Sx, Sy, ori, true);

    Mat oriMap = orientationMap(mag, ori, 1.0);

    imshow("x", mat2gray(Sx));
    imshow("y", mat2gray(Sy));

    imwrite("hor.png",mat2gray(Sx));
    imwrite("ver.png",mat2gray(Sy));

    imshow("magnitude", mat2gray(mag));
    imshow("orientation", mat2gray(ori));
    imshow("orientation map", oriMap);
    waitKey();

    return 0;
}


CMakeLists.txt :

cmake_minimum_required(VERSION 2.8)
project( g )
find_package( OpenCV REQUIRED )
include_directories( ${OpenCV_INCLUDE_DIRS} )
add_executable( g g.cpp )
target_link_libraries( g ${OpenCV_LIBS} )

Kompilacja :

 cmake .
 make

Uruchomienie

./g

pfm[edytuj]

python[edytuj]

gui[edytuj]

pomoc[edytuj]

Źródła[edytuj]

  1. stackoverflow question :how-to-check-for-opencv-on-ubuntu-9-10
  2. answers.opencv.org : which-one-is-preferred-to-use-c-or-c
  3. opencv linux install
  4. stackoverflow question: how-to-check-for-opencv-on-ubuntu-9-10
  5. stackoverflow question find-opencv-version-installed-on-ubuntu
  6. docs.opencv.org 2.4 : modules highgui
  7. stackoverflow question : how-to-make-a-simple-window-with-one-button-using-opencv-highgui-only
  8. building-an-interactive-gui-with-opencv by erget
  9. opencv-python-tutroals gui