Programowanie w systemie UNIX/OpenCV
Wygląd
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]Szukamy pliku opencv.pc:
pkg-config --cflags opencv
typowy wynik w Linuksie :
-I/usr/include/opencv
apt-file search opencv.pc
Lub flagi:
pkg-config --cflags -- opencv4
Wynik:
-I/usr/local/include/opencv4
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]- linuxize : how-to-install-opencv-on-ubuntu-20-04
- sudo apt install libopencv-dev python3-opencv
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
sprawdzanie
[edytuj]apt-file search opencv.pc
Funkcje
[edytuj]- convexHull
- isContourConvex
- convexityDefects
- Extreme Points means topmost, bottommost, rightmost and leftmost points of the object.
moduły
[edytuj]- highgui[6][7]
- podstawowe struktury w C ( ang. basic c structures)
Przykłady
[edytuj]c
[edytuj]"plain C API was discontinued somewhere before version 3.x !"[8]
#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>
kompilacja:
g++ o.cpp `pkg-config --cflags --libs opencv4` -I/usr/include/opencv4
plik pc
/usr/local/lib/opencv4.pc
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]Uwaga!
|
// 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]js
[edytuj]open file
[edytuj]Otwieranie pliku [9]
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello OpenCV.js</title>
</head>
<body>
<h2>Hello OpenCV.js</h2>
<p id="status">OpenCV.js is loading...</p>
<div>
<div class="inputoutput">
<img id="imageSrc" alt="No Image" />
<div class="caption">imageSrc <input type="file" id="fileInput" name="file" /></div>
</div>
<div class="inputoutput">
<canvas id="canvasOutput"></canvas>
<div class="caption">canvasOutput</div>
</div>
</div>
<script type="text/javascript">
let imgElement = document.getElementById('imageSrc');
let inputElement = document.getElementById('fileInput');
inputElement.addEventListener('change', (e) => {
imgElement.src = URL.createObjectURL(e.target.files[0]);
}, false);
imgElement.onload = function () {
let mat = cv.imread(imgElement);
cv.imshow('canvasOutput', mat);
mat.delete();
};
var Module = {
// https://emscripten.org/docs/api_reference/module.html#Module.onRuntimeInitialized
onRuntimeInitialized() {
document.getElementById('status').innerHTML = 'OpenCV.js is ready.';
}
};
</script>
<script async src="https://docs.opencv.org/master/opencv.js" type="text/javascript"></script>
</body>
</html>
python
[edytuj]Program do analizy obrazu[10]
- nie korzysta z pętli fo i CPU ( są one powolne i podatne na błędy )
- wykorzystuje wektoryzację z pomocą bibliotek Numpy lub OpenCV.
import cv2
import numpy as np
# Load image
im = cv2.imread('Mushroom1.jpg', cv2.IMREAD_GRAYSCALE)
# Calculate total number of pixels in image
nPixels = im.size
# Iterate over the possible threshold values, skipping 10 at a time for speed of development/checking
for T in range(1,255,10):
# Make all pixels under threshold black, leaving those above threshold unchanged
thresholded = (im < T) * im
# Count the non-zero pixels
nonZero = cv2.countNonZero(thresholded)
Zero = nPixels - nonZero
# Sum the non-zero pixels
sum = np.sum(thresholded)
# Print some statistics
print(f'T={T}, zero={Zero}, nonZero={nonZero}, sum={sum}')
# Save the image for animation
cv2.imwrite(f'DEBUG-T{T:03}.png', thresholded)
gui
[edytuj]GUI and OpenCV[11]
- python
- C++
- highgui
- Image-Processing-with-OpenCV-C++
- OpenCVGUI - github
- zGUI
- cvui learnopencv: cvui-gui-lib-built-on-top-of-opencv-drawing-primitives
pomoc
[edytuj]- strona domowa: http://opencv.org
- dokumentacja: http://docs.opencv.org/master/
- forum: http://answers.opencv.org
- learnopencv
- pyimagesearch The fastest way to learn OpenCV, Object Detection, and Deep Learning.
- https://github.com/opencv/opencv/issues
- http://stackoverflow.com/search?q=opencv
- https://help.ubuntu.com/community/OpenCV
- http://www.cs.iit.edu/~agam/cs512/lect-notes/opencv-intro/
- https://github.com/MartinThoma/algorithms/blob/master/OpenCV/mat-example/Makefile
- code project : OpenCV
- stackoverflow : opencv
- stackoverflow tag info : opencv
- RIP tutorial : OpenCV
- linuxfromscratch blfs
zobacz również
[edytuj]Źródła
[edytuj]- ↑ stackoverflow question :how-to-check-for-opencv-on-ubuntu-9-10
- ↑ answers.opencv.org : which-one-is-preferred-to-use-c-or-c
- ↑ opencv linux install
- ↑ stackoverflow question: how-to-check-for-opencv-on-ubuntu-9-10
- ↑ stackoverflow question find-opencv-version-installed-on-ubuntu
- ↑ docs.opencv.org 2.4 : modules highgui
- ↑ stackoverflow question : how-to-make-a-simple-window-with-one-button-using-opencv-highgui-only
- ↑ stackoverflow question: is-there-a-working-c-interface-for-opencv-3-x
- ↑ opencv : get-started
- ↑ stackoverflow question: is-there-any-good-command-to-get-pixels-gray-value-in-this-case-im-working-on
- ↑ stackoverflow question : opencv-and-creating-guis