提交 e1aa8eea 编写于 作者: A Ana Huaman

Added reST tutorials for copyMakeBorder, Sobel Operator, updated links in conf.py

上级 f0227edd
.. _canny_detector:
Canny Edge Detector
********************
Goal
=====
In this tutorial you will learn how to:
a. Use the OpenCV function :canny:`Canny <>` to implement the Canny Edge Detector.
Code
=====
.. code-block:: cpp
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <stdlib.h>
#include <stdio.h>
using namespace cv;
/// Global variables
Mat src, src_gray;
Mat dst, detected_edges;
int edgeThresh = 1;
int lowThreshold;
int const max_lowThreshold = 100;
int ratio = 3;
int kernel_size = 3;
char* window_name = "Edge Map";
/**
* @function CannyThreshold
* @brief Trackbar callback - Canny thresholds input with a ratio 1:3
*/
void CannyThreshold(int, void*)
{
/// Reduce noise with a kernel 3x3
blur( src_gray, dst, Size(3,3) );
/// Canny detector
Canny( src_gray, detected_edges, lowThreshold, lowThreshold*ratio, kernel_size );
/// Using Canny's output as a mask, we display our result
dst = Scalar::all(0);
src.copyTo( dst, detected_edges);
imshow( window_name, dst );
}
/** @function main */
int main( int argc, char** argv )
{
/// Load an image
src = imread( argv[1] );
if( !src.data )
{ return -1; }
/// Convert the image to grayscale
cvtColor( src, src_gray, CV_BGR2GRAY );
/// Create a window
namedWindow( window_name, CV_WINDOW_AUTOSIZE );
/// Create a Trackbar for user to enter threshold
createTrackbar( "Min Threshold:", window_name, &lowThreshold, max_lowThreshold, CannyThreshold );
/// Show the image
CannyThreshold(0, 0);
/// Wait until user exit program by pressing a key
waitKey(0);
return 0;
}
.. _copyMakeBorder:
Adding borders to your images
******************************
Goal
=====
In this tutorial you will learn how to:
#. Use the OpenCV function :copy_make_border:`copyMakeBorder <>` to set the borders (extra padding to your image).
Theory
============
.. note::
The explanation below belongs to the book **Learning OpenCV** by Bradski and Kaehler.
#. In our previous tutorial we learned to use convolution to operate on images. One problem that naturally arises is how to handle the boundaries. How can we convolve them if the evaluated points are at the edge of the image?
#. What most of OpenCV functions do is to copy a given image onto another slightly larger image and then automatically pads the boundary (by any of the methods explained in the sample code just below). This way, the convolution can be performed over the needed pixels without problems (the extra padding is cut after the operation is done).
#. In this tutorial, we will briefly explore two ways of defining the extra padding (border) for an image:
a. **BORDER_CONSTANT**: Pad the image with a constant value (i.e. black or :math:`0`
b. **BORDER_REPLICATE**: The row or column at the very edge of the original is replicated to the extra border.
This will be seen more clearly in the Code section.
Code
======
#. **What does this program do?**
* Load an image
* Let the user choose what kind of padding use in the input image. There are two options:
#. *Constant value border*: Applies a padding of a constant value for the whole border. This value will be updated randomly each 0.5 seconds.
#. *Replicated border*: The border will be replicated from the pixel values at the edges of the original image.
The user chooses either option by pressing 'c' (constant) or 'r' (replicate)
* The program finishes when the user presses 'ESC'
#. The tutorial code's is shown lines below. You can also download it from `here <https://code.ros.org/svn/opencv/trunk/opencv/samples/cpp/tutorial_code/ImgTrans/copyMakeBorder_demo.cpp>`_
.. code-block:: cpp
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <stdlib.h>
#include <stdio.h>
using namespace cv;
/// Global Variables
Mat src, dst;
int top, bottom, left, right;
int borderType;
Scalar value;
char* window_name = "copyMakeBorder Demo";
RNG rng(12345);
/** @function main */
int main( int argc, char** argv )
{
int c;
/// Load an image
src = imread( argv[1] );
if( !src.data )
{ return -1;
printf(" No data entered, please enter the path to an image file \n");
}
/// Brief how-to for this program
printf( "\n \t copyMakeBorder Demo: \n" );
printf( "\t -------------------- \n" );
printf( " ** Press 'c' to set the border to a random constant value \n");
printf( " ** Press 'r' to set the border to be replicated \n");
printf( " ** Press 'ESC' to exit the program \n");
/// Create window
namedWindow( window_name, CV_WINDOW_AUTOSIZE );
/// Initialize arguments for the filter
top = (int) (0.05*src.rows); bottom = (int) (0.05*src.rows);
left = (int) (0.05*src.cols); right = (int) (0.05*src.cols);
dst = src;
imshow( window_name, dst );
while( true )
{
c = waitKey(500);
if( (char)c == 27 )
{ break; }
else if( (char)c == 'c' )
{ borderType = BORDER_CONSTANT; }
else if( (char)c == 'r' )
{ borderType = BORDER_REPLICATE; }
value = Scalar( rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255) );
copyMakeBorder( src, dst, top, bottom, left, right, borderType, value );
imshow( window_name, dst );
}
return 0;
}
Explanation
=============
#. First we declare the variables we are going to use:
.. code-block:: cpp
Mat src, dst;
int top, bottom, left, right;
int borderType;
Scalar value;
char* window_name = "copyMakeBorder Demo";
RNG rng(12345);
Especial attention deserves the variable *rng* which is a random number generator. We use it to generate the random border color, as we will see soon.
#. As usual we load our source image *src*:
.. code-block:: cpp
src = imread( argv[1] );
if( !src.data )
{ return -1;
printf(" No data entered, please enter the path to an image file \n");
}
#. After giving a short intro of how to use the program, we create a window:
.. code-block:: cpp
namedWindow( window_name, CV_WINDOW_AUTOSIZE );
#. Now we initialize the argument that defines the size of the borders (*top*, *bottom*, *left* and *right*). We give them a value of 5% the size of *src*.
.. code-block:: cpp
top = (int) (0.05*src.rows); bottom = (int) (0.05*src.rows);
left = (int) (0.05*src.cols); right = (int) (0.05*src.cols);
#. The program begins a *while* loop. If the user presses 'c' or 'r', the *borderType* variable takes the value of *BORDER_CONSTANT* or *BORDER_REPLICATE* respectively:
.. code-block:: cpp
while( true )
{
c = waitKey(500);
if( (char)c == 27 )
{ break; }
else if( (char)c == 'c' )
{ borderType = BORDER_CONSTANT; }
else if( (char)c == 'r' )
{ borderType = BORDER_REPLICATE; }
#. In each iteration (after 0.5 seconds), the variable *value* is updated...
.. code-block:: cpp
value = Scalar( rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255) );
with a random value generated by the **RNG** variable *rng*. This value is a number picked randomly in the range :math:`[0,255]`
#. Finally, we call the function :copy_make_border:`copyMakeBorder <>` to apply the respective padding:
.. code-block:: cpp
copyMakeBorder( src, dst, top, bottom, left, right, borderType, value );
The arguments are:
a. *src*: Source image
#. *dst*: Destination image
#. *top*, *bottom*, *left*, *right*: Length in pixels of the borders at each side of the image. We define them as being 5% of the original size of the image.
#. *borderType*: Define what type of border is applied. It can be constant or replicate for this example.
#. *value*: If *borderType* is *BORDER_CONSTANT*, this is the value used to fill the border pixels.
#. We display our output image in the image created previously
.. code-block:: cpp
imshow( window_name, dst );
Results
========
#. After compiling the code above, you can execute it giving as argument the path of an image. The result should be:
* By default, it begins with the border set to BORDER_CONSTANT. Hence, a succession of random colored borders will be shown.
* If you press 'r', the border will become a replica of the edge pixels.
* If you press 'c', the random colored borders will appear again
* If you press 'ESC' the program will exit.
Below some screenshot showing how the border changes color and how the *BORDER_REPLICATE* option looks:
.. image:: images/CopyMakeBorder_Tutorial_Results.jpg
:alt: Final result after copyMakeBorder application
:width: 750pt
:align: center
.. _laplace_operator:
Laplace Operator
*****************
Goal
=====
In this tutorial you will learn how to:
a. Use the OpenCV function :laplacian:`Laplacian <>` to implement a discrete analog of the *Laplacian operator*.
Theory
=======
Laplacian Operator
-------------------
.. math::
Laplace(f) = \dfrac{\partial^{2} f}{\partial x^{2}} + \dfrac{\partial^{2} f}{\partial y^{2}}
Code
======
.. code-block:: cpp
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <stdlib.h>
#include <stdio.h>
using namespace cv;
/** @function main */
int main( int argc, char** argv )
{
Mat src, src_gray, dst;
int kernel_size = 3;
int scale = 1;
int delta = 0;
int ddepth = CV_16S;
char* window_name = "Laplace Demo";
int c;
/// Load an image
src = imread( argv[1] );
if( !src.data )
{ return -1; }
/// Remove noise by blurring with a Gaussian filter
GaussianBlur( src, src, Size(3,3), 0, 0, BORDER_DEFAULT );
/// Convert the image to grayscale
cvtColor( src, src_gray, CV_RGB2GRAY );
/// Create window
namedWindow( window_name, CV_WINDOW_AUTOSIZE );
/// Apply Laplace function
Mat abs_dst;
Laplacian( src_gray, dst, ddepth, kernel_size, scale, delta, BORDER_DEFAULT );
convertScaleAbs( dst, abs_dst );
/// Show what you got
imshow( window_name, abs_dst );
waitKey(0);
return 0;
}
.. _sobel_derivatives:
Sobel Derivatives
******************
Goal
=====
In this tutorial you will learn how to:
#. Use the OpenCV function :sobel:`Sobel <>` to calculate the derivatives from an image.
#. Use the OpenCV function :scharr:`Scharr <>` to calculate a more accurate derivative for a kernel of size :math:`3 \cdot 3`
Theory
========
.. note::
The explanation below belongs to the book **Learning OpenCV** by Bradski and Kaehler.
#. In the last two tutorials we have seen applicative examples of convolutions. One of the most important convolutions is the computation of derivatives in an image (or an approximation to them).
#. Why may be important the calculus of the derivatives in an image? Let's imagine we want to detect the *edges* present in the image. For instance:
.. image:: images/Sobel_Derivatives_Tutorial_Theory_0.jpg
:alt: How intensity changes in an edge
:height: 200pt
:align: center
You can easily notice that in an *edge*, the pixel intensity *changes* in a notorious way. A good way to express *changes* is by using *derivatives*. A high change in gradient indicates a major change in the image.
Sobel Operator
---------------
#. The Sobel Operator is a discrete differentiation operator. It computes an approximation of the gradient of an image intensity function.
#. The Sobel Operator combines Gaussian smoothing and differentiation.
Formulation
^^^^^^^^^^^^
Assuming that the image to be operated is :math:`I`:
#. We calculate two derivatives:
a. **Horizontal changes**: This is computed by convolving :math:`I` with a kernel :math:`G_{x}` such as:
.. math::
G_{x} = \begin{bmatrix}
-1 & 0 & +1 \\
-2 & 0 & +2 \\
-1 & 0 & +1
\end{bmatrix} * I
b. **Vertical changes**: This is computed by convolving :math:`I` with a kernel :math:`G_{y}` such as:
.. math::
G_{y} = \begin{bmatrix}
-1 & -2 & -1 \\
0 & 0 & 0 \\
+1 & +2 & +1
\end{bmatrix} * I
#. At each point of the image we calculate an approximation of the *gradient* in that point by combining both results above:
.. math::
G = \sqrt{ G_{x}^{2} + G_{y}^{2} }
Although sometimes the following simpler equation is used:
.. math::
G = |G_{x}| + |G_{y}|
Code
=====
#. **What does this program do?**
* Applies the *Sobel Operator* and generates as output an image with the detected *edges* bright on a darker background.
#. The tutorial code's is shown lines below. You can also download it from `here <https://code.ros.org/svn/opencv/trunk/opencv/samples/cpp/tutorial_code/ImgTrans/Sobel_Demo.cpp>`_
.. code-block:: cpp
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <stdlib.h>
#include <stdio.h>
using namespace cv;
/** @function main */
int main( int argc, char** argv )
{
Mat src, src_gray;
Mat grad;
char* window_name = "Sobel Demo - Simple Edge Detector";
int scale = 1;
int delta = 0;
int ddepth = CV_16S;
int c;
/// Load an image
src = imread( argv[1] );
if( !src.data )
{ return -1; }
GaussianBlur( src, src, Size(3,3), 0, 0, BORDER_DEFAULT );
/// Convert it to gray
cvtColor( src, src_gray, CV_RGB2GRAY );
/// Create window
namedWindow( window_name, CV_WINDOW_AUTOSIZE );
/// Generate grad_x and grad_y
Mat grad_x, grad_y;
Mat abs_grad_x, abs_grad_y;
/// Gradient X
//Scharr( src_gray, grad_x, ddepth, 1, 0, scale, delta, BORDER_DEFAULT );
Sobel( src_gray, grad_x, ddepth, 1, 0, 3, scale, delta, BORDER_DEFAULT );
convertScaleAbs( grad_x, abs_grad_x );
/// Gradient Y
//Scharr( src_gray, grad_y, ddepth, 0, 1, scale, delta, BORDER_DEFAULT );
Sobel( src_gray, grad_y, ddepth, 0, 1, 3, scale, delta, BORDER_DEFAULT );
convertScaleAbs( grad_y, abs_grad_y );
/// Total Gradient (approximate)
addWeighted( abs_grad_x, 0.5, abs_grad_y, 0.5, 0, grad );
imshow( window_name, grad );
waitKey(0);
return 0;
}
Explanation
=============
#. First we declare the variables we are going to use:
.. code-block:: cpp
Mat src, src_gray;
Mat grad;
char* window_name = "Sobel Demo - Simple Edge Detector";
int scale = 1;
int delta = 0;
int ddepth = CV_16S;
#. As usual we load our source image *src*:
.. code-block:: cpp
src = imread( argv[1] );
if( !src.data )
{ return -1; }
#. First, we apply a :gaussian_blur:`GaussianBlur <>` to our image to reduce the noise ( kernel size = 3 )
.. code-block:: cpp
GaussianBlur( src, src, Size(3,3), 0, 0, BORDER_DEFAULT );
#. Now we convert our filtered image to grayscale:
.. code-block:: cpp
cvtColor( src, src_gray, CV_RGB2GRAY );
#. Second, we calculate the "*derivatives*" in *x* and *y* directions. For this, we use the function :sobel:`Sobel <>` as shown below:
.. code-block:: cpp
Mat grad_x, grad_y;
Mat abs_grad_x, abs_grad_y;
/// Gradient X
Sobel( src_gray, grad_x, ddepth, 1, 0, 3, scale, delta, BORDER_DEFAULT );
/// Gradient Y
Sobel( src_gray, grad_y, ddepth, 0, 1, 3, scale, delta, BORDER_DEFAULT );
The function takes the following arguments:
* *src_gray*: In our example, the input image. Here it is *CV_8U*
* *grad_x*/*grad_y*: The output image.
* *ddepth*: The depth of the output image. We set it to *CV_16S* to avoid overflow.
* *x_order*: The order of the derivative in **x** direction.
* *y_order*: The order of the derivative in **y** direction.
* *scale*, *delta* and *BORDER_DEFAULT*: We use default values.
Notice that to calculate the gradient in *x* direction we use: :math:`x_{order}= 1` and :math:`y_{order} = 0`. We do analogously for the *y* direction.
#. We convert our partial results back to *CV_8U*:
.. code-block:: cpp
convertScaleAbs( grad_x, abs_grad_x );
convertScaleAbs( grad_y, abs_grad_y );
#. Finally, we try to approximate the *gradient* by adding both directional gradients (note that this is not an exact calculation at all! but it is good for our purposes).
.. code-block:: cpp
addWeighted( abs_grad_x, 0.5, abs_grad_y, 0.5, 0, grad );
#. Finally, we show our result:
.. code-block:: cpp
imshow( window_name, grad );
Results
========
#. Here is the output of applying our basic detector to *lena.jpg*:
.. image:: images/Sobel_Derivatives_Tutorial_Result.jpg
:alt: Result of applying Sobel operator to lena.jpg
:width: 300pt
:align: center
......@@ -126,3 +126,73 @@ In this section you will learn about the image processing (manipulation) functio
:width: 100pt
* :ref:`copyMakeBorder`
===================== ==============================================
|CopyMakeBorder| *Title:* **Adding borders to your images**
*Compatibility:* > OpenCV 2.0
*Author:* |Author_AnaH|
Where we learn how to pad our images!
===================== ==============================================
.. |CopyMakeBorder| image:: images/imgtrans/CopyMakeBorder_Tutorial_Cover.jpg
:height: 100pt
:width: 100pt
* :ref:`sobel_derivatives`
===================== ==============================================
|SobelDerivatives| *Title:* **Sobel Derivatives**
*Compatibility:* > OpenCV 2.0
*Author:* |Author_AnaH|
Where we learn how to calculate gradients and use them to detect edges!
===================== ==============================================
.. |SobelDerivatives| image:: images/imgtrans/Sobel_Derivatives_Tutorial_Cover.jpg
:height: 100pt
:width: 100pt
* :ref:`laplace_operator`
===================== ==============================================
|LaplaceOperator| *Title:* **Laplace Operator**
*Compatibility:* > OpenCV 2.0
*Author:* |Author_AnaH|
Where we learn about the *Laplace* operator and how to detect edges with it.
===================== ==============================================
.. |LaplaceOperator| image:: images/imgtrans/Laplace_Operator_Tutorial_Cover.jpg
:height: 100pt
:width: 100pt
* :ref:`canny_detector`
===================== ==============================================
|CannyDetector| *Title:* **Canny Edge Detector**
*Compatibility:* > OpenCV 2.0
*Author:* |Author_AnaH|
Where we learn a sophisticated alternative to detect edges.
===================== ==============================================
.. |CannyDetector| image:: images/imgtrans/Canny_Detector_Tutorial_Cover.jpg
:height: 100pt
:width: 100pt
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册