mirror of
https://github.com/opencv/opencv.git
synced 2026-07-30 15:53:03 +04:00
Removed Sphinx documentation files
This commit is contained in:
@@ -1,110 +0,0 @@
|
||||
ColorMaps in OpenCV
|
||||
===================
|
||||
|
||||
applyColorMap
|
||||
-------------
|
||||
|
||||
Applies a GNU Octave/MATLAB equivalent colormap on a given image.
|
||||
|
||||
.. ocv:function:: void applyColorMap(InputArray src, OutputArray dst, int colormap)
|
||||
|
||||
:param src: The source image, grayscale or colored does not matter.
|
||||
:param dst: The result is the colormapped source image. Note: :ocv:func:`Mat::create` is called on dst.
|
||||
:param colormap: The colormap to apply, see the list of available colormaps below.
|
||||
|
||||
Currently the following GNU Octave/MATLAB equivalent colormaps are implemented:
|
||||
|
||||
.. code-block:: cpp
|
||||
|
||||
enum
|
||||
{
|
||||
COLORMAP_AUTUMN = 0,
|
||||
COLORMAP_BONE = 1,
|
||||
COLORMAP_JET = 2,
|
||||
COLORMAP_WINTER = 3,
|
||||
COLORMAP_RAINBOW = 4,
|
||||
COLORMAP_OCEAN = 5,
|
||||
COLORMAP_SUMMER = 6,
|
||||
COLORMAP_SPRING = 7,
|
||||
COLORMAP_COOL = 8,
|
||||
COLORMAP_HSV = 9,
|
||||
COLORMAP_PINK = 10,
|
||||
COLORMAP_HOT = 11
|
||||
}
|
||||
|
||||
|
||||
Description
|
||||
===========
|
||||
|
||||
The human perception isn't built for observing fine changes in grayscale images. Human eyes are more sensitive to observing changes between colors, so you often need to recolor your grayscale images to get a clue about them. OpenCV now comes with various colormaps to enhance the visualization in your computer vision application.
|
||||
|
||||
In OpenCV you only need :ocv:func:`applyColorMap` to apply a colormap on a given image. The following sample code reads the path to an image from command line, applies a Jet colormap on it and shows the result:
|
||||
|
||||
.. code-block:: cpp
|
||||
|
||||
#include <opencv2/core.hpp>
|
||||
#include <opencv2/imgproc.hpp>
|
||||
#include <opencv2/imgcodecs.hpp>
|
||||
#include <opencv2/highgui.hpp>
|
||||
using namespace cv;
|
||||
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
int main(int argc, const char *argv[])
|
||||
{
|
||||
// We need an input image. (can be grayscale or color)
|
||||
if (argc < 2)
|
||||
{
|
||||
cerr << "We need an image to process here. Please run: colorMap [path_to_image]" << endl;
|
||||
return -1;
|
||||
}
|
||||
|
||||
Mat img_in = imread(argv[1]);
|
||||
|
||||
if(img_in.empty())
|
||||
{
|
||||
cerr << "Sample image (" << argv[1] << ") is empty. Please adjust your path, so it points to a valid input image!" << endl;
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Holds the colormap version of the image:
|
||||
Mat img_color;
|
||||
// Apply the colormap:
|
||||
applyColorMap(img_in, img_color, COLORMAP_JET);
|
||||
// Show the result:
|
||||
imshow("colorMap", img_color);
|
||||
waitKey(0);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
And here are the color scales for each of the available colormaps:
|
||||
|
||||
+-----------------------+---------------------------------------------------+
|
||||
| Class | Scale |
|
||||
+=======================+===================================================+
|
||||
| COLORMAP_AUTUMN | .. image:: pics/colormaps/colorscale_autumn.jpg |
|
||||
+-----------------------+---------------------------------------------------+
|
||||
| COLORMAP_BONE | .. image:: pics/colormaps/colorscale_bone.jpg |
|
||||
+-----------------------+---------------------------------------------------+
|
||||
| COLORMAP_COOL | .. image:: pics/colormaps/colorscale_cool.jpg |
|
||||
+-----------------------+---------------------------------------------------+
|
||||
| COLORMAP_HOT | .. image:: pics/colormaps/colorscale_hot.jpg |
|
||||
+-----------------------+---------------------------------------------------+
|
||||
| COLORMAP_HSV | .. image:: pics/colormaps/colorscale_hsv.jpg |
|
||||
+-----------------------+---------------------------------------------------+
|
||||
| COLORMAP_JET | .. image:: pics/colormaps/colorscale_jet.jpg |
|
||||
+-----------------------+---------------------------------------------------+
|
||||
| COLORMAP_OCEAN | .. image:: pics/colormaps/colorscale_ocean.jpg |
|
||||
+-----------------------+---------------------------------------------------+
|
||||
| COLORMAP_PINK | .. image:: pics/colormaps/colorscale_pink.jpg |
|
||||
+-----------------------+---------------------------------------------------+
|
||||
| COLORMAP_RAINBOW | .. image:: pics/colormaps/colorscale_rainbow.jpg |
|
||||
+-----------------------+---------------------------------------------------+
|
||||
| COLORMAP_SPRING | .. image:: pics/colormaps/colorscale_spring.jpg |
|
||||
+-----------------------+---------------------------------------------------+
|
||||
| COLORMAP_SUMMER | .. image:: pics/colormaps/colorscale_summer.jpg |
|
||||
+-----------------------+---------------------------------------------------+
|
||||
| COLORMAP_WINTER | .. image:: pics/colormaps/colorscale_winter.jpg |
|
||||
+-----------------------+---------------------------------------------------+
|
||||
@@ -1,634 +0,0 @@
|
||||
Drawing Functions
|
||||
=================
|
||||
|
||||
.. highlight:: cpp
|
||||
|
||||
Drawing functions work with matrices/images of arbitrary depth.
|
||||
The boundaries of the shapes can be rendered with antialiasing (implemented only for 8-bit images for now).
|
||||
All the functions include the parameter ``color`` that uses an RGB value (that may be constructed
|
||||
with the ``Scalar`` constructor
|
||||
) for color
|
||||
images and brightness for grayscale images. For color images, the channel ordering
|
||||
is normally *Blue, Green, Red*.
|
||||
This is what :ocv:func:`imshow`, :ocv:func:`imread`, and :ocv:func:`imwrite` expect.
|
||||
So, if you form a color using the
|
||||
``Scalar`` constructor, it should look like:
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{Scalar} (blue \_ component, green \_ component, red \_ component[, alpha \_ component])
|
||||
|
||||
If you are using your own image rendering and I/O functions, you can use any channel ordering. The drawing functions process each channel independently and do not depend on the channel order or even on the used color space. The whole image can be converted from BGR to RGB or to a different color space using
|
||||
:ocv:func:`cvtColor` .
|
||||
|
||||
If a drawn figure is partially or completely outside the image, the drawing functions clip it. Also, many drawing functions can handle pixel coordinates specified with sub-pixel accuracy. This means that the coordinates can be passed as fixed-point numbers encoded as integers. The number of fractional bits is specified by the ``shift`` parameter and the real point coordinates are calculated as
|
||||
:math:`\texttt{Point}(x,y)\rightarrow\texttt{Point2f}(x*2^{-shift},y*2^{-shift})` . This feature is especially effective when rendering antialiased shapes.
|
||||
|
||||
.. note:: The functions do not support alpha-transparency when the target image is 4-channel. In this case, the ``color[3]`` is simply copied to the repainted pixels. Thus, if you want to paint semi-transparent shapes, you can paint them in a separate buffer and then blend it with the main image.
|
||||
|
||||
.. note::
|
||||
|
||||
* An example on using variate drawing functions like line, rectangle, ... can be found at opencv_source_code/samples/cpp/drawing.cpp
|
||||
|
||||
circle
|
||||
----------
|
||||
Draws a circle.
|
||||
|
||||
.. ocv:function:: void circle( InputOutputArray img, Point center, int radius, const Scalar& color, int thickness=1, int lineType=LINE_8, int shift=0 )
|
||||
|
||||
.. ocv:pyfunction:: cv2.circle(img, center, radius, color[, thickness[, lineType[, shift]]]) -> img
|
||||
|
||||
.. ocv:cfunction:: void cvCircle( CvArr* img, CvPoint center, int radius, CvScalar color, int thickness=1, int line_type=8, int shift=0 )
|
||||
|
||||
:param img: Image where the circle is drawn.
|
||||
|
||||
:param center: Center of the circle.
|
||||
|
||||
:param radius: Radius of the circle.
|
||||
|
||||
:param color: Circle color.
|
||||
|
||||
:param thickness: Thickness of the circle outline, if positive. Negative thickness means that a filled circle is to be drawn.
|
||||
|
||||
:param lineType: Type of the circle boundary. See the :ocv:func:`line` description.
|
||||
|
||||
:param shift: Number of fractional bits in the coordinates of the center and in the radius value.
|
||||
|
||||
The function ``circle`` draws a simple or filled circle with a given center and radius.
|
||||
|
||||
clipLine
|
||||
------------
|
||||
Clips the line against the image rectangle.
|
||||
|
||||
.. ocv:function:: bool clipLine(Size imgSize, Point& pt1, Point& pt2)
|
||||
|
||||
.. ocv:function:: bool clipLine(Rect imgRect, Point& pt1, Point& pt2)
|
||||
|
||||
.. ocv:pyfunction:: cv2.clipLine(imgRect, pt1, pt2) -> retval, pt1, pt2
|
||||
|
||||
.. ocv:cfunction:: int cvClipLine( CvSize img_size, CvPoint* pt1, CvPoint* pt2 )
|
||||
|
||||
:param imgSize: Image size. The image rectangle is ``Rect(0, 0, imgSize.width, imgSize.height)`` .
|
||||
|
||||
:param imgRect: Image rectangle.
|
||||
|
||||
:param pt1: First line point.
|
||||
|
||||
:param pt2: Second line point.
|
||||
|
||||
The functions ``clipLine`` calculate a part of the line segment that is entirely within the specified rectangle.
|
||||
They return ``false`` if the line segment is completely outside the rectangle. Otherwise, they return ``true`` .
|
||||
|
||||
ellipse
|
||||
-----------
|
||||
Draws a simple or thick elliptic arc or fills an ellipse sector.
|
||||
|
||||
.. ocv:function:: void ellipse( InputOutputArray img, Point center, Size axes, double angle, double startAngle, double endAngle, const Scalar& color, int thickness=1, int lineType=LINE_8, int shift=0 )
|
||||
|
||||
.. ocv:function:: void ellipse( InputOutputArray img, const RotatedRect& box, const Scalar& color, int thickness=1, int lineType=LINE_8 )
|
||||
|
||||
.. ocv:pyfunction:: cv2.ellipse(img, center, axes, angle, startAngle, endAngle, color[, thickness[, lineType[, shift]]]) -> img
|
||||
|
||||
.. ocv:pyfunction:: cv2.ellipse(img, box, color[, thickness[, lineType]]) -> img
|
||||
|
||||
.. ocv:cfunction:: void cvEllipse( CvArr* img, CvPoint center, CvSize axes, double angle, double start_angle, double end_angle, CvScalar color, int thickness=1, int line_type=8, int shift=0 )
|
||||
|
||||
.. ocv:cfunction:: void cvEllipseBox( CvArr* img, CvBox2D box, CvScalar color, int thickness=1, int line_type=8, int shift=0 )
|
||||
|
||||
:param img: Image.
|
||||
|
||||
:param center: Center of the ellipse.
|
||||
|
||||
:param axes: Half of the size of the ellipse main axes.
|
||||
|
||||
:param angle: Ellipse rotation angle in degrees.
|
||||
|
||||
:param startAngle: Starting angle of the elliptic arc in degrees.
|
||||
|
||||
:param endAngle: Ending angle of the elliptic arc in degrees.
|
||||
|
||||
:param box: Alternative ellipse representation via :ocv:class:`RotatedRect` or ``CvBox2D``. This means that the function draws an ellipse inscribed in the rotated rectangle.
|
||||
|
||||
:param color: Ellipse color.
|
||||
|
||||
:param thickness: Thickness of the ellipse arc outline, if positive. Otherwise, this indicates that a filled ellipse sector is to be drawn.
|
||||
|
||||
:param lineType: Type of the ellipse boundary. See the :ocv:func:`line` description.
|
||||
|
||||
:param shift: Number of fractional bits in the coordinates of the center and values of axes.
|
||||
|
||||
The functions ``ellipse`` with less parameters draw an ellipse outline, a filled ellipse, an elliptic arc, or a filled ellipse sector.
|
||||
A piecewise-linear curve is used to approximate the elliptic arc boundary. If you need more control of the ellipse rendering, you can retrieve the curve using
|
||||
:ocv:func:`ellipse2Poly` and then render it with
|
||||
:ocv:func:`polylines` or fill it with
|
||||
:ocv:func:`fillPoly` . If you use the first variant of the function and want to draw the whole ellipse, not an arc, pass ``startAngle=0`` and ``endAngle=360`` . The figure below explains the meaning of the parameters.
|
||||
|
||||
**Figure 1. Parameters of Elliptic Arc**
|
||||
|
||||
.. image:: pics/ellipse.png
|
||||
|
||||
ellipse2Poly
|
||||
----------------
|
||||
Approximates an elliptic arc with a polyline.
|
||||
|
||||
.. ocv:function:: void ellipse2Poly( Point center, Size axes, int angle, int arcStart, int arcEnd, int delta, vector<Point>& pts )
|
||||
|
||||
.. ocv:pyfunction:: cv2.ellipse2Poly(center, axes, angle, arcStart, arcEnd, delta) -> pts
|
||||
|
||||
:param center: Center of the arc.
|
||||
|
||||
:param axes: Half of the size of the ellipse main axes. See the :ocv:func:`ellipse` for details.
|
||||
|
||||
:param angle: Rotation angle of the ellipse in degrees. See the :ocv:func:`ellipse` for details.
|
||||
|
||||
:param arcStart: Starting angle of the elliptic arc in degrees.
|
||||
|
||||
:param arcEnd: Ending angle of the elliptic arc in degrees.
|
||||
|
||||
:param delta: Angle between the subsequent polyline vertices. It defines the approximation accuracy.
|
||||
|
||||
:param pts: Output vector of polyline vertices.
|
||||
|
||||
The function ``ellipse2Poly`` computes the vertices of a polyline that approximates the specified elliptic arc. It is used by
|
||||
:ocv:func:`ellipse` .
|
||||
|
||||
|
||||
fillConvexPoly
|
||||
------------------
|
||||
Fills a convex polygon.
|
||||
|
||||
.. ocv:function:: void fillConvexPoly( Mat& img, const Point* pts, int npts, const Scalar& color, int lineType=LINE_8, int shift=0 )
|
||||
|
||||
.. ocv:function:: void fillConvexPoly( InputOutputArray img, InputArray points, const Scalar& color, int lineType=LINE_8, int shift=0 )
|
||||
|
||||
.. ocv:pyfunction:: cv2.fillConvexPoly(img, points, color[, lineType[, shift]]) -> img
|
||||
|
||||
.. ocv:cfunction:: void cvFillConvexPoly( CvArr* img, const CvPoint* pts, int npts, CvScalar color, int line_type=8, int shift=0 )
|
||||
|
||||
:param img: Image.
|
||||
|
||||
:param pts: Polygon vertices.
|
||||
|
||||
:param npts: Number of polygon vertices.
|
||||
|
||||
:param color: Polygon color.
|
||||
|
||||
:param lineType: Type of the polygon boundaries. See the :ocv:func:`line` description.
|
||||
|
||||
:param shift: Number of fractional bits in the vertex coordinates.
|
||||
|
||||
The function ``fillConvexPoly`` draws a filled convex polygon.
|
||||
This function is much faster than the function ``fillPoly`` . It can fill not only convex polygons but any monotonic polygon without self-intersections,
|
||||
that is, a polygon whose contour intersects every horizontal line (scan line) twice at the most (though, its top-most and/or the bottom edge could be horizontal).
|
||||
|
||||
|
||||
|
||||
fillPoly
|
||||
------------
|
||||
Fills the area bounded by one or more polygons.
|
||||
|
||||
.. ocv:function:: void fillPoly( Mat& img, const Point** pts, const int* npts, int ncontours, const Scalar& color, int lineType=LINE_8, int shift=0, Point offset=Point() )
|
||||
|
||||
.. ocv:function:: void fillPoly( InputOutputArray img, InputArrayOfArrays pts, const Scalar& color, int lineType=LINE_8, int shift=0, Point offset=Point() )
|
||||
|
||||
.. ocv:pyfunction:: cv2.fillPoly(img, pts, color[, lineType[, shift[, offset]]]) -> img
|
||||
|
||||
.. ocv:cfunction:: void cvFillPoly( CvArr* img, CvPoint** pts, const int* npts, int contours, CvScalar color, int line_type=8, int shift=0 )
|
||||
|
||||
:param img: Image.
|
||||
|
||||
:param pts: Array of polygons where each polygon is represented as an array of points.
|
||||
|
||||
:param npts: Array of polygon vertex counters.
|
||||
|
||||
:param ncontours: Number of contours that bind the filled region.
|
||||
|
||||
:param color: Polygon color.
|
||||
|
||||
:param lineType: Type of the polygon boundaries. See the :ocv:func:`line` description.
|
||||
|
||||
:param shift: Number of fractional bits in the vertex coordinates.
|
||||
|
||||
:param offset: Optional offset of all points of the contours.
|
||||
|
||||
The function ``fillPoly`` fills an area bounded by several polygonal contours. The function can fill complex areas, for example,
|
||||
areas with holes, contours with self-intersections (some of their parts), and so forth.
|
||||
|
||||
|
||||
|
||||
getTextSize
|
||||
---------------
|
||||
Calculates the width and height of a text string.
|
||||
|
||||
.. ocv:function:: Size getTextSize(const String& text, int fontFace, double fontScale, int thickness, int* baseLine)
|
||||
|
||||
.. ocv:pyfunction:: cv2.getTextSize(text, fontFace, fontScale, thickness) -> retval, baseLine
|
||||
|
||||
.. ocv:cfunction:: void cvGetTextSize( const char* text_string, const CvFont* font, CvSize* text_size, int* baseline )
|
||||
|
||||
:param text: Input text string.
|
||||
|
||||
:param text_string: Input text string in C format.
|
||||
|
||||
:param fontFace: Font to use. See the :ocv:func:`putText` for details.
|
||||
|
||||
:param fontScale: Font scale. See the :ocv:func:`putText` for details.
|
||||
|
||||
:param thickness: Thickness of lines used to render the text. See :ocv:func:`putText` for details.
|
||||
|
||||
:param baseLine: Output parameter - y-coordinate of the baseline relative to the bottom-most text point.
|
||||
|
||||
:param baseline: Output parameter - y-coordinate of the baseline relative to the bottom-most text point.
|
||||
|
||||
:param font: Font description in terms of old C API.
|
||||
|
||||
:param text_size: Output parameter - The size of a box that contains the specified text.
|
||||
|
||||
The function ``getTextSize`` calculates and returns the size of a box that contains the specified text.
|
||||
That is, the following code renders some text, the tight box surrounding it, and the baseline: ::
|
||||
|
||||
String text = "Funny text inside the box";
|
||||
int fontFace = FONT_HERSHEY_SCRIPT_SIMPLEX;
|
||||
double fontScale = 2;
|
||||
int thickness = 3;
|
||||
|
||||
Mat img(600, 800, CV_8UC3, Scalar::all(0));
|
||||
|
||||
int baseline=0;
|
||||
Size textSize = getTextSize(text, fontFace,
|
||||
fontScale, thickness, &baseline);
|
||||
baseline += thickness;
|
||||
|
||||
// center the text
|
||||
Point textOrg((img.cols - textSize.width)/2,
|
||||
(img.rows + textSize.height)/2);
|
||||
|
||||
// draw the box
|
||||
rectangle(img, textOrg + Point(0, baseline),
|
||||
textOrg + Point(textSize.width, -textSize.height),
|
||||
Scalar(0,0,255));
|
||||
// ... and the baseline first
|
||||
line(img, textOrg + Point(0, thickness),
|
||||
textOrg + Point(textSize.width, thickness),
|
||||
Scalar(0, 0, 255));
|
||||
|
||||
// then put the text itself
|
||||
putText(img, text, textOrg, fontFace, fontScale,
|
||||
Scalar::all(255), thickness, 8);
|
||||
|
||||
|
||||
InitFont
|
||||
--------
|
||||
Initializes font structure (OpenCV 1.x API).
|
||||
|
||||
.. ocv:cfunction:: void cvInitFont( CvFont* font, int font_face, double hscale, double vscale, double shear=0, int thickness=1, int line_type=8 )
|
||||
|
||||
:param font: Pointer to the font structure initialized by the function
|
||||
|
||||
:param font_face: Font name identifier. Only a subset of Hershey fonts http://sources.isc.org/utils/misc/hershey-font.txt are supported now:
|
||||
|
||||
* **CV_FONT_HERSHEY_SIMPLEX** normal size sans-serif font
|
||||
|
||||
* **CV_FONT_HERSHEY_PLAIN** small size sans-serif font
|
||||
|
||||
* **CV_FONT_HERSHEY_DUPLEX** normal size sans-serif font (more complex than ``CV_FONT_HERSHEY_SIMPLEX`` )
|
||||
|
||||
* **CV_FONT_HERSHEY_COMPLEX** normal size serif font
|
||||
|
||||
* **CV_FONT_HERSHEY_TRIPLEX** normal size serif font (more complex than ``CV_FONT_HERSHEY_COMPLEX`` )
|
||||
|
||||
* **CV_FONT_HERSHEY_COMPLEX_SMALL** smaller version of ``CV_FONT_HERSHEY_COMPLEX``
|
||||
|
||||
* **CV_FONT_HERSHEY_SCRIPT_SIMPLEX** hand-writing style font
|
||||
|
||||
* **CV_FONT_HERSHEY_SCRIPT_COMPLEX** more complex variant of ``CV_FONT_HERSHEY_SCRIPT_SIMPLEX``
|
||||
|
||||
The parameter can be composited from one of the values above and an optional ``CV_FONT_ITALIC`` flag, which indicates italic or oblique font.
|
||||
|
||||
|
||||
:param hscale: Horizontal scale. If equal to ``1.0f`` , the characters have the original width depending on the font type. If equal to ``0.5f`` , the characters are of half the original width.
|
||||
|
||||
|
||||
:param vscale: Vertical scale. If equal to ``1.0f`` , the characters have the original height depending on the font type. If equal to ``0.5f`` , the characters are of half the original height.
|
||||
|
||||
|
||||
:param shear: Approximate tangent of the character slope relative to the vertical line. A zero value means a non-italic font, ``1.0f`` means about a 45 degree slope, etc.
|
||||
|
||||
|
||||
:param thickness: Thickness of the text strokes
|
||||
|
||||
|
||||
:param line_type: Type of the strokes, see :ocv:func:`line` description
|
||||
|
||||
|
||||
The function initializes the font structure that can be passed to text rendering functions.
|
||||
|
||||
.. seealso:: :ocv:cfunc:`PutText`
|
||||
|
||||
.. _Line:
|
||||
|
||||
line
|
||||
--------
|
||||
Draws a line segment connecting two points.
|
||||
|
||||
.. ocv:function:: void line( InputOutputArray img, Point pt1, Point pt2, const Scalar& color, int thickness=1, int lineType=LINE_8, int shift=0 )
|
||||
|
||||
.. ocv:pyfunction:: cv2.line(img, pt1, pt2, color[, thickness[, lineType[, shift]]]) -> img
|
||||
|
||||
.. ocv:cfunction:: void cvLine( CvArr* img, CvPoint pt1, CvPoint pt2, CvScalar color, int thickness=1, int line_type=8, int shift=0 )
|
||||
|
||||
:param img: Image.
|
||||
|
||||
:param pt1: First point of the line segment.
|
||||
|
||||
:param pt2: Second point of the line segment.
|
||||
|
||||
:param color: Line color.
|
||||
|
||||
:param thickness: Line thickness.
|
||||
|
||||
:param lineType: Type of the line:
|
||||
|
||||
* **LINE_8** (or omitted) - 8-connected line.
|
||||
|
||||
* **LINE_4** - 4-connected line.
|
||||
|
||||
* **LINE_AA** - antialiased line.
|
||||
|
||||
:param shift: Number of fractional bits in the point coordinates.
|
||||
|
||||
The function ``line`` draws the line segment between ``pt1`` and ``pt2`` points in the image. The line is clipped by the image boundaries. For non-antialiased lines with integer coordinates, the 8-connected or 4-connected Bresenham algorithm is used. Thick lines are drawn with rounding endings.
|
||||
Antialiased lines are drawn using Gaussian filtering.
|
||||
|
||||
|
||||
arrowedLine
|
||||
----------------
|
||||
Draws a arrow segment pointing from the first point to the second one.
|
||||
|
||||
.. ocv:function:: void arrowedLine(InputOutputArray img, Point pt1, Point pt2, const Scalar& color, int thickness=1, int lineType=8, int shift=0, double tipLength=0.1)
|
||||
|
||||
:param img: Image.
|
||||
|
||||
:param pt1: The point the arrow starts from.
|
||||
|
||||
:param pt2: The point the arrow points to.
|
||||
|
||||
:param color: Line color.
|
||||
|
||||
:param thickness: Line thickness.
|
||||
|
||||
:param lineType: Type of the line:
|
||||
|
||||
* **8** (or omitted) - 8-connected line.
|
||||
|
||||
* **4** - 4-connected line.
|
||||
|
||||
* **CV_AA** - antialiased line.
|
||||
|
||||
:param shift: Number of fractional bits in the point coordinates.
|
||||
|
||||
:param tipLength: The length of the arrow tip in relation to the arrow length
|
||||
|
||||
The function ``arrowedLine`` draws an arrow between ``pt1`` and ``pt2`` points in the image. See also :ocv:func:`line`.
|
||||
|
||||
|
||||
LineIterator
|
||||
------------
|
||||
.. ocv:class:: LineIterator
|
||||
|
||||
Class for iterating pixels on a raster line. ::
|
||||
|
||||
class LineIterator
|
||||
{
|
||||
public:
|
||||
// creates iterators for the line connecting pt1 and pt2
|
||||
// the line will be clipped on the image boundaries
|
||||
// the line is 8-connected or 4-connected
|
||||
// If leftToRight=true, then the iteration is always done
|
||||
// from the left-most point to the right most,
|
||||
// not to depend on the ordering of pt1 and pt2 parameters
|
||||
LineIterator(const Mat& img, Point pt1, Point pt2,
|
||||
int connectivity=8, bool leftToRight=false);
|
||||
// returns pointer to the current line pixel
|
||||
uchar* operator *();
|
||||
// move the iterator to the next pixel
|
||||
LineIterator& operator ++();
|
||||
LineIterator operator ++(int);
|
||||
Point pos() const;
|
||||
|
||||
// internal state of the iterator
|
||||
uchar* ptr;
|
||||
int err, count;
|
||||
int minusDelta, plusDelta;
|
||||
int minusStep, plusStep;
|
||||
};
|
||||
|
||||
The class ``LineIterator`` is used to get each pixel of a raster line. It can be treated as versatile implementation of the Bresenham algorithm where you can stop at each pixel and do some extra processing, for example, grab pixel values along the line or draw a line with an effect (for example, with XOR operation).
|
||||
|
||||
The number of pixels along the line is stored in ``LineIterator::count`` . The method ``LineIterator::pos`` returns the current position in the image ::
|
||||
|
||||
// grabs pixels along the line (pt1, pt2)
|
||||
// from 8-bit 3-channel image to the buffer
|
||||
LineIterator it(img, pt1, pt2, 8);
|
||||
LineIterator it2 = it;
|
||||
vector<Vec3b> buf(it.count);
|
||||
|
||||
for(int i = 0; i < it.count; i++, ++it)
|
||||
buf[i] = *(const Vec3b)*it;
|
||||
|
||||
// alternative way of iterating through the line
|
||||
for(int i = 0; i < it2.count; i++, ++it2)
|
||||
{
|
||||
Vec3b val = img.at<Vec3b>(it2.pos());
|
||||
CV_Assert(buf[i] == val);
|
||||
}
|
||||
|
||||
|
||||
rectangle
|
||||
-------------
|
||||
Draws a simple, thick, or filled up-right rectangle.
|
||||
|
||||
.. ocv:function:: void rectangle( InputOutputArray img, Point pt1, Point pt2, const Scalar& color, int thickness=1, int lineType=LINE_8, int shift=0 )
|
||||
|
||||
.. ocv:function:: void rectangle( Mat& img, Rect rec, const Scalar& color, int thickness=1, int lineType=LINE_8, int shift=0 )
|
||||
|
||||
.. ocv:pyfunction:: cv2.rectangle(img, pt1, pt2, color[, thickness[, lineType[, shift]]]) -> img
|
||||
|
||||
.. ocv:cfunction:: void cvRectangle( CvArr* img, CvPoint pt1, CvPoint pt2, CvScalar color, int thickness=1, int line_type=8, int shift=0 )
|
||||
|
||||
:param img: Image.
|
||||
|
||||
:param pt1: Vertex of the rectangle.
|
||||
|
||||
:param pt2: Vertex of the rectangle opposite to ``pt1`` .
|
||||
|
||||
:param rec: Alternative specification of the drawn rectangle.
|
||||
|
||||
:param color: Rectangle color or brightness (grayscale image).
|
||||
|
||||
:param thickness: Thickness of lines that make up the rectangle. Negative values, like ``CV_FILLED`` , mean that the function has to draw a filled rectangle.
|
||||
|
||||
:param lineType: Type of the line. See the :ocv:func:`line` description.
|
||||
|
||||
:param shift: Number of fractional bits in the point coordinates.
|
||||
|
||||
The function ``rectangle`` draws a rectangle outline or a filled rectangle whose two opposite corners are ``pt1`` and ``pt2``, or ``r.tl()`` and ``r.br()-Point(1,1)``.
|
||||
|
||||
|
||||
|
||||
polylines
|
||||
-------------
|
||||
Draws several polygonal curves.
|
||||
|
||||
.. ocv:function:: void polylines( Mat& img, const Point* const* pts, const int* npts, int ncontours, bool isClosed, const Scalar& color, int thickness=1, int lineType=LINE_8, int shift=0 )
|
||||
|
||||
.. ocv:function:: void polylines( InputOutputArray img, InputArrayOfArrays pts, bool isClosed, const Scalar& color, int thickness=1, int lineType=LINE_8, int shift=0 )
|
||||
|
||||
.. ocv:pyfunction:: cv2.polylines(img, pts, isClosed, color[, thickness[, lineType[, shift]]]) -> img
|
||||
|
||||
.. ocv:cfunction:: void cvPolyLine( CvArr* img, CvPoint** pts, const int* npts, int contours, int is_closed, CvScalar color, int thickness=1, int line_type=8, int shift=0 )
|
||||
|
||||
:param img: Image.
|
||||
|
||||
:param pts: Array of polygonal curves.
|
||||
|
||||
:param npts: Array of polygon vertex counters.
|
||||
|
||||
:param ncontours: Number of curves.
|
||||
|
||||
:param isClosed: Flag indicating whether the drawn polylines are closed or not. If they are closed, the function draws a line from the last vertex of each curve to its first vertex.
|
||||
|
||||
:param color: Polyline color.
|
||||
|
||||
:param thickness: Thickness of the polyline edges.
|
||||
|
||||
:param lineType: Type of the line segments. See the :ocv:func:`line` description.
|
||||
|
||||
:param shift: Number of fractional bits in the vertex coordinates.
|
||||
|
||||
The function ``polylines`` draws one or more polygonal curves.
|
||||
|
||||
|
||||
drawContours
|
||||
----------------
|
||||
Draws contours outlines or filled contours.
|
||||
|
||||
.. ocv:function:: void drawContours( InputOutputArray image, InputArrayOfArrays contours, int contourIdx, const Scalar& color, int thickness=1, int lineType=LINE_8, InputArray hierarchy=noArray(), int maxLevel=INT_MAX, Point offset=Point() )
|
||||
|
||||
.. ocv:pyfunction:: cv2.drawContours(image, contours, contourIdx, color[, thickness[, lineType[, hierarchy[, maxLevel[, offset]]]]]) -> image
|
||||
|
||||
.. ocv:cfunction:: void cvDrawContours( CvArr * img, CvSeq* contour, CvScalar external_color, CvScalar hole_color, int max_level, int thickness=1, int line_type=8, CvPoint offset=cvPoint(0,0) )
|
||||
|
||||
:param image: Destination image.
|
||||
|
||||
:param contours: All the input contours. Each contour is stored as a point vector.
|
||||
|
||||
:param contourIdx: Parameter indicating a contour to draw. If it is negative, all the contours are drawn.
|
||||
|
||||
:param color: Color of the contours.
|
||||
|
||||
:param thickness: Thickness of lines the contours are drawn with. If it is negative (for example, ``thickness=CV_FILLED`` ), the contour interiors are
|
||||
drawn.
|
||||
|
||||
:param lineType: Line connectivity. See :ocv:func:`line` for details.
|
||||
|
||||
:param hierarchy: Optional information about hierarchy. It is only needed if you want to draw only some of the contours (see ``maxLevel`` ).
|
||||
|
||||
:param maxLevel: Maximal level for drawn contours. If it is 0, only
|
||||
the specified contour is drawn. If it is 1, the function draws the contour(s) and all the nested contours. If it is 2, the function draws the contours, all the nested contours, all the nested-to-nested contours, and so on. This parameter is only taken into account when there is ``hierarchy`` available.
|
||||
|
||||
:param offset: Optional contour shift parameter. Shift all the drawn contours by the specified :math:`\texttt{offset}=(dx,dy)` .
|
||||
|
||||
:param contour: Pointer to the first contour.
|
||||
|
||||
:param external_color: Color of external contours.
|
||||
|
||||
:param hole_color: Color of internal contours (holes).
|
||||
|
||||
The function draws contour outlines in the image if
|
||||
:math:`\texttt{thickness} \ge 0` or fills the area bounded by the contours if
|
||||
:math:`\texttt{thickness}<0` . The example below shows how to retrieve connected components from the binary image and label them: ::
|
||||
|
||||
#include "opencv2/imgproc.hpp"
|
||||
#include "opencv2/highgui.hpp"
|
||||
|
||||
using namespace cv;
|
||||
using namespace std;
|
||||
|
||||
int main( int argc, char** argv )
|
||||
{
|
||||
Mat src;
|
||||
// the first command-line parameter must be a filename of the binary
|
||||
// (black-n-white) image
|
||||
if( argc != 2 || !(src=imread(argv[1], 0)).data)
|
||||
return -1;
|
||||
|
||||
Mat dst = Mat::zeros(src.rows, src.cols, CV_8UC3);
|
||||
|
||||
src = src > 1;
|
||||
namedWindow( "Source", 1 );
|
||||
imshow( "Source", src );
|
||||
|
||||
vector<vector<Point> > contours;
|
||||
vector<Vec4i> hierarchy;
|
||||
|
||||
findContours( src, contours, hierarchy,
|
||||
RETR_CCOMP, CHAIN_APPROX_SIMPLE );
|
||||
|
||||
// iterate through all the top-level contours,
|
||||
// draw each connected component with its own random color
|
||||
int idx = 0;
|
||||
for( ; idx >= 0; idx = hierarchy[idx][0] )
|
||||
{
|
||||
Scalar color( rand()&255, rand()&255, rand()&255 );
|
||||
drawContours( dst, contours, idx, color, FILLED, 8, hierarchy );
|
||||
}
|
||||
|
||||
namedWindow( "Components", 1 );
|
||||
imshow( "Components", dst );
|
||||
waitKey(0);
|
||||
}
|
||||
|
||||
.. note::
|
||||
|
||||
* An example using the drawContour functionality can be found at opencv_source_code/samples/cpp/contours2.cpp
|
||||
* An example using drawContours to clean up a background segmentation result at opencv_source_code/samples/cpp/segment_objects.cpp
|
||||
|
||||
* (Python) An example using the drawContour functionality can be found at opencv_source/samples/python2/contours.py
|
||||
|
||||
|
||||
putText
|
||||
-----------
|
||||
Draws a text string.
|
||||
|
||||
.. ocv:function:: void putText( InputOutputArray img, const String& text, Point org, int fontFace, double fontScale, Scalar color, int thickness=1, int lineType=LINE_8, bool bottomLeftOrigin=false )
|
||||
|
||||
.. ocv:pyfunction:: cv2.putText(img, text, org, fontFace, fontScale, color[, thickness[, lineType[, bottomLeftOrigin]]]) -> None
|
||||
|
||||
.. ocv:cfunction:: void cvPutText( CvArr* img, const char* text, CvPoint org, const CvFont* font, CvScalar color )
|
||||
|
||||
:param img: Image.
|
||||
|
||||
:param text: Text string to be drawn.
|
||||
|
||||
:param org: Bottom-left corner of the text string in the image.
|
||||
|
||||
:param font: ``CvFont`` structure initialized using :ocv:cfunc:`InitFont`.
|
||||
|
||||
:param fontFace: Font type. One of ``FONT_HERSHEY_SIMPLEX``, ``FONT_HERSHEY_PLAIN``, ``FONT_HERSHEY_DUPLEX``, ``FONT_HERSHEY_COMPLEX``, ``FONT_HERSHEY_TRIPLEX``, ``FONT_HERSHEY_COMPLEX_SMALL``, ``FONT_HERSHEY_SCRIPT_SIMPLEX``, or ``FONT_HERSHEY_SCRIPT_COMPLEX``,
|
||||
where each of the font ID's can be combined with ``FONT_ITALIC`` to get the slanted letters.
|
||||
|
||||
:param fontScale: Font scale factor that is multiplied by the font-specific base size.
|
||||
|
||||
:param color: Text color.
|
||||
|
||||
:param thickness: Thickness of the lines used to draw a text.
|
||||
|
||||
:param lineType: Line type. See the ``line`` for details.
|
||||
|
||||
:param bottomLeftOrigin: When true, the image data origin is at the bottom-left corner. Otherwise, it is at the top-left corner.
|
||||
|
||||
The function ``putText`` renders the specified text string in the image.
|
||||
Symbols that cannot be rendered using the specified font are
|
||||
replaced by question marks. See
|
||||
:ocv:func:`getTextSize` for a text rendering code example.
|
||||
@@ -1,662 +0,0 @@
|
||||
Feature Detection
|
||||
=================
|
||||
|
||||
.. highlight:: cpp
|
||||
|
||||
|
||||
|
||||
Canny
|
||||
---------
|
||||
Finds edges in an image using the [Canny86]_ algorithm.
|
||||
|
||||
.. ocv:function:: void Canny( InputArray image, OutputArray edges, double threshold1, double threshold2, int apertureSize=3, bool L2gradient=false )
|
||||
|
||||
.. ocv:pyfunction:: cv2.Canny(image, threshold1, threshold2[, edges[, apertureSize[, L2gradient]]]) -> edges
|
||||
|
||||
.. ocv:cfunction:: void cvCanny( const CvArr* image, CvArr* edges, double threshold1, double threshold2, int aperture_size=3 )
|
||||
|
||||
:param image: 8-bit input image.
|
||||
|
||||
:param edges: output edge map; single channels 8-bit image, which has the same size as ``image`` .
|
||||
|
||||
:param threshold1: first threshold for the hysteresis procedure.
|
||||
|
||||
:param threshold2: second threshold for the hysteresis procedure.
|
||||
|
||||
:param apertureSize: aperture size for the :ocv:func:`Sobel` operator.
|
||||
|
||||
:param L2gradient: a flag, indicating whether a more accurate :math:`L_2` norm :math:`=\sqrt{(dI/dx)^2 + (dI/dy)^2}` should be used to calculate the image gradient magnitude ( ``L2gradient=true`` ), or whether the default :math:`L_1` norm :math:`=|dI/dx|+|dI/dy|` is enough ( ``L2gradient=false`` ).
|
||||
|
||||
The function finds edges in the input image ``image`` and marks them in the output map ``edges`` using the Canny algorithm. The smallest value between ``threshold1`` and ``threshold2`` is used for edge linking. The largest value is used to find initial segments of strong edges. See
|
||||
http://en.wikipedia.org/wiki/Canny_edge_detector
|
||||
|
||||
.. note::
|
||||
|
||||
* An example on using the canny edge detector can be found at opencv_source_code/samples/cpp/edge.cpp
|
||||
|
||||
* (Python) An example on using the canny edge detector can be found at opencv_source_code/samples/python/edge.py
|
||||
|
||||
cornerEigenValsAndVecs
|
||||
----------------------
|
||||
Calculates eigenvalues and eigenvectors of image blocks for corner detection.
|
||||
|
||||
.. ocv:function:: void cornerEigenValsAndVecs( InputArray src, OutputArray dst, int blockSize, int ksize, int borderType=BORDER_DEFAULT )
|
||||
|
||||
.. ocv:pyfunction:: cv2.cornerEigenValsAndVecs(src, blockSize, ksize[, dst[, borderType]]) -> dst
|
||||
|
||||
.. ocv:cfunction:: void cvCornerEigenValsAndVecs( const CvArr* image, CvArr* eigenvv, int block_size, int aperture_size=3 )
|
||||
|
||||
:param src: Input single-channel 8-bit or floating-point image.
|
||||
|
||||
:param dst: Image to store the results. It has the same size as ``src`` and the type ``CV_32FC(6)`` .
|
||||
|
||||
:param blockSize: Neighborhood size (see details below).
|
||||
|
||||
:param ksize: Aperture parameter for the :ocv:func:`Sobel` operator.
|
||||
|
||||
:param borderType: Pixel extrapolation method. See :ocv:func:`borderInterpolate` .
|
||||
|
||||
For every pixel
|
||||
:math:`p` , the function ``cornerEigenValsAndVecs`` considers a ``blockSize`` :math:`\times` ``blockSize`` neighborhood
|
||||
:math:`S(p)` . It calculates the covariation matrix of derivatives over the neighborhood as:
|
||||
|
||||
.. math::
|
||||
|
||||
M = \begin{bmatrix} \sum _{S(p)}(dI/dx)^2 & \sum _{S(p)}dI/dx dI/dy \\ \sum _{S(p)}dI/dx dI/dy & \sum _{S(p)}(dI/dy)^2 \end{bmatrix}
|
||||
|
||||
where the derivatives are computed using the
|
||||
:ocv:func:`Sobel` operator.
|
||||
|
||||
After that, it finds eigenvectors and eigenvalues of
|
||||
:math:`M` and stores them in the destination image as
|
||||
:math:`(\lambda_1, \lambda_2, x_1, y_1, x_2, y_2)` where
|
||||
|
||||
* :math:`\lambda_1, \lambda_2` are the non-sorted eigenvalues of :math:`M`
|
||||
|
||||
* :math:`x_1, y_1` are the eigenvectors corresponding to :math:`\lambda_1`
|
||||
|
||||
* :math:`x_2, y_2` are the eigenvectors corresponding to :math:`\lambda_2`
|
||||
|
||||
The output of the function can be used for robust edge or corner detection.
|
||||
|
||||
.. seealso::
|
||||
|
||||
:ocv:func:`cornerMinEigenVal`,
|
||||
:ocv:func:`cornerHarris`,
|
||||
:ocv:func:`preCornerDetect`
|
||||
|
||||
.. note::
|
||||
|
||||
* (Python) An example on how to use eigenvectors and eigenvalues to estimate image texture flow direction can be found at opencv_source_code/samples/python2/texture_flow.py
|
||||
|
||||
cornerHarris
|
||||
------------
|
||||
Harris corner detector.
|
||||
|
||||
.. ocv:function:: void cornerHarris( InputArray src, OutputArray dst, int blockSize, int ksize, double k, int borderType=BORDER_DEFAULT )
|
||||
|
||||
.. ocv:pyfunction:: cv2.cornerHarris(src, blockSize, ksize, k[, dst[, borderType]]) -> dst
|
||||
|
||||
.. ocv:cfunction:: void cvCornerHarris( const CvArr* image, CvArr* harris_response, int block_size, int aperture_size=3, double k=0.04 )
|
||||
|
||||
:param src: Input single-channel 8-bit or floating-point image.
|
||||
|
||||
:param dst: Image to store the Harris detector responses. It has the type ``CV_32FC1`` and the same size as ``src`` .
|
||||
|
||||
:param blockSize: Neighborhood size (see the details on :ocv:func:`cornerEigenValsAndVecs` ).
|
||||
|
||||
:param ksize: Aperture parameter for the :ocv:func:`Sobel` operator.
|
||||
|
||||
:param k: Harris detector free parameter. See the formula below.
|
||||
|
||||
:param borderType: Pixel extrapolation method. See :ocv:func:`borderInterpolate` .
|
||||
|
||||
The function runs the Harris corner detector on the image. Similarly to
|
||||
:ocv:func:`cornerMinEigenVal` and
|
||||
:ocv:func:`cornerEigenValsAndVecs` , for each pixel
|
||||
:math:`(x, y)` it calculates a
|
||||
:math:`2\times2` gradient covariance matrix
|
||||
:math:`M^{(x,y)}` over a
|
||||
:math:`\texttt{blockSize} \times \texttt{blockSize}` neighborhood. Then, it computes the following characteristic:
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{dst} (x,y) = \mathrm{det} M^{(x,y)} - k \cdot \left ( \mathrm{tr} M^{(x,y)} \right )^2
|
||||
|
||||
Corners in the image can be found as the local maxima of this response map.
|
||||
|
||||
|
||||
|
||||
cornerMinEigenVal
|
||||
-----------------
|
||||
Calculates the minimal eigenvalue of gradient matrices for corner detection.
|
||||
|
||||
.. ocv:function:: void cornerMinEigenVal( InputArray src, OutputArray dst, int blockSize, int ksize=3, int borderType=BORDER_DEFAULT )
|
||||
|
||||
.. ocv:pyfunction:: cv2.cornerMinEigenVal(src, blockSize[, dst[, ksize[, borderType]]]) -> dst
|
||||
|
||||
.. ocv:cfunction:: void cvCornerMinEigenVal( const CvArr* image, CvArr* eigenval, int block_size, int aperture_size=3 )
|
||||
|
||||
:param src: Input single-channel 8-bit or floating-point image.
|
||||
|
||||
:param dst: Image to store the minimal eigenvalues. It has the type ``CV_32FC1`` and the same size as ``src`` .
|
||||
|
||||
:param blockSize: Neighborhood size (see the details on :ocv:func:`cornerEigenValsAndVecs` ).
|
||||
|
||||
:param ksize: Aperture parameter for the :ocv:func:`Sobel` operator.
|
||||
|
||||
:param borderType: Pixel extrapolation method. See :ocv:func:`borderInterpolate` .
|
||||
|
||||
The function is similar to
|
||||
:ocv:func:`cornerEigenValsAndVecs` but it calculates and stores only the minimal eigenvalue of the covariance matrix of derivatives, that is,
|
||||
:math:`\min(\lambda_1, \lambda_2)` in terms of the formulae in the
|
||||
:ocv:func:`cornerEigenValsAndVecs` description.
|
||||
|
||||
|
||||
|
||||
cornerSubPix
|
||||
----------------
|
||||
Refines the corner locations.
|
||||
|
||||
.. ocv:function:: void cornerSubPix( InputArray image, InputOutputArray corners, Size winSize, Size zeroZone, TermCriteria criteria )
|
||||
|
||||
.. ocv:pyfunction:: cv2.cornerSubPix(image, corners, winSize, zeroZone, criteria) -> corners
|
||||
|
||||
.. ocv:cfunction:: void cvFindCornerSubPix( const CvArr* image, CvPoint2D32f* corners, int count, CvSize win, CvSize zero_zone, CvTermCriteria criteria )
|
||||
|
||||
:param image: Input image.
|
||||
|
||||
:param corners: Initial coordinates of the input corners and refined coordinates provided for output.
|
||||
|
||||
:param winSize: Half of the side length of the search window. For example, if ``winSize=Size(5,5)`` , then a :math:`5*2+1 \times 5*2+1 = 11 \times 11` search window is used.
|
||||
|
||||
:param zeroZone: Half of the size of the dead region in the middle of the search zone over which the summation in the formula below is not done. It is used sometimes to avoid possible singularities of the autocorrelation matrix. The value of (-1,-1) indicates that there is no such a size.
|
||||
|
||||
:param criteria: Criteria for termination of the iterative process of corner refinement. That is, the process of corner position refinement stops either after ``criteria.maxCount`` iterations or when the corner position moves by less than ``criteria.epsilon`` on some iteration.
|
||||
|
||||
The function iterates to find the sub-pixel accurate location of corners or radial saddle points, as shown on the figure below.
|
||||
|
||||
.. image:: pics/cornersubpix.png
|
||||
|
||||
Sub-pixel accurate corner locator is based on the observation that every vector from the center
|
||||
:math:`q` to a point
|
||||
:math:`p` located within a neighborhood of
|
||||
:math:`q` is orthogonal to the image gradient at
|
||||
:math:`p` subject to image and measurement noise. Consider the expression:
|
||||
|
||||
.. math::
|
||||
|
||||
\epsilon _i = {DI_{p_i}}^T \cdot (q - p_i)
|
||||
|
||||
where
|
||||
:math:`{DI_{p_i}}` is an image gradient at one of the points
|
||||
:math:`p_i` in a neighborhood of
|
||||
:math:`q` . The value of
|
||||
:math:`q` is to be found so that
|
||||
:math:`\epsilon_i` is minimized. A system of equations may be set up with
|
||||
:math:`\epsilon_i` set to zero:
|
||||
|
||||
.. math::
|
||||
|
||||
\sum _i(DI_{p_i} \cdot {DI_{p_i}}^T) - \sum _i(DI_{p_i} \cdot {DI_{p_i}}^T \cdot p_i)
|
||||
|
||||
where the gradients are summed within a neighborhood ("search window") of
|
||||
:math:`q` . Calling the first gradient term
|
||||
:math:`G` and the second gradient term
|
||||
:math:`b` gives:
|
||||
|
||||
.. math::
|
||||
|
||||
q = G^{-1} \cdot b
|
||||
|
||||
The algorithm sets the center of the neighborhood window at this new center
|
||||
:math:`q` and then iterates until the center stays within a set threshold.
|
||||
|
||||
|
||||
|
||||
goodFeaturesToTrack
|
||||
-------------------
|
||||
Determines strong corners on an image.
|
||||
|
||||
.. ocv:function:: void goodFeaturesToTrack( InputArray image, OutputArray corners, int maxCorners, double qualityLevel, double minDistance, InputArray mask=noArray(), int blockSize=3, bool useHarrisDetector=false, double k=0.04 )
|
||||
|
||||
.. ocv:pyfunction:: cv2.goodFeaturesToTrack(image, maxCorners, qualityLevel, minDistance[, corners[, mask[, blockSize[, useHarrisDetector[, k]]]]]) -> corners
|
||||
|
||||
.. ocv:cfunction:: void cvGoodFeaturesToTrack( const CvArr* image, CvArr* eig_image, CvArr* temp_image, CvPoint2D32f* corners, int* corner_count, double quality_level, double min_distance, const CvArr* mask=NULL, int block_size=3, int use_harris=0, double k=0.04 )
|
||||
|
||||
:param image: Input 8-bit or floating-point 32-bit, single-channel image.
|
||||
|
||||
:param eig_image: The parameter is ignored.
|
||||
|
||||
:param temp_image: The parameter is ignored.
|
||||
|
||||
:param corners: Output vector of detected corners.
|
||||
|
||||
:param maxCorners: Maximum number of corners to return. If there are more corners than are found, the strongest of them is returned.
|
||||
|
||||
:param qualityLevel: Parameter characterizing the minimal accepted quality of image corners. The parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue (see :ocv:func:`cornerMinEigenVal` ) or the Harris function response (see :ocv:func:`cornerHarris` ). The corners with the quality measure less than the product are rejected. For example, if the best corner has the quality measure = 1500, and the ``qualityLevel=0.01`` , then all the corners with the quality measure less than 15 are rejected.
|
||||
|
||||
:param minDistance: Minimum possible Euclidean distance between the returned corners.
|
||||
|
||||
:param mask: Optional region of interest. If the image is not empty (it needs to have the type ``CV_8UC1`` and the same size as ``image`` ), it specifies the region in which the corners are detected.
|
||||
|
||||
:param blockSize: Size of an average block for computing a derivative covariation matrix over each pixel neighborhood. See :ocv:func:`cornerEigenValsAndVecs` .
|
||||
|
||||
:param useHarrisDetector: Parameter indicating whether to use a Harris detector (see :ocv:func:`cornerHarris`) or :ocv:func:`cornerMinEigenVal`.
|
||||
|
||||
:param k: Free parameter of the Harris detector.
|
||||
|
||||
The function finds the most prominent corners in the image or in the specified image region, as described in [Shi94]_:
|
||||
|
||||
#.
|
||||
Function calculates the corner quality measure at every source image pixel using the
|
||||
:ocv:func:`cornerMinEigenVal` or
|
||||
:ocv:func:`cornerHarris` .
|
||||
|
||||
#.
|
||||
Function performs a non-maximum suppression (the local maximums in *3 x 3* neighborhood are retained).
|
||||
|
||||
#.
|
||||
The corners with the minimal eigenvalue less than
|
||||
:math:`\texttt{qualityLevel} \cdot \max_{x,y} qualityMeasureMap(x,y)` are rejected.
|
||||
|
||||
#.
|
||||
The remaining corners are sorted by the quality measure in the descending order.
|
||||
|
||||
#.
|
||||
Function throws away each corner for which there is a stronger corner at a distance less than ``maxDistance``.
|
||||
|
||||
The function can be used to initialize a point-based tracker of an object.
|
||||
|
||||
.. note:: If the function is called with different values ``A`` and ``B`` of the parameter ``qualityLevel`` , and ``A`` > ``B``, the vector of returned corners with ``qualityLevel=A`` will be the prefix of the output vector with ``qualityLevel=B`` .
|
||||
|
||||
.. seealso::
|
||||
|
||||
:ocv:func:`cornerMinEigenVal`,
|
||||
:ocv:func:`cornerHarris`,
|
||||
:ocv:func:`calcOpticalFlowPyrLK`,
|
||||
:ocv:func:`estimateRigidTransform`,
|
||||
|
||||
|
||||
HoughCircles
|
||||
------------
|
||||
Finds circles in a grayscale image using a modification of the Hough transform.
|
||||
|
||||
.. ocv:function:: void HoughCircles( InputArray image, OutputArray circles, int method, double dp, double minDist, double param1=100, double param2=100, int minRadius=0, int maxRadius=0 )
|
||||
|
||||
.. ocv:cfunction:: CvSeq* cvHoughCircles( CvArr* image, void* circle_storage, int method, double dp, double min_dist, double param1=100, double param2=100, int min_radius=0, int max_radius=0 )
|
||||
|
||||
.. ocv:pyfunction:: cv2.HoughCircles(image, method, dp, minDist[, circles[, param1[, param2[, minRadius[, maxRadius]]]]]) -> circles
|
||||
|
||||
:param image: 8-bit, single-channel, grayscale input image.
|
||||
|
||||
:param circles: Output vector of found circles. Each vector is encoded as a 3-element floating-point vector :math:`(x, y, radius)` .
|
||||
|
||||
:param circle_storage: In C function this is a memory storage that will contain the output sequence of found circles.
|
||||
|
||||
:param method: Detection method to use. Currently, the only implemented method is ``CV_HOUGH_GRADIENT`` , which is basically *21HT* , described in [Yuen90]_.
|
||||
|
||||
:param dp: Inverse ratio of the accumulator resolution to the image resolution. For example, if ``dp=1`` , the accumulator has the same resolution as the input image. If ``dp=2`` , the accumulator has half as big width and height.
|
||||
|
||||
:param minDist: Minimum distance between the centers of the detected circles. If the parameter is too small, multiple neighbor circles may be falsely detected in addition to a true one. If it is too large, some circles may be missed.
|
||||
|
||||
:param param1: First method-specific parameter. In case of ``CV_HOUGH_GRADIENT`` , it is the higher threshold of the two passed to the :ocv:func:`Canny` edge detector (the lower one is twice smaller).
|
||||
|
||||
:param param2: Second method-specific parameter. In case of ``CV_HOUGH_GRADIENT`` , it is the accumulator threshold for the circle centers at the detection stage. The smaller it is, the more false circles may be detected. Circles, corresponding to the larger accumulator values, will be returned first.
|
||||
|
||||
:param minRadius: Minimum circle radius.
|
||||
|
||||
:param maxRadius: Maximum circle radius.
|
||||
|
||||
Example: ::
|
||||
|
||||
#include <opencv2/imgproc.hpp>
|
||||
#include <opencv2/highgui.hpp>
|
||||
#include <math.h>
|
||||
|
||||
using namespace cv;
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
Mat img, gray;
|
||||
if( argc != 2 && !(img=imread(argv[1], 1)).data)
|
||||
return -1;
|
||||
cvtColor(img, gray, COLOR_BGR2GRAY);
|
||||
// smooth it, otherwise a lot of false circles may be detected
|
||||
GaussianBlur( gray, gray, Size(9, 9), 2, 2 );
|
||||
vector<Vec3f> circles;
|
||||
HoughCircles(gray, circles, HOUGH_GRADIENT,
|
||||
2, gray->rows/4, 200, 100 );
|
||||
for( size_t i = 0; i < circles.size(); i++ )
|
||||
{
|
||||
Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
|
||||
int radius = cvRound(circles[i][2]);
|
||||
// draw the circle center
|
||||
circle( img, center, 3, Scalar(0,255,0), -1, 8, 0 );
|
||||
// draw the circle outline
|
||||
circle( img, center, radius, Scalar(0,0,255), 3, 8, 0 );
|
||||
}
|
||||
namedWindow( "circles", 1 );
|
||||
imshow( "circles", img );
|
||||
return 0;
|
||||
}
|
||||
|
||||
.. note:: The elements of the output vector of found circles ("circles" in the above example) are sorted in descending order of accumulator values. This way, the centres with the most supporting pixels appear first.
|
||||
|
||||
.. note:: Usually the function detects the centers of circles well. However, it may fail to find correct radii. You can assist to the function by specifying the radius range ( ``minRadius`` and ``maxRadius`` ) if you know it. Or, you may ignore the returned radius, use only the center, and find the correct radius using an additional procedure.
|
||||
|
||||
.. seealso::
|
||||
|
||||
:ocv:func:`fitEllipse`,
|
||||
:ocv:func:`minEnclosingCircle`
|
||||
|
||||
.. note::
|
||||
|
||||
* An example using the Hough circle detector can be found at opencv_source_code/samples/cpp/houghcircles.cpp
|
||||
|
||||
HoughLines
|
||||
----------
|
||||
Finds lines in a binary image using the standard Hough transform.
|
||||
|
||||
.. ocv:function:: void HoughLines( InputArray image, OutputArray lines, double rho, double theta, int threshold, double srn=0, double stn=0, double min_theta=0, double max_theta=CV_PI )
|
||||
|
||||
.. ocv:pyfunction:: cv2.HoughLines(image, rho, theta, threshold[, lines[, srn[, stn[, min_theta[, max_theta]]]]]) -> lines
|
||||
|
||||
.. ocv:cfunction:: CvSeq* cvHoughLines2( CvArr* image, void* line_storage, int method, double rho, double theta, int threshold, double param1=0, double param2=0, double min_theta=0, double max_theta=CV_PI )
|
||||
|
||||
:param image: 8-bit, single-channel binary source image. The image may be modified by the function.
|
||||
|
||||
:param lines: Output vector of lines. Each line is represented by a two-element vector :math:`(\rho, \theta)` . :math:`\rho` is the distance from the coordinate origin :math:`(0,0)` (top-left corner of the image). :math:`\theta` is the line rotation angle in radians ( :math:`0 \sim \textrm{vertical line}, \pi/2 \sim \textrm{horizontal line}` ).
|
||||
|
||||
:param rho: Distance resolution of the accumulator in pixels.
|
||||
|
||||
:param theta: Angle resolution of the accumulator in radians.
|
||||
|
||||
:param threshold: Accumulator threshold parameter. Only those lines are returned that get enough votes ( :math:`>\texttt{threshold}` ).
|
||||
|
||||
:param srn: For the multi-scale Hough transform, it is a divisor for the distance resolution ``rho`` . The coarse accumulator distance resolution is ``rho`` and the accurate accumulator resolution is ``rho/srn`` . If both ``srn=0`` and ``stn=0`` , the classical Hough transform is used. Otherwise, both these parameters should be positive.
|
||||
|
||||
:param stn: For the multi-scale Hough transform, it is a divisor for the distance resolution ``theta``.
|
||||
|
||||
:param min_theta: For standard and multi-scale Hough transform, minimum angle to check for lines. Must fall between 0 and max_theta.
|
||||
|
||||
:param max_theta: For standard and multi-scale Hough transform, maximum angle to check for lines. Must fall between min_theta and CV_PI.
|
||||
|
||||
:param method: One of the following Hough transform variants:
|
||||
|
||||
* **CV_HOUGH_STANDARD** classical or standard Hough transform. Every line is represented by two floating-point numbers :math:`(\rho, \theta)` , where :math:`\rho` is a distance between (0,0) point and the line, and :math:`\theta` is the angle between x-axis and the normal to the line. Thus, the matrix must be (the created sequence will be) of ``CV_32FC2`` type
|
||||
|
||||
|
||||
* **CV_HOUGH_PROBABILISTIC** probabilistic Hough transform (more efficient in case if the picture contains a few long linear segments). It returns line segments rather than the whole line. Each segment is represented by starting and ending points, and the matrix must be (the created sequence will be) of the ``CV_32SC4`` type.
|
||||
|
||||
* **CV_HOUGH_MULTI_SCALE** multi-scale variant of the classical Hough transform. The lines are encoded the same way as ``CV_HOUGH_STANDARD``.
|
||||
|
||||
|
||||
:param param1: First method-dependent parameter:
|
||||
|
||||
* For the classical Hough transform, it is not used (0).
|
||||
|
||||
* For the probabilistic Hough transform, it is the minimum line length.
|
||||
|
||||
* For the multi-scale Hough transform, it is ``srn``.
|
||||
|
||||
:param param2: Second method-dependent parameter:
|
||||
|
||||
* For the classical Hough transform, it is not used (0).
|
||||
|
||||
* For the probabilistic Hough transform, it is the maximum gap between line segments lying on the same line to treat them as a single line segment (that is, to join them).
|
||||
|
||||
* For the multi-scale Hough transform, it is ``stn``.
|
||||
|
||||
The function implements the standard or standard multi-scale Hough transform algorithm for line detection. See http://homepages.inf.ed.ac.uk/rbf/HIPR2/hough.htm for a good explanation of Hough transform.
|
||||
See also the example in :ocv:func:`HoughLinesP` description.
|
||||
|
||||
.. note::
|
||||
|
||||
* An example using the Hough line detector can be found at opencv_source_code/samples/cpp/houghlines.cpp
|
||||
|
||||
HoughLinesP
|
||||
-----------
|
||||
Finds line segments in a binary image using the probabilistic Hough transform.
|
||||
|
||||
.. ocv:function:: void HoughLinesP( InputArray image, OutputArray lines, double rho, double theta, int threshold, double minLineLength=0, double maxLineGap=0 )
|
||||
|
||||
.. ocv:pyfunction:: cv2.HoughLinesP(image, rho, theta, threshold[, lines[, minLineLength[, maxLineGap]]]) -> lines
|
||||
|
||||
:param image: 8-bit, single-channel binary source image. The image may be modified by the function.
|
||||
|
||||
:param lines: Output vector of lines. Each line is represented by a 4-element vector :math:`(x_1, y_1, x_2, y_2)` , where :math:`(x_1,y_1)` and :math:`(x_2, y_2)` are the ending points of each detected line segment.
|
||||
|
||||
:param rho: Distance resolution of the accumulator in pixels.
|
||||
|
||||
:param theta: Angle resolution of the accumulator in radians.
|
||||
|
||||
:param threshold: Accumulator threshold parameter. Only those lines are returned that get enough votes ( :math:`>\texttt{threshold}` ).
|
||||
|
||||
:param minLineLength: Minimum line length. Line segments shorter than that are rejected.
|
||||
|
||||
:param maxLineGap: Maximum allowed gap between points on the same line to link them.
|
||||
|
||||
The function implements the probabilistic Hough transform algorithm for line detection, described in
|
||||
[Matas00]_. See the line detection example below: ::
|
||||
|
||||
/* This is a standalone program. Pass an image name as the first parameter
|
||||
of the program. Switch between standard and probabilistic Hough transform
|
||||
by changing "#if 1" to "#if 0" and back */
|
||||
#include <opencv2/imgproc.hpp>
|
||||
#include <opencv2/highgui.hpp>
|
||||
|
||||
using namespace cv;
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
Mat src, dst, color_dst;
|
||||
if( argc != 2 || !(src=imread(argv[1], 0)).data)
|
||||
return -1;
|
||||
|
||||
Canny( src, dst, 50, 200, 3 );
|
||||
cvtColor( dst, color_dst, COLOR_GRAY2BGR );
|
||||
|
||||
#if 0
|
||||
vector<Vec2f> lines;
|
||||
HoughLines( dst, lines, 1, CV_PI/180, 100 );
|
||||
|
||||
for( size_t i = 0; i < lines.size(); i++ )
|
||||
{
|
||||
float rho = lines[i][0];
|
||||
float theta = lines[i][1];
|
||||
double a = cos(theta), b = sin(theta);
|
||||
double x0 = a*rho, y0 = b*rho;
|
||||
Point pt1(cvRound(x0 + 1000*(-b)),
|
||||
cvRound(y0 + 1000*(a)));
|
||||
Point pt2(cvRound(x0 - 1000*(-b)),
|
||||
cvRound(y0 - 1000*(a)));
|
||||
line( color_dst, pt1, pt2, Scalar(0,0,255), 3, 8 );
|
||||
}
|
||||
#else
|
||||
vector<Vec4i> lines;
|
||||
HoughLinesP( dst, lines, 1, CV_PI/180, 80, 30, 10 );
|
||||
for( size_t i = 0; i < lines.size(); i++ )
|
||||
{
|
||||
line( color_dst, Point(lines[i][0], lines[i][1]),
|
||||
Point(lines[i][2], lines[i][3]), Scalar(0,0,255), 3, 8 );
|
||||
}
|
||||
#endif
|
||||
namedWindow( "Source", 1 );
|
||||
imshow( "Source", src );
|
||||
|
||||
namedWindow( "Detected Lines", 1 );
|
||||
imshow( "Detected Lines", color_dst );
|
||||
|
||||
waitKey(0);
|
||||
return 0;
|
||||
}
|
||||
|
||||
This is a sample picture the function parameters have been tuned for:
|
||||
|
||||
.. image:: pics/building.jpg
|
||||
|
||||
And this is the output of the above program in case of the probabilistic Hough transform:
|
||||
|
||||
.. image:: pics/houghp.png
|
||||
|
||||
.. seealso::
|
||||
|
||||
:ocv:class:`LineSegmentDetector`
|
||||
|
||||
|
||||
|
||||
LineSegmentDetector
|
||||
-------------------
|
||||
Line segment detector class, following the algorithm described at [Rafael12]_.
|
||||
|
||||
.. ocv:class:: LineSegmentDetector : public Algorithm
|
||||
|
||||
|
||||
createLineSegmentDetector
|
||||
-------------------------
|
||||
Creates a smart pointer to a LineSegmentDetector object and initializes it.
|
||||
|
||||
.. ocv:function:: Ptr<LineSegmentDetector> createLineSegmentDetector(int _refine = LSD_REFINE_STD, double _scale = 0.8, double _sigma_scale = 0.6, double _quant = 2.0, double _ang_th = 22.5, double _log_eps = 0, double _density_th = 0.7, int _n_bins = 1024)
|
||||
|
||||
.. ocv:pyfunction:: cv2.createLineSegmentDetector([, _refine[, _scale[, _sigma_scale[, _quant[, _ang_th[, _log_eps[, _density_th[, _n_bins]]]]]]]]) -> retval
|
||||
|
||||
:param _refine: The way found lines will be refined:
|
||||
|
||||
* **LSD_REFINE_NONE** - No refinement applied.
|
||||
|
||||
* **LSD_REFINE_STD** - Standard refinement is applied. E.g. breaking arches into smaller straighter line approximations.
|
||||
|
||||
* **LSD_REFINE_ADV** - Advanced refinement. Number of false alarms is calculated, lines are refined through increase of precision, decrement in size, etc.
|
||||
|
||||
:param scale: The scale of the image that will be used to find the lines. Range (0..1].
|
||||
|
||||
:param sigma_scale: Sigma for Gaussian filter. It is computed as sigma = _sigma_scale/_scale.
|
||||
|
||||
:param quant: Bound to the quantization error on the gradient norm.
|
||||
|
||||
:param ang_th: Gradient angle tolerance in degrees.
|
||||
|
||||
:param log_eps: Detection threshold: -log10(NFA) > log_eps. Used only when advancent refinement is chosen.
|
||||
|
||||
:param density_th: Minimal density of aligned region points in the enclosing rectangle.
|
||||
|
||||
:param n_bins: Number of bins in pseudo-ordering of gradient modulus.
|
||||
|
||||
The LineSegmentDetector algorithm is defined using the standard values. Only advanced users may want to edit those, as to tailor it for their own application.
|
||||
|
||||
|
||||
LineSegmentDetector::detect
|
||||
---------------------------
|
||||
Finds lines in the input image. See the lsd_lines.cpp sample for possible usage.
|
||||
|
||||
.. ocv:function:: void LineSegmentDetector::detect(const InputArray _image, OutputArray _lines, OutputArray width = noArray(), OutputArray prec = noArray(), OutputArray nfa = noArray())
|
||||
|
||||
.. ocv:pyfunction:: cv2.createLineSegmentDetector.detect(_image[, _lines[, width[, prec[, nfa]]]]) -> _lines, width, prec, nfa
|
||||
|
||||
:param _image A grayscale (CV_8UC1) input image.
|
||||
If only a roi needs to be selected, use ::
|
||||
lsd_ptr->detect(image(roi), lines, ...);
|
||||
lines += Scalar(roi.x, roi.y, roi.x, roi.y);
|
||||
|
||||
:param lines: A vector of Vec4i elements specifying the beginning and ending point of a line. Where Vec4i is (x1, y1, x2, y2), point 1 is the start, point 2 - end. Returned lines are strictly oriented depending on the gradient.
|
||||
|
||||
:param width: Vector of widths of the regions, where the lines are found. E.g. Width of line.
|
||||
|
||||
:param prec: Vector of precisions with which the lines are found.
|
||||
|
||||
:param nfa: Vector containing number of false alarms in the line region, with precision of 10%. The bigger the value, logarithmically better the detection.
|
||||
|
||||
* -1 corresponds to 10 mean false alarms
|
||||
|
||||
* 0 corresponds to 1 mean false alarm
|
||||
|
||||
* 1 corresponds to 0.1 mean false alarms
|
||||
|
||||
This vector will be calculated only when the objects type is LSD_REFINE_ADV.
|
||||
|
||||
This is the output of the default parameters of the algorithm on the above shown image.
|
||||
|
||||
.. image:: pics/building_lsd.png
|
||||
|
||||
.. note::
|
||||
|
||||
* An example using the LineSegmentDetector can be found at opencv_source_code/samples/cpp/lsd_lines.cpp
|
||||
|
||||
LineSegmentDetector::drawSegments
|
||||
---------------------------------
|
||||
Draws the line segments on a given image.
|
||||
|
||||
.. ocv:function:: void LineSegmentDetector::drawSegments(InputOutputArray _image, InputArray lines)
|
||||
|
||||
.. ocv:pyfunction:: cv2.createLineSegmentDetector.drawSegments(_image, lines) -> _image
|
||||
|
||||
:param image: The image, where the liens will be drawn. Should be bigger or equal to the image, where the lines were found.
|
||||
|
||||
:param lines: A vector of the lines that needed to be drawn.
|
||||
|
||||
|
||||
LineSegmentDetector::compareSegments
|
||||
------------------------------------
|
||||
Draws two groups of lines in blue and red, counting the non overlapping (mismatching) pixels.
|
||||
|
||||
.. ocv:function:: int LineSegmentDetector::compareSegments(const Size& size, InputArray lines1, InputArray lines2, InputOutputArray _image = noArray())
|
||||
|
||||
.. ocv:pyfunction:: cv2.createLineSegmentDetector.compareSegments(size, lines1, lines2[, _image]) -> retval, _image
|
||||
|
||||
:param size: The size of the image, where lines1 and lines2 were found.
|
||||
|
||||
:param lines1: The first group of lines that needs to be drawn. It is visualized in blue color.
|
||||
|
||||
:param lines2: The second group of lines. They visualized in red color.
|
||||
|
||||
:param image: Optional image, where the lines will be drawn. The image should be color(3-channel) in order for lines1 and lines2 to be drawn in the above mentioned colors.
|
||||
|
||||
|
||||
|
||||
preCornerDetect
|
||||
---------------
|
||||
Calculates a feature map for corner detection.
|
||||
|
||||
.. ocv:function:: void preCornerDetect( InputArray src, OutputArray dst, int ksize, int borderType=BORDER_DEFAULT )
|
||||
|
||||
.. ocv:pyfunction:: cv2.preCornerDetect(src, ksize[, dst[, borderType]]) -> dst
|
||||
|
||||
.. ocv:cfunction:: void cvPreCornerDetect( const CvArr* image, CvArr* corners, int aperture_size=3 )
|
||||
|
||||
:param src: Source single-channel 8-bit of floating-point image.
|
||||
|
||||
:param dst: Output image that has the type ``CV_32F`` and the same size as ``src`` .
|
||||
|
||||
:param ksize: Aperture size of the :ocv:func:`Sobel` .
|
||||
|
||||
:param borderType: Pixel extrapolation method. See :ocv:func:`borderInterpolate` .
|
||||
|
||||
The function calculates the complex spatial derivative-based function of the source image
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{dst} = (D_x \texttt{src} )^2 \cdot D_{yy} \texttt{src} + (D_y \texttt{src} )^2 \cdot D_{xx} \texttt{src} - 2 D_x \texttt{src} \cdot D_y \texttt{src} \cdot D_{xy} \texttt{src}
|
||||
|
||||
where
|
||||
:math:`D_x`,:math:`D_y` are the first image derivatives,
|
||||
:math:`D_{xx}`,:math:`D_{yy}` are the second image derivatives, and
|
||||
:math:`D_{xy}` is the mixed derivative.
|
||||
|
||||
The corners can be found as local maximums of the functions, as shown below: ::
|
||||
|
||||
Mat corners, dilated_corners;
|
||||
preCornerDetect(image, corners, 3);
|
||||
// dilation with 3x3 rectangular structuring element
|
||||
dilate(corners, dilated_corners, Mat(), 1);
|
||||
Mat corner_mask = corners == dilated_corners;
|
||||
|
||||
.. [Canny86] J. Canny. *A Computational Approach to Edge Detection*, IEEE Trans. on Pattern Analysis and Machine Intelligence, 8(6), pp. 679-698 (1986).
|
||||
|
||||
.. [Matas00] Matas, J. and Galambos, C. and Kittler, J.V., *Robust Detection of Lines Using the Progressive Probabilistic Hough Transform*. CVIU 78 1, pp 119-137 (2000)
|
||||
|
||||
.. [Shi94] J. Shi and C. Tomasi. *Good Features to Track*. Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pages 593-600, June 1994.
|
||||
|
||||
.. [Yuen90] Yuen, H. K. and Princen, J. and Illingworth, J. and Kittler, J., *Comparative study of Hough transform methods for circle finding*. Image Vision Comput. 8 1, pp 71–77 (1990)
|
||||
|
||||
.. [Rafael12] Rafael Grompone von Gioi, Jérémie Jakubowicz, Jean-Michel Morel, and Gregory Randall, LSD: a Line Segment Detector, Image Processing On Line, vol. 2012. http://dx.doi.org/10.5201/ipol.2012.gjmr-lsd
|
||||
@@ -1,950 +0,0 @@
|
||||
Image Filtering
|
||||
===============
|
||||
|
||||
.. highlight:: cpp
|
||||
|
||||
Functions and classes described in this section are used to perform various linear or non-linear filtering operations on 2D images (represented as
|
||||
:ocv:func:`Mat`'s). It means that for each pixel location
|
||||
:math:`(x,y)` in the source image (normally, rectangular), its neighborhood is considered and used to compute the response. In case of a linear filter, it is a weighted sum of pixel values. In case of morphological operations, it is the minimum or maximum values, and so on. The computed response is stored in the destination image at the same location
|
||||
:math:`(x,y)` . It means that the output image will be of the same size as the input image. Normally, the functions support multi-channel arrays, in which case every channel is processed independently. Therefore, the output image will also have the same number of channels as the input one.
|
||||
|
||||
Another common feature of the functions and classes described in this section is that, unlike simple arithmetic functions, they need to extrapolate values of some non-existing pixels. For example, if you want to smooth an image using a Gaussian
|
||||
:math:`3 \times 3` filter, then, when processing the left-most pixels in each row, you need pixels to the left of them, that is, outside of the image. You can let these pixels be the same as the left-most image pixels ("replicated border" extrapolation method), or assume that all the non-existing pixels are zeros ("constant border" extrapolation method), and so on.
|
||||
OpenCV enables you to specify the extrapolation method. For details, see the function ``borderInterpolate`` and discussion of the ``borderType`` parameter in the section and various functions below. ::
|
||||
|
||||
/*
|
||||
Various border types, image boundaries are denoted with '|'
|
||||
|
||||
* BORDER_REPLICATE: aaaaaa|abcdefgh|hhhhhhh
|
||||
* BORDER_REFLECT: fedcba|abcdefgh|hgfedcb
|
||||
* BORDER_REFLECT_101: gfedcb|abcdefgh|gfedcba
|
||||
* BORDER_WRAP: cdefgh|abcdefgh|abcdefg
|
||||
* BORDER_CONSTANT: iiiiii|abcdefgh|iiiiiii with some specified 'i'
|
||||
*/
|
||||
|
||||
.. note::
|
||||
|
||||
* (Python) A complete example illustrating different morphological operations like erode/dilate, open/close, blackhat/tophat ... can be found at opencv_source_code/samples/python2/morphology.py
|
||||
|
||||
bilateralFilter
|
||||
-------------------
|
||||
Applies the bilateral filter to an image.
|
||||
|
||||
.. ocv:function:: void bilateralFilter( InputArray src, OutputArray dst, int d, double sigmaColor, double sigmaSpace, int borderType=BORDER_DEFAULT )
|
||||
|
||||
.. ocv:pyfunction:: cv2.bilateralFilter(src, d, sigmaColor, sigmaSpace[, dst[, borderType]]) -> dst
|
||||
|
||||
:param src: Source 8-bit or floating-point, 1-channel or 3-channel image.
|
||||
|
||||
:param dst: Destination image of the same size and type as ``src`` .
|
||||
|
||||
:param d: Diameter of each pixel neighborhood that is used during filtering. If it is non-positive, it is computed from ``sigmaSpace`` .
|
||||
|
||||
:param sigmaColor: Filter sigma in the color space. A larger value of the parameter means that farther colors within the pixel neighborhood (see ``sigmaSpace`` ) will be mixed together, resulting in larger areas of semi-equal color.
|
||||
|
||||
:param sigmaSpace: Filter sigma in the coordinate space. A larger value of the parameter means that farther pixels will influence each other as long as their colors are close enough (see ``sigmaColor`` ). When ``d>0`` , it specifies the neighborhood size regardless of ``sigmaSpace`` . Otherwise, ``d`` is proportional to ``sigmaSpace`` .
|
||||
|
||||
The function applies bilateral filtering to the input image, as described in
|
||||
http://www.dai.ed.ac.uk/CVonline/LOCAL\_COPIES/MANDUCHI1/Bilateral\_Filtering.html
|
||||
``bilateralFilter`` can reduce unwanted noise very well while keeping edges fairly sharp. However, it is very slow compared to most filters.
|
||||
|
||||
*Sigma values*: For simplicity, you can set the 2 sigma values to be the same. If they are small (< 10), the filter will not have much effect, whereas if they are large (> 150), they will have a very strong effect, making the image look "cartoonish".
|
||||
|
||||
*Filter size*: Large filters (d > 5) are very slow, so it is recommended to use d=5 for real-time applications, and perhaps d=9 for offline applications that need heavy noise filtering.
|
||||
|
||||
This filter does not work inplace.
|
||||
|
||||
|
||||
blur
|
||||
----
|
||||
Blurs an image using the normalized box filter.
|
||||
|
||||
.. ocv:function:: void blur( InputArray src, OutputArray dst, Size ksize, Point anchor=Point(-1,-1), int borderType=BORDER_DEFAULT )
|
||||
|
||||
.. ocv:pyfunction:: cv2.blur(src, ksize[, dst[, anchor[, borderType]]]) -> dst
|
||||
|
||||
:param src: input image; it can have any number of channels, which are processed independently, but the depth should be ``CV_8U``, ``CV_16U``, ``CV_16S``, ``CV_32F`` or ``CV_64F``.
|
||||
|
||||
:param dst: output image of the same size and type as ``src``.
|
||||
|
||||
:param ksize: blurring kernel size.
|
||||
|
||||
:param anchor: anchor point; default value ``Point(-1,-1)`` means that the anchor is at the kernel center.
|
||||
|
||||
:param borderType: border mode used to extrapolate pixels outside of the image.
|
||||
|
||||
The function smoothes an image using the kernel:
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{K} = \frac{1}{\texttt{ksize.width*ksize.height}} \begin{bmatrix} 1 & 1 & 1 & \cdots & 1 & 1 \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \hdotsfor{6} \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \end{bmatrix}
|
||||
|
||||
The call ``blur(src, dst, ksize, anchor, borderType)`` is equivalent to ``boxFilter(src, dst, src.type(), anchor, true, borderType)`` .
|
||||
|
||||
.. seealso::
|
||||
|
||||
:ocv:func:`boxFilter`,
|
||||
:ocv:func:`bilateralFilter`,
|
||||
:ocv:func:`GaussianBlur`,
|
||||
:ocv:func:`medianBlur`
|
||||
|
||||
|
||||
boxFilter
|
||||
---------
|
||||
Blurs an image using the box filter.
|
||||
|
||||
.. ocv:function:: void boxFilter( InputArray src, OutputArray dst, int ddepth, Size ksize, Point anchor=Point(-1,-1), bool normalize=true, int borderType=BORDER_DEFAULT )
|
||||
|
||||
.. ocv:pyfunction:: cv2.boxFilter(src, ddepth, ksize[, dst[, anchor[, normalize[, borderType]]]]) -> dst
|
||||
|
||||
:param src: input image.
|
||||
|
||||
:param dst: output image of the same size and type as ``src``.
|
||||
|
||||
:param ddepth: the output image depth (-1 to use ``src.depth()``).
|
||||
|
||||
:param ksize: blurring kernel size.
|
||||
|
||||
:param anchor: anchor point; default value ``Point(-1,-1)`` means that the anchor is at the kernel center.
|
||||
|
||||
:param normalize: flag, specifying whether the kernel is normalized by its area or not.
|
||||
|
||||
:param borderType: border mode used to extrapolate pixels outside of the image.
|
||||
|
||||
The function smoothes an image using the kernel:
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{K} = \alpha \begin{bmatrix} 1 & 1 & 1 & \cdots & 1 & 1 \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \hdotsfor{6} \\ 1 & 1 & 1 & \cdots & 1 & 1 \end{bmatrix}
|
||||
|
||||
where
|
||||
|
||||
.. math::
|
||||
|
||||
\alpha = \fork{\frac{1}{\texttt{ksize.width*ksize.height}}}{when \texttt{normalize=true}}{1}{otherwise}
|
||||
|
||||
Unnormalized box filter is useful for computing various integral characteristics over each pixel neighborhood, such as covariance matrices of image derivatives (used in dense optical flow algorithms, and so on). If you need to compute pixel sums over variable-size windows, use :ocv:func:`integral` .
|
||||
|
||||
.. seealso::
|
||||
|
||||
:ocv:func:`blur`,
|
||||
:ocv:func:`bilateralFilter`,
|
||||
:ocv:func:`GaussianBlur`,
|
||||
:ocv:func:`medianBlur`,
|
||||
:ocv:func:`integral`
|
||||
|
||||
|
||||
|
||||
buildPyramid
|
||||
------------
|
||||
Constructs the Gaussian pyramid for an image.
|
||||
|
||||
.. ocv:function:: void buildPyramid( InputArray src, OutputArrayOfArrays dst, int maxlevel, int borderType=BORDER_DEFAULT )
|
||||
|
||||
:param src: Source image. Check :ocv:func:`pyrDown` for the list of supported types.
|
||||
|
||||
:param dst: Destination vector of ``maxlevel+1`` images of the same type as ``src`` . ``dst[0]`` will be the same as ``src`` . ``dst[1]`` is the next pyramid layer, a smoothed and down-sized ``src`` , and so on.
|
||||
|
||||
:param maxlevel: 0-based index of the last (the smallest) pyramid layer. It must be non-negative.
|
||||
|
||||
:param borderType: Pixel extrapolation method (BORDER_CONSTANT don't supported). See ``borderInterpolate`` for details.
|
||||
|
||||
The function constructs a vector of images and builds the Gaussian pyramid by recursively applying
|
||||
:ocv:func:`pyrDown` to the previously built pyramid layers, starting from ``dst[0]==src`` .
|
||||
|
||||
|
||||
dilate
|
||||
------
|
||||
Dilates an image by using a specific structuring element.
|
||||
|
||||
.. ocv:function:: void dilate( InputArray src, OutputArray dst, InputArray kernel, Point anchor=Point(-1,-1), int iterations=1, int borderType=BORDER_CONSTANT, const Scalar& borderValue=morphologyDefaultBorderValue() )
|
||||
|
||||
.. ocv:pyfunction:: cv2.dilate(src, kernel[, dst[, anchor[, iterations[, borderType[, borderValue]]]]]) -> dst
|
||||
|
||||
.. ocv:cfunction:: void cvDilate( const CvArr* src, CvArr* dst, IplConvKernel* element=NULL, int iterations=1 )
|
||||
|
||||
:param src: input image; the number of channels can be arbitrary, but the depth should be one of ``CV_8U``, ``CV_16U``, ``CV_16S``, ``CV_32F` or ``CV_64F``.
|
||||
|
||||
:param dst: output image of the same size and type as ``src``.
|
||||
|
||||
:param kernel: structuring element used for dilation; if ``elemenat=Mat()`` , a ``3 x 3`` rectangular structuring element is used. Kernel can be created using :ocv:func:`getStructuringElement`
|
||||
|
||||
:param anchor: position of the anchor within the element; default value ``(-1, -1)`` means that the anchor is at the element center.
|
||||
|
||||
:param iterations: number of times dilation is applied.
|
||||
|
||||
:param borderType: pixel extrapolation method (see ``borderInterpolate`` for details).
|
||||
|
||||
:param borderValue: border value in case of a constant border
|
||||
|
||||
The function dilates the source image using the specified structuring element that determines the shape of a pixel neighborhood over which the maximum is taken:
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{dst} (x,y) = \max _{(x',y'): \, \texttt{element} (x',y') \ne0 } \texttt{src} (x+x',y+y')
|
||||
|
||||
The function supports the in-place mode. Dilation can be applied several ( ``iterations`` ) times. In case of multi-channel images, each channel is processed independently.
|
||||
|
||||
.. seealso::
|
||||
|
||||
:ocv:func:`erode`,
|
||||
:ocv:func:`morphologyEx`,
|
||||
:ocv:func:`getStructuringElement`
|
||||
|
||||
|
||||
.. note::
|
||||
|
||||
* An example using the morphological dilate operation can be found at opencv_source_code/samples/cpp/morphology2.cpp
|
||||
|
||||
|
||||
erode
|
||||
-----
|
||||
Erodes an image by using a specific structuring element.
|
||||
|
||||
.. ocv:function:: void erode( InputArray src, OutputArray dst, InputArray kernel, Point anchor=Point(-1,-1), int iterations=1, int borderType=BORDER_CONSTANT, const Scalar& borderValue=morphologyDefaultBorderValue() )
|
||||
|
||||
.. ocv:pyfunction:: cv2.erode(src, kernel[, dst[, anchor[, iterations[, borderType[, borderValue]]]]]) -> dst
|
||||
|
||||
.. ocv:cfunction:: void cvErode( const CvArr* src, CvArr* dst, IplConvKernel* element=NULL, int iterations=1)
|
||||
|
||||
:param src: input image; the number of channels can be arbitrary, but the depth should be one of ``CV_8U``, ``CV_16U``, ``CV_16S``, ``CV_32F` or ``CV_64F``.
|
||||
|
||||
:param dst: output image of the same size and type as ``src``.
|
||||
|
||||
:param kernel: structuring element used for erosion; if ``element=Mat()`` , a ``3 x 3`` rectangular structuring element is used. Kernel can be created using :ocv:func:`getStructuringElement`.
|
||||
|
||||
:param anchor: position of the anchor within the element; default value ``(-1, -1)`` means that the anchor is at the element center.
|
||||
|
||||
:param iterations: number of times erosion is applied.
|
||||
|
||||
:param borderType: pixel extrapolation method (see ``borderInterpolate`` for details).
|
||||
|
||||
:param borderValue: border value in case of a constant border
|
||||
|
||||
The function erodes the source image using the specified structuring element that determines the shape of a pixel neighborhood over which the minimum is taken:
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{dst} (x,y) = \min _{(x',y'): \, \texttt{element} (x',y') \ne0 } \texttt{src} (x+x',y+y')
|
||||
|
||||
The function supports the in-place mode. Erosion can be applied several ( ``iterations`` ) times. In case of multi-channel images, each channel is processed independently.
|
||||
|
||||
.. seealso::
|
||||
|
||||
:ocv:func:`dilate`,
|
||||
:ocv:func:`morphologyEx`,
|
||||
:ocv:func:`getStructuringElement`
|
||||
|
||||
.. note::
|
||||
|
||||
* An example using the morphological erode operation can be found at opencv_source_code/samples/cpp/morphology2.cpp
|
||||
|
||||
filter2D
|
||||
--------
|
||||
Convolves an image with the kernel.
|
||||
|
||||
.. ocv:function:: void filter2D( InputArray src, OutputArray dst, int ddepth, InputArray kernel, Point anchor=Point(-1,-1), double delta=0, int borderType=BORDER_DEFAULT )
|
||||
|
||||
.. ocv:pyfunction:: cv2.filter2D(src, ddepth, kernel[, dst[, anchor[, delta[, borderType]]]]) -> dst
|
||||
|
||||
.. ocv:cfunction:: void cvFilter2D( const CvArr* src, CvArr* dst, const CvMat* kernel, CvPoint anchor=cvPoint(-1,-1) )
|
||||
|
||||
:param src: input image.
|
||||
|
||||
:param dst: output image of the same size and the same number of channels as ``src``.
|
||||
|
||||
|
||||
:param ddepth: desired depth of the destination image; if it is negative, it will be the same as ``src.depth()``; the following combinations of ``src.depth()`` and ``ddepth`` are supported:
|
||||
* ``src.depth()`` = ``CV_8U``, ``ddepth`` = -1/``CV_16S``/``CV_32F``/``CV_64F``
|
||||
* ``src.depth()`` = ``CV_16U``/``CV_16S``, ``ddepth`` = -1/``CV_32F``/``CV_64F``
|
||||
* ``src.depth()`` = ``CV_32F``, ``ddepth`` = -1/``CV_32F``/``CV_64F``
|
||||
* ``src.depth()`` = ``CV_64F``, ``ddepth`` = -1/``CV_64F``
|
||||
|
||||
when ``ddepth=-1``, the output image will have the same depth as the source.
|
||||
|
||||
:param kernel: convolution kernel (or rather a correlation kernel), a single-channel floating point matrix; if you want to apply different kernels to different channels, split the image into separate color planes using :ocv:func:`split` and process them individually.
|
||||
|
||||
:param anchor: anchor of the kernel that indicates the relative position of a filtered point within the kernel; the anchor should lie within the kernel; default value (-1,-1) means that the anchor is at the kernel center.
|
||||
|
||||
:param delta: optional value added to the filtered pixels before storing them in ``dst``.
|
||||
|
||||
:param borderType: pixel extrapolation method (see ``borderInterpolate`` for details).
|
||||
|
||||
The function applies an arbitrary linear filter to an image. In-place operation is supported. When the aperture is partially outside the image, the function interpolates outlier pixel values according to the specified border mode.
|
||||
|
||||
The function does actually compute correlation, not the convolution:
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{dst} (x,y) = \sum _{ \stackrel{0\leq x' < \texttt{kernel.cols},}{0\leq y' < \texttt{kernel.rows}} } \texttt{kernel} (x',y')* \texttt{src} (x+x'- \texttt{anchor.x} ,y+y'- \texttt{anchor.y} )
|
||||
|
||||
That is, the kernel is not mirrored around the anchor point. If you need a real convolution, flip the kernel using
|
||||
:ocv:func:`flip` and set the new anchor to ``(kernel.cols - anchor.x - 1, kernel.rows - anchor.y - 1)`` .
|
||||
|
||||
The function uses the DFT-based algorithm in case of sufficiently large kernels (~``11 x 11`` or larger) and the direct algorithm for small kernels.
|
||||
|
||||
.. seealso::
|
||||
|
||||
:ocv:func:`sepFilter2D`,
|
||||
:ocv:func:`dft`,
|
||||
:ocv:func:`matchTemplate`
|
||||
|
||||
|
||||
|
||||
GaussianBlur
|
||||
------------
|
||||
Blurs an image using a Gaussian filter.
|
||||
|
||||
.. ocv:function:: void GaussianBlur( InputArray src, OutputArray dst, Size ksize, double sigmaX, double sigmaY=0, int borderType=BORDER_DEFAULT )
|
||||
|
||||
.. ocv:pyfunction:: cv2.GaussianBlur(src, ksize, sigmaX[, dst[, sigmaY[, borderType]]]) -> dst
|
||||
|
||||
:param src: input image; the image can have any number of channels, which are processed independently, but the depth should be ``CV_8U``, ``CV_16U``, ``CV_16S``, ``CV_32F`` or ``CV_64F``.
|
||||
|
||||
:param dst: output image of the same size and type as ``src``.
|
||||
|
||||
:param ksize: Gaussian kernel size. ``ksize.width`` and ``ksize.height`` can differ but they both must be positive and odd. Or, they can be zero's and then they are computed from ``sigma*`` .
|
||||
|
||||
:param sigmaX: Gaussian kernel standard deviation in X direction.
|
||||
|
||||
:param sigmaY: Gaussian kernel standard deviation in Y direction; if ``sigmaY`` is zero, it is set to be equal to ``sigmaX``, if both sigmas are zeros, they are computed from ``ksize.width`` and ``ksize.height`` , respectively (see :ocv:func:`getGaussianKernel` for details); to fully control the result regardless of possible future modifications of all this semantics, it is recommended to specify all of ``ksize``, ``sigmaX``, and ``sigmaY``.
|
||||
|
||||
:param borderType: pixel extrapolation method (see ``borderInterpolate`` for details).
|
||||
|
||||
The function convolves the source image with the specified Gaussian kernel. In-place filtering is supported.
|
||||
|
||||
.. seealso::
|
||||
|
||||
:ocv:func:`sepFilter2D`,
|
||||
:ocv:func:`filter2D`,
|
||||
:ocv:func:`blur`,
|
||||
:ocv:func:`boxFilter`,
|
||||
:ocv:func:`bilateralFilter`,
|
||||
:ocv:func:`medianBlur`
|
||||
|
||||
|
||||
getDerivKernels
|
||||
---------------
|
||||
Returns filter coefficients for computing spatial image derivatives.
|
||||
|
||||
.. ocv:function:: void getDerivKernels( OutputArray kx, OutputArray ky, int dx, int dy, int ksize, bool normalize=false, int ktype=CV_32F )
|
||||
|
||||
.. ocv:pyfunction:: cv2.getDerivKernels(dx, dy, ksize[, kx[, ky[, normalize[, ktype]]]]) -> kx, ky
|
||||
|
||||
:param kx: Output matrix of row filter coefficients. It has the type ``ktype`` .
|
||||
|
||||
:param ky: Output matrix of column filter coefficients. It has the type ``ktype`` .
|
||||
|
||||
:param dx: Derivative order in respect of x.
|
||||
|
||||
:param dy: Derivative order in respect of y.
|
||||
|
||||
:param ksize: Aperture size. It can be ``CV_SCHARR`` , 1, 3, 5, or 7.
|
||||
|
||||
:param normalize: Flag indicating whether to normalize (scale down) the filter coefficients or not. Theoretically, the coefficients should have the denominator :math:`=2^{ksize*2-dx-dy-2}` . If you are going to filter floating-point images, you are likely to use the normalized kernels. But if you compute derivatives of an 8-bit image, store the results in a 16-bit image, and wish to preserve all the fractional bits, you may want to set ``normalize=false`` .
|
||||
|
||||
:param ktype: Type of filter coefficients. It can be ``CV_32f`` or ``CV_64F`` .
|
||||
|
||||
The function computes and returns the filter coefficients for spatial image derivatives. When ``ksize=CV_SCHARR`` , the Scharr
|
||||
:math:`3 \times 3` kernels are generated (see
|
||||
:ocv:func:`Scharr` ). Otherwise, Sobel kernels are generated (see
|
||||
:ocv:func:`Sobel` ). The filters are normally passed to
|
||||
:ocv:func:`sepFilter2D` or to
|
||||
|
||||
|
||||
getGaussianKernel
|
||||
-----------------
|
||||
Returns Gaussian filter coefficients.
|
||||
|
||||
.. ocv:function:: Mat getGaussianKernel( int ksize, double sigma, int ktype=CV_64F )
|
||||
|
||||
.. ocv:pyfunction:: cv2.getGaussianKernel(ksize, sigma[, ktype]) -> retval
|
||||
|
||||
:param ksize: Aperture size. It should be odd ( :math:`\texttt{ksize} \mod 2 = 1` ) and positive.
|
||||
|
||||
:param sigma: Gaussian standard deviation. If it is non-positive, it is computed from ``ksize`` as \ ``sigma = 0.3*((ksize-1)*0.5 - 1) + 0.8`` .
|
||||
:param ktype: Type of filter coefficients. It can be ``CV_32F`` or ``CV_64F`` .
|
||||
|
||||
The function computes and returns the
|
||||
:math:`\texttt{ksize} \times 1` matrix of Gaussian filter coefficients:
|
||||
|
||||
.. math::
|
||||
|
||||
G_i= \alpha *e^{-(i-( \texttt{ksize} -1)/2)^2/(2* \texttt{sigma} )^2},
|
||||
|
||||
where
|
||||
:math:`i=0..\texttt{ksize}-1` and
|
||||
:math:`\alpha` is the scale factor chosen so that
|
||||
:math:`\sum_i G_i=1`.
|
||||
|
||||
Two of such generated kernels can be passed to
|
||||
:ocv:func:`sepFilter2D`. Those functions automatically recognize smoothing kernels (a symmetrical kernel with sum of weights equal to 1) and handle them accordingly. You may also use the higher-level
|
||||
:ocv:func:`GaussianBlur`.
|
||||
|
||||
.. seealso::
|
||||
|
||||
:ocv:func:`sepFilter2D`,
|
||||
:ocv:func:`getDerivKernels`,
|
||||
:ocv:func:`getStructuringElement`,
|
||||
:ocv:func:`GaussianBlur`
|
||||
|
||||
|
||||
|
||||
getGaborKernel
|
||||
-----------------
|
||||
Returns Gabor filter coefficients.
|
||||
|
||||
.. ocv:function:: Mat getGaborKernel( Size ksize, double sigma, double theta, double lambd, double gamma, double psi = CV_PI*0.5, int ktype = CV_64F )
|
||||
|
||||
.. ocv:pyfunction:: cv2.getGaborKernel(ksize, sigma, theta, lambd, gamma[, psi[, ktype]]) -> retval
|
||||
|
||||
:param ksize: Size of the filter returned.
|
||||
|
||||
:param sigma: Standard deviation of the gaussian envelope.
|
||||
|
||||
:param theta: Orientation of the normal to the parallel stripes of a Gabor function.
|
||||
|
||||
:param lambd: Wavelength of the sinusoidal factor.
|
||||
|
||||
:param gamma: Spatial aspect ratio.
|
||||
|
||||
:param psi: Phase offset.
|
||||
|
||||
:param ktype: Type of filter coefficients. It can be ``CV_32F`` or ``CV_64F`` .
|
||||
|
||||
For more details about gabor filter equations and parameters, see: `Gabor Filter <http://en.wikipedia.org/wiki/Gabor_filter>`_.
|
||||
|
||||
|
||||
getStructuringElement
|
||||
---------------------
|
||||
Returns a structuring element of the specified size and shape for morphological operations.
|
||||
|
||||
.. ocv:function:: Mat getStructuringElement(int shape, Size ksize, Point anchor=Point(-1,-1))
|
||||
|
||||
.. ocv:pyfunction:: cv2.getStructuringElement(shape, ksize[, anchor]) -> retval
|
||||
|
||||
.. ocv:cfunction:: IplConvKernel* cvCreateStructuringElementEx( int cols, int rows, int anchor_x, int anchor_y, int shape, int* values=NULL )
|
||||
|
||||
:param shape: Element shape that could be one of the following:
|
||||
|
||||
* **MORPH_RECT** - a rectangular structuring element:
|
||||
|
||||
.. math::
|
||||
|
||||
E_{ij}=1
|
||||
|
||||
* **MORPH_ELLIPSE** - an elliptic structuring element, that is, a filled ellipse inscribed into the rectangle ``Rect(0, 0, esize.width, 0.esize.height)``
|
||||
|
||||
* **MORPH_CROSS** - a cross-shaped structuring element:
|
||||
|
||||
.. math::
|
||||
|
||||
E_{ij} = \fork{1}{if i=\texttt{anchor.y} or j=\texttt{anchor.x}}{0}{otherwise}
|
||||
|
||||
* **CV_SHAPE_CUSTOM** - custom structuring element (OpenCV 1.x API)
|
||||
|
||||
:param ksize: Size of the structuring element.
|
||||
|
||||
:param cols: Width of the structuring element
|
||||
|
||||
:param rows: Height of the structuring element
|
||||
|
||||
:param anchor: Anchor position within the element. The default value :math:`(-1, -1)` means that the anchor is at the center. Note that only the shape of a cross-shaped element depends on the anchor position. In other cases the anchor just regulates how much the result of the morphological operation is shifted.
|
||||
|
||||
:param anchor_x: x-coordinate of the anchor
|
||||
|
||||
:param anchor_y: y-coordinate of the anchor
|
||||
|
||||
:param values: integer array of ``cols``*``rows`` elements that specifies the custom shape of the structuring element, when ``shape=CV_SHAPE_CUSTOM``.
|
||||
|
||||
The function constructs and returns the structuring element that can be further passed to
|
||||
:ocv:func:`erode`,
|
||||
:ocv:func:`dilate` or
|
||||
:ocv:func:`morphologyEx` . But you can also construct an arbitrary binary mask yourself and use it as the structuring element.
|
||||
|
||||
.. note:: When using OpenCV 1.x C API, the created structuring element ``IplConvKernel* element`` must be released in the end using ``cvReleaseStructuringElement(&element)``.
|
||||
|
||||
|
||||
medianBlur
|
||||
----------
|
||||
Blurs an image using the median filter.
|
||||
|
||||
.. ocv:function:: void medianBlur( InputArray src, OutputArray dst, int ksize )
|
||||
|
||||
.. ocv:pyfunction:: cv2.medianBlur(src, ksize[, dst]) -> dst
|
||||
|
||||
:param src: input 1-, 3-, or 4-channel image; when ``ksize`` is 3 or 5, the image depth should be ``CV_8U``, ``CV_16U``, or ``CV_32F``, for larger aperture sizes, it can only be ``CV_8U``.
|
||||
|
||||
:param dst: destination array of the same size and type as ``src``.
|
||||
|
||||
:param ksize: aperture linear size; it must be odd and greater than 1, for example: 3, 5, 7 ...
|
||||
|
||||
The function smoothes an image using the median filter with the
|
||||
:math:`\texttt{ksize} \times \texttt{ksize}` aperture. Each channel of a multi-channel image is processed independently. In-place operation is supported.
|
||||
|
||||
.. seealso::
|
||||
|
||||
:ocv:func:`bilateralFilter`,
|
||||
:ocv:func:`blur`,
|
||||
:ocv:func:`boxFilter`,
|
||||
:ocv:func:`GaussianBlur`
|
||||
|
||||
|
||||
|
||||
morphologyEx
|
||||
------------
|
||||
Performs advanced morphological transformations.
|
||||
|
||||
.. ocv:function:: void morphologyEx( InputArray src, OutputArray dst, int op, InputArray kernel, Point anchor=Point(-1,-1), int iterations=1, int borderType=BORDER_CONSTANT, const Scalar& borderValue=morphologyDefaultBorderValue() )
|
||||
|
||||
.. ocv:pyfunction:: cv2.morphologyEx(src, op, kernel[, dst[, anchor[, iterations[, borderType[, borderValue]]]]]) -> dst
|
||||
|
||||
.. ocv:cfunction:: void cvMorphologyEx( const CvArr* src, CvArr* dst, CvArr* temp, IplConvKernel* element, int operation, int iterations=1 )
|
||||
|
||||
:param src: Source image. The number of channels can be arbitrary. The depth should be one of ``CV_8U``, ``CV_16U``, ``CV_16S``, ``CV_32F` or ``CV_64F``.
|
||||
|
||||
:param dst: Destination image of the same size and type as ``src`` .
|
||||
|
||||
:param kernel: Structuring element. It can be created using :ocv:func:`getStructuringElement`.
|
||||
|
||||
:param anchor: Anchor position with the kernel. Negative values mean that the anchor is at the kernel center.
|
||||
|
||||
:param op: Type of a morphological operation that can be one of the following:
|
||||
|
||||
* **MORPH_OPEN** - an opening operation
|
||||
|
||||
* **MORPH_CLOSE** - a closing operation
|
||||
|
||||
* **MORPH_GRADIENT** - a morphological gradient
|
||||
|
||||
* **MORPH_TOPHAT** - "top hat"
|
||||
|
||||
* **MORPH_BLACKHAT** - "black hat"
|
||||
|
||||
:param iterations: Number of times erosion and dilation are applied.
|
||||
|
||||
:param borderType: Pixel extrapolation method. See ``borderInterpolate`` for details.
|
||||
|
||||
:param borderValue: Border value in case of a constant border. The default value has a special meaning.
|
||||
|
||||
The function can perform advanced morphological transformations using an erosion and dilation as basic operations.
|
||||
|
||||
Opening operation:
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{dst} = \mathrm{open} ( \texttt{src} , \texttt{element} )= \mathrm{dilate} ( \mathrm{erode} ( \texttt{src} , \texttt{element} ))
|
||||
|
||||
Closing operation:
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{dst} = \mathrm{close} ( \texttt{src} , \texttt{element} )= \mathrm{erode} ( \mathrm{dilate} ( \texttt{src} , \texttt{element} ))
|
||||
|
||||
Morphological gradient:
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{dst} = \mathrm{morph\_grad} ( \texttt{src} , \texttt{element} )= \mathrm{dilate} ( \texttt{src} , \texttt{element} )- \mathrm{erode} ( \texttt{src} , \texttt{element} )
|
||||
|
||||
"Top hat":
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{dst} = \mathrm{tophat} ( \texttt{src} , \texttt{element} )= \texttt{src} - \mathrm{open} ( \texttt{src} , \texttt{element} )
|
||||
|
||||
"Black hat":
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{dst} = \mathrm{blackhat} ( \texttt{src} , \texttt{element} )= \mathrm{close} ( \texttt{src} , \texttt{element} )- \texttt{src}
|
||||
|
||||
Any of the operations can be done in-place. In case of multi-channel images, each channel is processed independently.
|
||||
|
||||
.. seealso::
|
||||
|
||||
:ocv:func:`dilate`,
|
||||
:ocv:func:`erode`,
|
||||
:ocv:func:`getStructuringElement`
|
||||
|
||||
.. note::
|
||||
|
||||
* An example using the morphologyEx function for the morphological opening and closing operations can be found at opencv_source_code/samples/cpp/morphology2.cpp
|
||||
|
||||
Laplacian
|
||||
---------
|
||||
Calculates the Laplacian of an image.
|
||||
|
||||
.. ocv:function:: void Laplacian( InputArray src, OutputArray dst, int ddepth, int ksize=1, double scale=1, double delta=0, int borderType=BORDER_DEFAULT )
|
||||
|
||||
.. ocv:pyfunction:: cv2.Laplacian(src, ddepth[, dst[, ksize[, scale[, delta[, borderType]]]]]) -> dst
|
||||
|
||||
.. ocv:cfunction:: void cvLaplace( const CvArr* src, CvArr* dst, int aperture_size=3 )
|
||||
|
||||
:param src: Source image.
|
||||
|
||||
:param dst: Destination image of the same size and the same number of channels as ``src`` .
|
||||
|
||||
:param ddepth: Desired depth of the destination image.
|
||||
|
||||
:param ksize: Aperture size used to compute the second-derivative filters. See :ocv:func:`getDerivKernels` for details. The size must be positive and odd.
|
||||
|
||||
:param scale: Optional scale factor for the computed Laplacian values. By default, no scaling is applied. See :ocv:func:`getDerivKernels` for details.
|
||||
|
||||
:param delta: Optional delta value that is added to the results prior to storing them in ``dst`` .
|
||||
|
||||
:param borderType: Pixel extrapolation method. See ``borderInterpolate`` for details.
|
||||
|
||||
The function calculates the Laplacian of the source image by adding up the second x and y derivatives calculated using the Sobel operator:
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{dst} = \Delta \texttt{src} = \frac{\partial^2 \texttt{src}}{\partial x^2} + \frac{\partial^2 \texttt{src}}{\partial y^2}
|
||||
|
||||
This is done when ``ksize > 1`` . When ``ksize == 1`` , the Laplacian is computed by filtering the image with the following
|
||||
:math:`3 \times 3` aperture:
|
||||
|
||||
.. math::
|
||||
|
||||
\vecthreethree {0}{1}{0}{1}{-4}{1}{0}{1}{0}
|
||||
|
||||
.. seealso::
|
||||
|
||||
:ocv:func:`Sobel`,
|
||||
:ocv:func:`Scharr`
|
||||
|
||||
.. note::
|
||||
|
||||
* An example using the Laplace transformation for edge detection can be found at opencv_source_code/samples/cpp/laplace.cpp
|
||||
|
||||
pyrDown
|
||||
-------
|
||||
Blurs an image and downsamples it.
|
||||
|
||||
.. ocv:function:: void pyrDown( InputArray src, OutputArray dst, const Size& dstsize=Size(), int borderType=BORDER_DEFAULT )
|
||||
|
||||
.. ocv:pyfunction:: cv2.pyrDown(src[, dst[, dstsize[, borderType]]]) -> dst
|
||||
|
||||
.. ocv:cfunction:: void cvPyrDown( const CvArr* src, CvArr* dst, int filter=CV_GAUSSIAN_5x5 )
|
||||
|
||||
:param src: input image.
|
||||
|
||||
:param dst: output image; it has the specified size and the same type as ``src``.
|
||||
|
||||
:param dstsize: size of the output image.
|
||||
|
||||
:param borderType: Pixel extrapolation method (BORDER_CONSTANT don't supported). See ``borderInterpolate`` for details.
|
||||
|
||||
By default, size of the output image is computed as ``Size((src.cols+1)/2, (src.rows+1)/2)``, but in any case, the following conditions should be satisfied:
|
||||
|
||||
.. math::
|
||||
|
||||
\begin{array}{l}
|
||||
| \texttt{dstsize.width} *2-src.cols| \leq 2 \\ | \texttt{dstsize.height} *2-src.rows| \leq 2 \end{array}
|
||||
|
||||
The function performs the downsampling step of the Gaussian pyramid construction. First, it convolves the source image with the kernel:
|
||||
|
||||
.. math::
|
||||
|
||||
\frac{1}{256} \begin{bmatrix} 1 & 4 & 6 & 4 & 1 \\ 4 & 16 & 24 & 16 & 4 \\ 6 & 24 & 36 & 24 & 6 \\ 4 & 16 & 24 & 16 & 4 \\ 1 & 4 & 6 & 4 & 1 \end{bmatrix}
|
||||
|
||||
Then, it downsamples the image by rejecting even rows and columns.
|
||||
|
||||
pyrUp
|
||||
-----
|
||||
Upsamples an image and then blurs it.
|
||||
|
||||
.. ocv:function:: void pyrUp( InputArray src, OutputArray dst, const Size& dstsize=Size(), int borderType=BORDER_DEFAULT )
|
||||
|
||||
.. ocv:pyfunction:: cv2.pyrUp(src[, dst[, dstsize[, borderType]]]) -> dst
|
||||
|
||||
.. ocv:cfunction:: cvPyrUp( const CvArr* src, CvArr* dst, int filter=CV_GAUSSIAN_5x5 )
|
||||
|
||||
:param src: input image.
|
||||
|
||||
:param dst: output image. It has the specified size and the same type as ``src`` .
|
||||
|
||||
:param dstsize: size of the output image.
|
||||
|
||||
:param borderType: Pixel extrapolation method (only BORDER_DEFAULT supported). See ``borderInterpolate`` for details.
|
||||
|
||||
By default, size of the output image is computed as ``Size(src.cols*2, (src.rows*2)``, but in any case, the following conditions should be satisfied:
|
||||
|
||||
.. math::
|
||||
|
||||
\begin{array}{l}
|
||||
| \texttt{dstsize.width} -src.cols*2| \leq ( \texttt{dstsize.width} \mod 2) \\ | \texttt{dstsize.height} -src.rows*2| \leq ( \texttt{dstsize.height} \mod 2) \end{array}
|
||||
|
||||
The function performs the upsampling step of the Gaussian pyramid construction, though it can actually be used to construct the Laplacian pyramid. First, it upsamples the source image by injecting even zero rows and columns and then convolves the result with the same kernel as in
|
||||
:ocv:func:`pyrDown` multiplied by 4.
|
||||
|
||||
.. note::
|
||||
|
||||
* (Python) An example of Laplacian Pyramid construction and merging can be found at opencv_source_code/samples/python2/lappyr.py
|
||||
|
||||
|
||||
pyrMeanShiftFiltering
|
||||
---------------------
|
||||
Performs initial step of meanshift segmentation of an image.
|
||||
|
||||
.. ocv:function:: void pyrMeanShiftFiltering( InputArray src, OutputArray dst, double sp, double sr, int maxLevel=1, TermCriteria termcrit=TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS,5,1) )
|
||||
|
||||
.. ocv:pyfunction:: cv2.pyrMeanShiftFiltering(src, sp, sr[, dst[, maxLevel[, termcrit]]]) -> dst
|
||||
|
||||
.. ocv:cfunction:: void cvPyrMeanShiftFiltering( const CvArr* src, CvArr* dst, double sp, double sr, int max_level=1, CvTermCriteria termcrit= cvTermCriteria(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS,5,1))
|
||||
|
||||
:param src: The source 8-bit, 3-channel image.
|
||||
|
||||
:param dst: The destination image of the same format and the same size as the source.
|
||||
|
||||
:param sp: The spatial window radius.
|
||||
|
||||
:param sr: The color window radius.
|
||||
|
||||
:param maxLevel: Maximum level of the pyramid for the segmentation.
|
||||
|
||||
:param termcrit: Termination criteria: when to stop meanshift iterations.
|
||||
|
||||
|
||||
The function implements the filtering stage of meanshift segmentation, that is, the output of the function is the filtered "posterized" image with color gradients and fine-grain texture flattened. At every pixel
|
||||
``(X,Y)`` of the input image (or down-sized input image, see below) the function executes meanshift
|
||||
iterations, that is, the pixel ``(X,Y)`` neighborhood in the joint space-color hyperspace is considered:
|
||||
|
||||
.. math::
|
||||
|
||||
(x,y): X- \texttt{sp} \le x \le X+ \texttt{sp} , Y- \texttt{sp} \le y \le Y+ \texttt{sp} , ||(R,G,B)-(r,g,b)|| \le \texttt{sr}
|
||||
|
||||
|
||||
where ``(R,G,B)`` and ``(r,g,b)`` are the vectors of color components at ``(X,Y)`` and ``(x,y)``, respectively (though, the algorithm does not depend on the color space used, so any 3-component color space can be used instead). Over the neighborhood the average spatial value ``(X',Y')`` and average color vector ``(R',G',B')`` are found and they act as the neighborhood center on the next iteration:
|
||||
|
||||
.. math::
|
||||
|
||||
(X,Y)~(X',Y'), (R,G,B)~(R',G',B').
|
||||
|
||||
After the iterations over, the color components of the initial pixel (that is, the pixel from where the iterations started) are set to the final value (average color at the last iteration):
|
||||
|
||||
.. math::
|
||||
|
||||
I(X,Y) <- (R*,G*,B*)
|
||||
|
||||
When ``maxLevel > 0``, the gaussian pyramid of ``maxLevel+1`` levels is built, and the above procedure is run on the smallest layer first. After that, the results are propagated to the larger layer and the iterations are run again only on those pixels where the layer colors differ by more than ``sr`` from the lower-resolution layer of the pyramid. That makes boundaries of color regions sharper. Note that the results will be actually different from the ones obtained by running the meanshift procedure on the whole original image (i.e. when ``maxLevel==0``).
|
||||
|
||||
.. note::
|
||||
|
||||
* An example using mean-shift image segmentation can be found at opencv_source_code/samples/cpp/meanshift_segmentation.cpp
|
||||
|
||||
sepFilter2D
|
||||
-----------
|
||||
Applies a separable linear filter to an image.
|
||||
|
||||
.. ocv:function:: void sepFilter2D( InputArray src, OutputArray dst, int ddepth, InputArray kernelX, InputArray kernelY, Point anchor=Point(-1,-1), double delta=0, int borderType=BORDER_DEFAULT )
|
||||
|
||||
.. ocv:pyfunction:: cv2.sepFilter2D(src, ddepth, kernelX, kernelY[, dst[, anchor[, delta[, borderType]]]]) -> dst
|
||||
|
||||
:param src: Source image.
|
||||
|
||||
:param dst: Destination image of the same size and the same number of channels as ``src`` .
|
||||
|
||||
:param ddepth: Destination image depth. The following combination of ``src.depth()`` and ``ddepth`` are supported:
|
||||
* ``src.depth()`` = ``CV_8U``, ``ddepth`` = -1/``CV_16S``/``CV_32F``/``CV_64F``
|
||||
* ``src.depth()`` = ``CV_16U``/``CV_16S``, ``ddepth`` = -1/``CV_32F``/``CV_64F``
|
||||
* ``src.depth()`` = ``CV_32F``, ``ddepth`` = -1/``CV_32F``/``CV_64F``
|
||||
* ``src.depth()`` = ``CV_64F``, ``ddepth`` = -1/``CV_64F``
|
||||
|
||||
when ``ddepth=-1``, the destination image will have the same depth as the source.
|
||||
|
||||
:param kernelX: Coefficients for filtering each row.
|
||||
|
||||
:param kernelY: Coefficients for filtering each column.
|
||||
|
||||
:param anchor: Anchor position within the kernel. The default value :math:`(-1,-1)` means that the anchor is at the kernel center.
|
||||
|
||||
:param delta: Value added to the filtered results before storing them.
|
||||
|
||||
:param borderType: Pixel extrapolation method. See ``borderInterpolate`` for details.
|
||||
|
||||
The function applies a separable linear filter to the image. That is, first, every row of ``src`` is filtered with the 1D kernel ``kernelX`` . Then, every column of the result is filtered with the 1D kernel ``kernelY`` . The final result shifted by ``delta`` is stored in ``dst`` .
|
||||
|
||||
.. seealso::
|
||||
|
||||
:ocv:func:`filter2D`,
|
||||
:ocv:func:`Sobel`,
|
||||
:ocv:func:`GaussianBlur`,
|
||||
:ocv:func:`boxFilter`,
|
||||
:ocv:func:`blur`
|
||||
|
||||
|
||||
Smooth
|
||||
------
|
||||
Smooths the image in one of several ways.
|
||||
|
||||
.. ocv:cfunction:: void cvSmooth( const CvArr* src, CvArr* dst, int smoothtype=CV_GAUSSIAN, int size1=3, int size2=0, double sigma1=0, double sigma2=0 )
|
||||
|
||||
:param src: The source image
|
||||
|
||||
:param dst: The destination image
|
||||
|
||||
:param smoothtype: Type of the smoothing:
|
||||
|
||||
* **CV_BLUR_NO_SCALE** linear convolution with :math:`\texttt{size1}\times\texttt{size2}` box kernel (all 1's). If you want to smooth different pixels with different-size box kernels, you can use the integral image that is computed using :ocv:func:`integral`
|
||||
|
||||
|
||||
* **CV_BLUR** linear convolution with :math:`\texttt{size1}\times\texttt{size2}` box kernel (all 1's) with subsequent scaling by :math:`1/(\texttt{size1}\cdot\texttt{size2})`
|
||||
|
||||
|
||||
* **CV_GAUSSIAN** linear convolution with a :math:`\texttt{size1}\times\texttt{size2}` Gaussian kernel
|
||||
|
||||
|
||||
* **CV_MEDIAN** median filter with a :math:`\texttt{size1}\times\texttt{size1}` square aperture
|
||||
|
||||
|
||||
* **CV_BILATERAL** bilateral filter with a :math:`\texttt{size1}\times\texttt{size1}` square aperture, color sigma= ``sigma1`` and spatial sigma= ``sigma2`` . If ``size1=0`` , the aperture square side is set to ``cvRound(sigma2*1.5)*2+1`` . Information about bilateral filtering can be found at http://www.dai.ed.ac.uk/CVonline/LOCAL\_COPIES/MANDUCHI1/Bilateral\_Filtering.html
|
||||
|
||||
|
||||
:param size1: The first parameter of the smoothing operation, the aperture width. Must be a positive odd number (1, 3, 5, ...)
|
||||
|
||||
:param size2: The second parameter of the smoothing operation, the aperture height. Ignored by ``CV_MEDIAN`` and ``CV_BILATERAL`` methods. In the case of simple scaled/non-scaled and Gaussian blur if ``size2`` is zero, it is set to ``size1`` . Otherwise it must be a positive odd number.
|
||||
|
||||
:param sigma1: In the case of a Gaussian parameter this parameter may specify Gaussian :math:`\sigma` (standard deviation). If it is zero, it is calculated from the kernel size:
|
||||
|
||||
.. math::
|
||||
|
||||
\sigma = 0.3 (n/2 - 1) + 0.8 \quad \text{where} \quad n= \begin{array}{l l} \mbox{\texttt{size1} for horizontal kernel} \\ \mbox{\texttt{size2} for vertical kernel} \end{array}
|
||||
|
||||
Using standard sigma for small kernels ( :math:`3\times 3` to :math:`7\times 7` ) gives better speed. If ``sigma1`` is not zero, while ``size1`` and ``size2`` are zeros, the kernel size is calculated from the sigma (to provide accurate enough operation).
|
||||
|
||||
The function smooths an image using one of several methods. Every of the methods has some features and restrictions listed below:
|
||||
|
||||
* Blur with no scaling works with single-channel images only and supports accumulation of 8-bit to 16-bit format (similar to :ocv:func:`Sobel` and :ocv:func:`Laplacian`) and 32-bit floating point to 32-bit floating-point format.
|
||||
|
||||
* Simple blur and Gaussian blur support 1- or 3-channel, 8-bit and 32-bit floating point images. These two methods can process images in-place.
|
||||
|
||||
* Median and bilateral filters work with 1- or 3-channel 8-bit images and can not process images in-place.
|
||||
|
||||
.. note:: The function is now obsolete. Use :ocv:func:`GaussianBlur`, :ocv:func:`blur`, :ocv:func:`medianBlur` or :ocv:func:`bilateralFilter`.
|
||||
|
||||
|
||||
Sobel
|
||||
-----
|
||||
Calculates the first, second, third, or mixed image derivatives using an extended Sobel operator.
|
||||
|
||||
.. ocv:function:: void Sobel( InputArray src, OutputArray dst, int ddepth, int dx, int dy, int ksize=3, double scale=1, double delta=0, int borderType=BORDER_DEFAULT )
|
||||
|
||||
.. ocv:pyfunction:: cv2.Sobel(src, ddepth, dx, dy[, dst[, ksize[, scale[, delta[, borderType]]]]]) -> dst
|
||||
|
||||
.. ocv:cfunction:: void cvSobel( const CvArr* src, CvArr* dst, int xorder, int yorder, int aperture_size=3 )
|
||||
|
||||
:param src: input image.
|
||||
|
||||
:param dst: output image of the same size and the same number of channels as ``src`` .
|
||||
|
||||
:param ddepth: output image depth; the following combinations of ``src.depth()`` and ``ddepth`` are supported:
|
||||
* ``src.depth()`` = ``CV_8U``, ``ddepth`` = -1/``CV_16S``/``CV_32F``/``CV_64F``
|
||||
* ``src.depth()`` = ``CV_16U``/``CV_16S``, ``ddepth`` = -1/``CV_32F``/``CV_64F``
|
||||
* ``src.depth()`` = ``CV_32F``, ``ddepth`` = -1/``CV_32F``/``CV_64F``
|
||||
* ``src.depth()`` = ``CV_64F``, ``ddepth`` = -1/``CV_64F``
|
||||
|
||||
when ``ddepth=-1``, the destination image will have the same depth as the source; in the case of 8-bit input images it will result in truncated derivatives.
|
||||
|
||||
:param xorder: order of the derivative x.
|
||||
|
||||
:param yorder: order of the derivative y.
|
||||
|
||||
:param ksize: size of the extended Sobel kernel; it must be 1, 3, 5, or 7.
|
||||
|
||||
:param scale: optional scale factor for the computed derivative values; by default, no scaling is applied (see :ocv:func:`getDerivKernels` for details).
|
||||
|
||||
:param delta: optional delta value that is added to the results prior to storing them in ``dst``.
|
||||
|
||||
:param borderType: pixel extrapolation method (see ``borderInterpolate`` for details).
|
||||
|
||||
In all cases except one, the
|
||||
:math:`\texttt{ksize} \times
|
||||
\texttt{ksize}` separable kernel is used to calculate the
|
||||
derivative. When
|
||||
:math:`\texttt{ksize = 1}` , the
|
||||
:math:`3 \times 1` or
|
||||
:math:`1 \times 3` kernel is used (that is, no Gaussian smoothing is done). ``ksize = 1`` can only be used for the first or the second x- or y- derivatives.
|
||||
|
||||
There is also the special value ``ksize = CV_SCHARR`` (-1) that corresponds to the
|
||||
:math:`3\times3` Scharr
|
||||
filter that may give more accurate results than the
|
||||
:math:`3\times3` Sobel. The Scharr aperture is
|
||||
|
||||
.. math::
|
||||
|
||||
\vecthreethree{-3}{0}{3}{-10}{0}{10}{-3}{0}{3}
|
||||
|
||||
for the x-derivative, or transposed for the y-derivative.
|
||||
|
||||
The function calculates an image derivative by convolving the image with the appropriate kernel:
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{dst} = \frac{\partial^{xorder+yorder} \texttt{src}}{\partial x^{xorder} \partial y^{yorder}}
|
||||
|
||||
The Sobel operators combine Gaussian smoothing and differentiation,
|
||||
so the result is more or less resistant to the noise. Most often,
|
||||
the function is called with ( ``xorder`` = 1, ``yorder`` = 0, ``ksize`` = 3) or ( ``xorder`` = 0, ``yorder`` = 1, ``ksize`` = 3) to calculate the first x- or y- image
|
||||
derivative. The first case corresponds to a kernel of:
|
||||
|
||||
.. math::
|
||||
|
||||
\vecthreethree{-1}{0}{1}{-2}{0}{2}{-1}{0}{1}
|
||||
|
||||
The second case corresponds to a kernel of:
|
||||
|
||||
.. math::
|
||||
|
||||
\vecthreethree{-1}{-2}{-1}{0}{0}{0}{1}{2}{1}
|
||||
|
||||
.. seealso::
|
||||
|
||||
:ocv:func:`Scharr`,
|
||||
:ocv:func:`Laplacian`,
|
||||
:ocv:func:`sepFilter2D`,
|
||||
:ocv:func:`filter2D`,
|
||||
:ocv:func:`GaussianBlur`,
|
||||
:ocv:func:`cartToPolar`
|
||||
|
||||
|
||||
|
||||
Scharr
|
||||
------
|
||||
Calculates the first x- or y- image derivative using Scharr operator.
|
||||
|
||||
.. ocv:function:: void Scharr( InputArray src, OutputArray dst, int ddepth, int dx, int dy, double scale=1, double delta=0, int borderType=BORDER_DEFAULT )
|
||||
|
||||
.. ocv:pyfunction:: cv2.Scharr(src, ddepth, dx, dy[, dst[, scale[, delta[, borderType]]]]) -> dst
|
||||
|
||||
:param src: input image.
|
||||
|
||||
:param dst: output image of the same size and the same number of channels as ``src``.
|
||||
|
||||
:param ddepth: output image depth (see :ocv:func:`Sobel` for the list of supported combination of ``src.depth()`` and ``ddepth``).
|
||||
|
||||
:param dx: order of the derivative x.
|
||||
|
||||
:param dy: order of the derivative y.
|
||||
|
||||
:param scale: optional scale factor for the computed derivative values; by default, no scaling is applied (see :ocv:func:`getDerivKernels` for details).
|
||||
|
||||
:param delta: optional delta value that is added to the results prior to storing them in ``dst``.
|
||||
|
||||
:param borderType: pixel extrapolation method (see ``borderInterpolate`` for details).
|
||||
|
||||
The function computes the first x- or y- spatial image derivative using the Scharr operator. The call
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{Scharr(src, dst, ddepth, dx, dy, scale, delta, borderType)}
|
||||
|
||||
is equivalent to
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{Sobel(src, dst, ddepth, dx, dy, CV\_SCHARR, scale, delta, borderType)} .
|
||||
|
||||
.. seealso::
|
||||
|
||||
:ocv:func:`cartToPolar`
|
||||
@@ -1,735 +0,0 @@
|
||||
Geometric Image Transformations
|
||||
===============================
|
||||
.. highlight:: cpp
|
||||
|
||||
The functions in this section perform various geometrical transformations of 2D images. They do not change the image content but deform the pixel grid and map this deformed grid to the destination image. In fact, to avoid sampling artifacts, the mapping is done in the reverse order, from destination to the source. That is, for each pixel :math:`(x, y)` of the destination image, the functions compute coordinates of the corresponding "donor" pixel in the source image and copy the pixel value:
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{dst} (x,y)= \texttt{src} (f_x(x,y), f_y(x,y))
|
||||
|
||||
In case when you specify the forward mapping
|
||||
:math:`\left<g_x, g_y\right>: \texttt{src} \rightarrow \texttt{dst}` , the OpenCV functions first compute the corresponding inverse mapping
|
||||
:math:`\left<f_x, f_y\right>: \texttt{dst} \rightarrow \texttt{src}` and then use the above formula.
|
||||
|
||||
The actual implementations of the geometrical transformations, from the most generic
|
||||
:ocv:func:`remap` and to the simplest and the fastest
|
||||
:ocv:func:`resize` , need to solve two main problems with the above formula:
|
||||
|
||||
*
|
||||
Extrapolation of non-existing pixels. Similarly to the filtering functions described in the previous section, for some
|
||||
:math:`(x,y)` , either one of
|
||||
:math:`f_x(x,y)` , or
|
||||
:math:`f_y(x,y)` , or both of them may fall outside of the image. In this case, an extrapolation method needs to be used. OpenCV provides the same selection of extrapolation methods as in the filtering functions. In addition, it provides the method ``BORDER_TRANSPARENT`` . This means that the corresponding pixels in the destination image will not be modified at all.
|
||||
|
||||
*
|
||||
Interpolation of pixel values. Usually
|
||||
:math:`f_x(x,y)` and
|
||||
:math:`f_y(x,y)` are floating-point numbers. This means that
|
||||
:math:`\left<f_x, f_y\right>` can be either an affine or perspective transformation, or radial lens distortion correction, and so on. So, a pixel value at fractional coordinates needs to be retrieved. In the simplest case, the coordinates can be just rounded to the nearest integer coordinates and the corresponding pixel can be used. This is called a nearest-neighbor interpolation. However, a better result can be achieved by using more sophisticated `interpolation methods <http://en.wikipedia.org/wiki/Multivariate_interpolation>`_
|
||||
, where a polynomial function is fit into some neighborhood of the computed pixel
|
||||
:math:`(f_x(x,y), f_y(x,y))` , and then the value of the polynomial at
|
||||
:math:`(f_x(x,y), f_y(x,y))` is taken as the interpolated pixel value. In OpenCV, you can choose between several interpolation methods. See
|
||||
:ocv:func:`resize` for details.
|
||||
|
||||
convertMaps
|
||||
-----------
|
||||
Converts image transformation maps from one representation to another.
|
||||
|
||||
.. ocv:function:: void convertMaps( InputArray map1, InputArray map2, OutputArray dstmap1, OutputArray dstmap2, int dstmap1type, bool nninterpolation=false )
|
||||
|
||||
.. ocv:pyfunction:: cv2.convertMaps(map1, map2, dstmap1type[, dstmap1[, dstmap2[, nninterpolation]]]) -> dstmap1, dstmap2
|
||||
|
||||
:param map1: The first input map of type ``CV_16SC2`` , ``CV_32FC1`` , or ``CV_32FC2`` .
|
||||
|
||||
:param map2: The second input map of type ``CV_16UC1`` , ``CV_32FC1`` , or none (empty matrix), respectively.
|
||||
|
||||
:param dstmap1: The first output map that has the type ``dstmap1type`` and the same size as ``src`` .
|
||||
|
||||
:param dstmap2: The second output map.
|
||||
|
||||
:param dstmap1type: Type of the first output map that should be ``CV_16SC2`` , ``CV_32FC1`` , or ``CV_32FC2`` .
|
||||
|
||||
:param nninterpolation: Flag indicating whether the fixed-point maps are used for the nearest-neighbor or for a more complex interpolation.
|
||||
|
||||
The function converts a pair of maps for
|
||||
:ocv:func:`remap` from one representation to another. The following options ( ``(map1.type(), map2.type())`` :math:`\rightarrow` ``(dstmap1.type(), dstmap2.type())`` ) are supported:
|
||||
|
||||
*
|
||||
:math:`\texttt{(CV\_32FC1, CV\_32FC1)} \rightarrow \texttt{(CV\_16SC2, CV\_16UC1)}` . This is the most frequently used conversion operation, in which the original floating-point maps (see
|
||||
:ocv:func:`remap` ) are converted to a more compact and much faster fixed-point representation. The first output array contains the rounded coordinates and the second array (created only when ``nninterpolation=false`` ) contains indices in the interpolation tables.
|
||||
|
||||
*
|
||||
:math:`\texttt{(CV\_32FC2)} \rightarrow \texttt{(CV\_16SC2, CV\_16UC1)}` . The same as above but the original maps are stored in one 2-channel matrix.
|
||||
|
||||
*
|
||||
Reverse conversion. Obviously, the reconstructed floating-point maps will not be exactly the same as the originals.
|
||||
|
||||
.. seealso::
|
||||
|
||||
:ocv:func:`remap`,
|
||||
:ocv:func:`undistort`,
|
||||
:ocv:func:`initUndistortRectifyMap`
|
||||
|
||||
|
||||
|
||||
getAffineTransform
|
||||
----------------------
|
||||
Calculates an affine transform from three pairs of the corresponding points.
|
||||
|
||||
.. ocv:function:: Mat getAffineTransform( InputArray src, InputArray dst )
|
||||
|
||||
.. ocv:function:: Mat getAffineTransform( const Point2f src[], const Point2f dst[] )
|
||||
|
||||
.. ocv:pyfunction:: cv2.getAffineTransform(src, dst) -> retval
|
||||
|
||||
.. ocv:cfunction:: CvMat* cvGetAffineTransform( const CvPoint2D32f * src, const CvPoint2D32f * dst, CvMat * map_matrix )
|
||||
|
||||
:param src: Coordinates of triangle vertices in the source image.
|
||||
|
||||
:param dst: Coordinates of the corresponding triangle vertices in the destination image.
|
||||
|
||||
The function calculates the :math:`2 \times 3` matrix of an affine transform so that:
|
||||
|
||||
.. math::
|
||||
|
||||
\begin{bmatrix} x'_i \\ y'_i \end{bmatrix} = \texttt{map\_matrix} \cdot \begin{bmatrix} x_i \\ y_i \\ 1 \end{bmatrix}
|
||||
|
||||
where
|
||||
|
||||
.. math::
|
||||
|
||||
dst(i)=(x'_i,y'_i),
|
||||
src(i)=(x_i, y_i),
|
||||
i=0,1,2
|
||||
|
||||
.. seealso::
|
||||
|
||||
:ocv:func:`warpAffine`,
|
||||
:ocv:func:`transform`
|
||||
|
||||
|
||||
|
||||
getPerspectiveTransform
|
||||
---------------------------
|
||||
Calculates a perspective transform from four pairs of the corresponding points.
|
||||
|
||||
.. ocv:function:: Mat getPerspectiveTransform( InputArray src, InputArray dst )
|
||||
|
||||
.. ocv:function:: Mat getPerspectiveTransform( const Point2f src[], const Point2f dst[] )
|
||||
|
||||
.. ocv:pyfunction:: cv2.getPerspectiveTransform(src, dst) -> retval
|
||||
|
||||
.. ocv:cfunction:: CvMat* cvGetPerspectiveTransform( const CvPoint2D32f* src, const CvPoint2D32f* dst, CvMat* map_matrix )
|
||||
|
||||
:param src: Coordinates of quadrangle vertices in the source image.
|
||||
|
||||
:param dst: Coordinates of the corresponding quadrangle vertices in the destination image.
|
||||
|
||||
The function calculates the :math:`3 \times 3` matrix of a perspective transform so that:
|
||||
|
||||
.. math::
|
||||
|
||||
\begin{bmatrix} t_i x'_i \\ t_i y'_i \\ t_i \end{bmatrix} = \texttt{map\_matrix} \cdot \begin{bmatrix} x_i \\ y_i \\ 1 \end{bmatrix}
|
||||
|
||||
where
|
||||
|
||||
.. math::
|
||||
|
||||
dst(i)=(x'_i,y'_i),
|
||||
src(i)=(x_i, y_i),
|
||||
i=0,1,2,3
|
||||
|
||||
.. seealso::
|
||||
|
||||
:ocv:func:`findHomography`,
|
||||
:ocv:func:`warpPerspective`,
|
||||
:ocv:func:`perspectiveTransform`
|
||||
|
||||
|
||||
getRectSubPix
|
||||
-----------------
|
||||
Retrieves a pixel rectangle from an image with sub-pixel accuracy.
|
||||
|
||||
.. ocv:function:: void getRectSubPix( InputArray image, Size patchSize, Point2f center, OutputArray patch, int patchType=-1 )
|
||||
|
||||
.. ocv:pyfunction:: cv2.getRectSubPix(image, patchSize, center[, patch[, patchType]]) -> patch
|
||||
|
||||
.. ocv:cfunction:: void cvGetRectSubPix( const CvArr* src, CvArr* dst, CvPoint2D32f center )
|
||||
|
||||
:param src: Source image.
|
||||
|
||||
:param patchSize: Size of the extracted patch.
|
||||
|
||||
:param center: Floating point coordinates of the center of the extracted rectangle within the source image. The center must be inside the image.
|
||||
|
||||
:param dst: Extracted patch that has the size ``patchSize`` and the same number of channels as ``src`` .
|
||||
|
||||
:param patchType: Depth of the extracted pixels. By default, they have the same depth as ``src`` .
|
||||
|
||||
The function ``getRectSubPix`` extracts pixels from ``src`` :
|
||||
|
||||
.. math::
|
||||
|
||||
dst(x, y) = src(x + \texttt{center.x} - ( \texttt{dst.cols} -1)*0.5, y + \texttt{center.y} - ( \texttt{dst.rows} -1)*0.5)
|
||||
|
||||
where the values of the pixels at non-integer coordinates are retrieved
|
||||
using bilinear interpolation. Every channel of multi-channel
|
||||
images is processed independently. While the center of the rectangle
|
||||
must be inside the image, parts of the rectangle may be
|
||||
outside. In this case, the replication border mode (see
|
||||
:ocv:func:`borderInterpolate` ) is used to extrapolate
|
||||
the pixel values outside of the image.
|
||||
|
||||
.. seealso::
|
||||
|
||||
:ocv:func:`warpAffine`,
|
||||
:ocv:func:`warpPerspective`
|
||||
|
||||
|
||||
getRotationMatrix2D
|
||||
-----------------------
|
||||
Calculates an affine matrix of 2D rotation.
|
||||
|
||||
.. ocv:function:: Mat getRotationMatrix2D( Point2f center, double angle, double scale )
|
||||
|
||||
.. ocv:pyfunction:: cv2.getRotationMatrix2D(center, angle, scale) -> retval
|
||||
|
||||
.. ocv:cfunction:: CvMat* cv2DRotationMatrix( CvPoint2D32f center, double angle, double scale, CvMat* map_matrix )
|
||||
|
||||
:param center: Center of the rotation in the source image.
|
||||
|
||||
:param angle: Rotation angle in degrees. Positive values mean counter-clockwise rotation (the coordinate origin is assumed to be the top-left corner).
|
||||
|
||||
:param scale: Isotropic scale factor.
|
||||
|
||||
:param map_matrix: The output affine transformation, 2x3 floating-point matrix.
|
||||
|
||||
The function calculates the following matrix:
|
||||
|
||||
.. math::
|
||||
|
||||
\begin{bmatrix} \alpha & \beta & (1- \alpha ) \cdot \texttt{center.x} - \beta \cdot \texttt{center.y} \\ - \beta & \alpha & \beta \cdot \texttt{center.x} + (1- \alpha ) \cdot \texttt{center.y} \end{bmatrix}
|
||||
|
||||
where
|
||||
|
||||
.. math::
|
||||
|
||||
\begin{array}{l} \alpha = \texttt{scale} \cdot \cos \texttt{angle} , \\ \beta = \texttt{scale} \cdot \sin \texttt{angle} \end{array}
|
||||
|
||||
The transformation maps the rotation center to itself. If this is not the target, adjust the shift.
|
||||
|
||||
.. seealso::
|
||||
|
||||
:ocv:func:`getAffineTransform`,
|
||||
:ocv:func:`warpAffine`,
|
||||
:ocv:func:`transform`
|
||||
|
||||
|
||||
|
||||
invertAffineTransform
|
||||
-------------------------
|
||||
Inverts an affine transformation.
|
||||
|
||||
.. ocv:function:: void invertAffineTransform(InputArray M, OutputArray iM)
|
||||
|
||||
.. ocv:pyfunction:: cv2.invertAffineTransform(M[, iM]) -> iM
|
||||
|
||||
:param M: Original affine transformation.
|
||||
|
||||
:param iM: Output reverse affine transformation.
|
||||
|
||||
The function computes an inverse affine transformation represented by
|
||||
:math:`2 \times 3` matrix ``M`` :
|
||||
|
||||
.. math::
|
||||
|
||||
\begin{bmatrix} a_{11} & a_{12} & b_1 \\ a_{21} & a_{22} & b_2 \end{bmatrix}
|
||||
|
||||
The result is also a
|
||||
:math:`2 \times 3` matrix of the same type as ``M`` .
|
||||
|
||||
LinearPolar
|
||||
-----------
|
||||
Remaps an image to polar space.
|
||||
|
||||
.. ocv:cfunction:: void cvLinearPolar( const CvArr* src, CvArr* dst, CvPoint2D32f center, double maxRadius, int flags=CV_INTER_LINEAR+CV_WARP_FILL_OUTLIERS )
|
||||
|
||||
:param src: Source image
|
||||
|
||||
:param dst: Destination image
|
||||
|
||||
:param center: The transformation center;
|
||||
|
||||
:param maxRadius: Inverse magnitude scale parameter. See below
|
||||
|
||||
:param flags: A combination of interpolation methods and the following optional flags:
|
||||
|
||||
* **CV_WARP_FILL_OUTLIERS** fills all of the destination image pixels. If some of them correspond to outliers in the source image, they are set to zero
|
||||
|
||||
* **CV_WARP_INVERSE_MAP** See below
|
||||
|
||||
The function ``cvLinearPolar`` transforms the source image using the following transformation:
|
||||
|
||||
*
|
||||
Forward transformation (``CV_WARP_INVERSE_MAP`` is not set):
|
||||
|
||||
.. math::
|
||||
|
||||
dst( \phi , \rho ) = src(x,y)
|
||||
|
||||
|
||||
*
|
||||
Inverse transformation (``CV_WARP_INVERSE_MAP`` is set):
|
||||
|
||||
.. math::
|
||||
|
||||
dst(x,y) = src( \phi , \rho )
|
||||
|
||||
|
||||
where
|
||||
|
||||
.. math::
|
||||
|
||||
\rho = (src.width/maxRadius) \cdot \sqrt{x^2 + y^2} , \phi =atan(y/x)
|
||||
|
||||
|
||||
The function can not operate in-place.
|
||||
|
||||
.. note::
|
||||
|
||||
* An example using the LinearPolar operation can be found at opencv_source_code/samples/c/polar_transforms.c
|
||||
|
||||
|
||||
|
||||
LogPolar
|
||||
--------
|
||||
Remaps an image to log-polar space.
|
||||
|
||||
.. ocv:cfunction:: void cvLogPolar( const CvArr* src, CvArr* dst, CvPoint2D32f center, double M, int flags=CV_INTER_LINEAR+CV_WARP_FILL_OUTLIERS )
|
||||
|
||||
:param src: Source image
|
||||
|
||||
:param dst: Destination image
|
||||
|
||||
:param center: The transformation center; where the output precision is maximal
|
||||
|
||||
:param M: Magnitude scale parameter. See below
|
||||
|
||||
:param flags: A combination of interpolation methods and the following optional flags:
|
||||
|
||||
* **CV_WARP_FILL_OUTLIERS** fills all of the destination image pixels. If some of them correspond to outliers in the source image, they are set to zero
|
||||
|
||||
* **CV_WARP_INVERSE_MAP** See below
|
||||
|
||||
The function ``cvLogPolar`` transforms the source image using the following transformation:
|
||||
|
||||
*
|
||||
Forward transformation (``CV_WARP_INVERSE_MAP`` is not set):
|
||||
|
||||
.. math::
|
||||
|
||||
dst( \phi , \rho ) = src(x,y)
|
||||
|
||||
|
||||
*
|
||||
Inverse transformation (``CV_WARP_INVERSE_MAP`` is set):
|
||||
|
||||
.. math::
|
||||
|
||||
dst(x,y) = src( \phi , \rho )
|
||||
|
||||
|
||||
where
|
||||
|
||||
.. math::
|
||||
|
||||
\rho = M \cdot \log{\sqrt{x^2 + y^2}} , \phi =atan(y/x)
|
||||
|
||||
|
||||
The function emulates the human "foveal" vision and can be used for fast scale and rotation-invariant template matching, for object tracking and so forth. The function can not operate in-place.
|
||||
|
||||
.. note::
|
||||
|
||||
* An example using the geometric logpolar operation in 4 applications can be found at opencv_source_code/samples/cpp/logpolar_bsm.cpp
|
||||
|
||||
remap
|
||||
-----
|
||||
Applies a generic geometrical transformation to an image.
|
||||
|
||||
.. ocv:function:: void remap( InputArray src, OutputArray dst, InputArray map1, InputArray map2, int interpolation, int borderMode=BORDER_CONSTANT, const Scalar& borderValue=Scalar())
|
||||
|
||||
.. ocv:pyfunction:: cv2.remap(src, map1, map2, interpolation[, dst[, borderMode[, borderValue]]]) -> dst
|
||||
|
||||
.. ocv:cfunction:: void cvRemap( const CvArr* src, CvArr* dst, const CvArr* mapx, const CvArr* mapy, int flags=CV_INTER_LINEAR+CV_WARP_FILL_OUTLIERS, CvScalar fillval=cvScalarAll(0) )
|
||||
|
||||
:param src: Source image.
|
||||
|
||||
:param dst: Destination image. It has the same size as ``map1`` and the same type as ``src`` .
|
||||
:param map1: The first map of either ``(x,y)`` points or just ``x`` values having the type ``CV_16SC2`` , ``CV_32FC1`` , or ``CV_32FC2`` . See :ocv:func:`convertMaps` for details on converting a floating point representation to fixed-point for speed.
|
||||
|
||||
:param map2: The second map of ``y`` values having the type ``CV_16UC1`` , ``CV_32FC1`` , or none (empty map if ``map1`` is ``(x,y)`` points), respectively.
|
||||
|
||||
:param interpolation: Interpolation method (see :ocv:func:`resize` ). The method ``INTER_AREA`` is not supported by this function.
|
||||
|
||||
:param borderMode: Pixel extrapolation method (see :ocv:func:`borderInterpolate` ). When \ ``borderMode=BORDER_TRANSPARENT`` , it means that the pixels in the destination image that corresponds to the "outliers" in the source image are not modified by the function.
|
||||
|
||||
:param borderValue: Value used in case of a constant border. By default, it is 0.
|
||||
|
||||
The function ``remap`` transforms the source image using the specified map:
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{dst} (x,y) = \texttt{src} (map_x(x,y),map_y(x,y))
|
||||
|
||||
where values of pixels with non-integer coordinates are computed using one of available interpolation methods.
|
||||
:math:`map_x` and
|
||||
:math:`map_y` can be encoded as separate floating-point maps in
|
||||
:math:`map_1` and
|
||||
:math:`map_2` respectively, or interleaved floating-point maps of
|
||||
:math:`(x,y)` in
|
||||
:math:`map_1` , or
|
||||
fixed-point maps created by using
|
||||
:ocv:func:`convertMaps` . The reason you might want to convert from floating to fixed-point
|
||||
representations of a map is that they can yield much faster (~2x) remapping operations. In the converted case,
|
||||
:math:`map_1` contains pairs ``(cvFloor(x), cvFloor(y))`` and
|
||||
:math:`map_2` contains indices in a table of interpolation coefficients.
|
||||
|
||||
This function cannot operate in-place.
|
||||
|
||||
|
||||
|
||||
resize
|
||||
------
|
||||
Resizes an image.
|
||||
|
||||
.. ocv:function:: void resize( InputArray src, OutputArray dst, Size dsize, double fx=0, double fy=0, int interpolation=INTER_LINEAR )
|
||||
|
||||
.. ocv:pyfunction:: cv2.resize(src, dsize[, dst[, fx[, fy[, interpolation]]]]) -> dst
|
||||
|
||||
.. ocv:cfunction:: void cvResize( const CvArr* src, CvArr* dst, int interpolation=CV_INTER_LINEAR )
|
||||
|
||||
:param src: input image.
|
||||
|
||||
:param dst: output image; it has the size ``dsize`` (when it is non-zero) or the size computed from ``src.size()``, ``fx``, and ``fy``; the type of ``dst`` is the same as of ``src``.
|
||||
|
||||
:param dsize: output image size; if it equals zero, it is computed as:
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{dsize = Size(round(fx*src.cols), round(fy*src.rows))}
|
||||
|
||||
|
||||
Either ``dsize`` or both ``fx`` and ``fy`` must be non-zero.
|
||||
|
||||
:param fx: scale factor along the horizontal axis; when it equals 0, it is computed as
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{(double)dsize.width/src.cols}
|
||||
|
||||
:param fy: scale factor along the vertical axis; when it equals 0, it is computed as
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{(double)dsize.height/src.rows}
|
||||
|
||||
:param interpolation: interpolation method:
|
||||
|
||||
* **INTER_NEAREST** - a nearest-neighbor interpolation
|
||||
|
||||
* **INTER_LINEAR** - a bilinear interpolation (used by default)
|
||||
|
||||
* **INTER_AREA** - resampling using pixel area relation. It may be a preferred method for image decimation, as it gives moire'-free results. But when the image is zoomed, it is similar to the ``INTER_NEAREST`` method.
|
||||
|
||||
* **INTER_CUBIC** - a bicubic interpolation over 4x4 pixel neighborhood
|
||||
|
||||
* **INTER_LANCZOS4** - a Lanczos interpolation over 8x8 pixel neighborhood
|
||||
|
||||
The function ``resize`` resizes the image ``src`` down to or up to the specified size.
|
||||
Note that the initial ``dst`` type or size are not taken into account. Instead, the size and type are derived from the ``src``,``dsize``,``fx`` , and ``fy`` . If you want to resize ``src`` so that it fits the pre-created ``dst`` , you may call the function as follows: ::
|
||||
|
||||
// explicitly specify dsize=dst.size(); fx and fy will be computed from that.
|
||||
resize(src, dst, dst.size(), 0, 0, interpolation);
|
||||
|
||||
|
||||
If you want to decimate the image by factor of 2 in each direction, you can call the function this way: ::
|
||||
|
||||
// specify fx and fy and let the function compute the destination image size.
|
||||
resize(src, dst, Size(), 0.5, 0.5, interpolation);
|
||||
|
||||
To shrink an image, it will generally look best with CV_INTER_AREA interpolation, whereas to enlarge an image, it will generally look best with CV_INTER_CUBIC (slow) or CV_INTER_LINEAR (faster but still looks OK).
|
||||
|
||||
.. seealso::
|
||||
|
||||
:ocv:func:`warpAffine`,
|
||||
:ocv:func:`warpPerspective`,
|
||||
:ocv:func:`remap`
|
||||
|
||||
|
||||
warpAffine
|
||||
----------
|
||||
Applies an affine transformation to an image.
|
||||
|
||||
.. ocv:function:: void warpAffine( InputArray src, OutputArray dst, InputArray M, Size dsize, int flags=INTER_LINEAR, int borderMode=BORDER_CONSTANT, const Scalar& borderValue=Scalar())
|
||||
|
||||
.. ocv:pyfunction:: cv2.warpAffine(src, M, dsize[, dst[, flags[, borderMode[, borderValue]]]]) -> dst
|
||||
|
||||
.. ocv:cfunction:: void cvWarpAffine( const CvArr* src, CvArr* dst, const CvMat* map_matrix, int flags=CV_INTER_LINEAR+CV_WARP_FILL_OUTLIERS, CvScalar fillval=cvScalarAll(0) )
|
||||
|
||||
.. ocv:cfunction:: void cvGetQuadrangleSubPix( const CvArr* src, CvArr* dst, const CvMat* map_matrix )
|
||||
|
||||
:param src: input image.
|
||||
|
||||
:param dst: output image that has the size ``dsize`` and the same type as ``src`` .
|
||||
|
||||
:param M: :math:`2\times 3` transformation matrix.
|
||||
|
||||
:param dsize: size of the output image.
|
||||
|
||||
:param flags: combination of interpolation methods (see :ocv:func:`resize` ) and the optional flag ``WARP_INVERSE_MAP`` that means that ``M`` is the inverse transformation ( :math:`\texttt{dst}\rightarrow\texttt{src}` ).
|
||||
|
||||
:param borderMode: pixel extrapolation method (see :ocv:func:`borderInterpolate`); when \ ``borderMode=BORDER_TRANSPARENT`` , it means that the pixels in the destination image corresponding to the "outliers" in the source image are not modified by the function.
|
||||
|
||||
:param borderValue: value used in case of a constant border; by default, it is 0.
|
||||
|
||||
The function ``warpAffine`` transforms the source image using the specified matrix:
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{dst} (x,y) = \texttt{src} ( \texttt{M} _{11} x + \texttt{M} _{12} y + \texttt{M} _{13}, \texttt{M} _{21} x + \texttt{M} _{22} y + \texttt{M} _{23})
|
||||
|
||||
when the flag ``WARP_INVERSE_MAP`` is set. Otherwise, the transformation is first inverted with
|
||||
:ocv:func:`invertAffineTransform` and then put in the formula above instead of ``M`` .
|
||||
The function cannot operate in-place.
|
||||
|
||||
.. seealso::
|
||||
|
||||
:ocv:func:`warpPerspective`,
|
||||
:ocv:func:`resize`,
|
||||
:ocv:func:`remap`,
|
||||
:ocv:func:`getRectSubPix`,
|
||||
:ocv:func:`transform`
|
||||
|
||||
|
||||
.. note:: ``cvGetQuadrangleSubPix`` is similar to ``cvWarpAffine``, but the outliers are extrapolated using replication border mode.
|
||||
|
||||
warpPerspective
|
||||
---------------
|
||||
Applies a perspective transformation to an image.
|
||||
|
||||
.. ocv:function:: void warpPerspective( InputArray src, OutputArray dst, InputArray M, Size dsize, int flags=INTER_LINEAR, int borderMode=BORDER_CONSTANT, const Scalar& borderValue=Scalar())
|
||||
|
||||
.. ocv:pyfunction:: cv2.warpPerspective(src, M, dsize[, dst[, flags[, borderMode[, borderValue]]]]) -> dst
|
||||
|
||||
.. ocv:cfunction:: void cvWarpPerspective( const CvArr* src, CvArr* dst, const CvMat* map_matrix, int flags=CV_INTER_LINEAR+CV_WARP_FILL_OUTLIERS, CvScalar fillval=cvScalarAll(0) )
|
||||
|
||||
:param src: input image.
|
||||
|
||||
:param dst: output image that has the size ``dsize`` and the same type as ``src`` .
|
||||
|
||||
:param M: :math:`3\times 3` transformation matrix.
|
||||
|
||||
:param dsize: size of the output image.
|
||||
|
||||
:param flags: combination of interpolation methods (``INTER_LINEAR`` or ``INTER_NEAREST``) and the optional flag ``WARP_INVERSE_MAP``, that sets ``M`` as the inverse transformation ( :math:`\texttt{dst}\rightarrow\texttt{src}` ).
|
||||
|
||||
:param borderMode: pixel extrapolation method (``BORDER_CONSTANT`` or ``BORDER_REPLICATE``).
|
||||
|
||||
:param borderValue: value used in case of a constant border; by default, it equals 0.
|
||||
|
||||
The function ``warpPerspective`` transforms the source image using the specified matrix:
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{dst} (x,y) = \texttt{src} \left ( \frac{M_{11} x + M_{12} y + M_{13}}{M_{31} x + M_{32} y + M_{33}} ,
|
||||
\frac{M_{21} x + M_{22} y + M_{23}}{M_{31} x + M_{32} y + M_{33}} \right )
|
||||
|
||||
when the flag ``WARP_INVERSE_MAP`` is set. Otherwise, the transformation is first inverted with
|
||||
:ocv:func:`invert` and then put in the formula above instead of ``M`` .
|
||||
The function cannot operate in-place.
|
||||
|
||||
.. seealso::
|
||||
|
||||
:ocv:func:`warpAffine`,
|
||||
:ocv:func:`resize`,
|
||||
:ocv:func:`remap`,
|
||||
:ocv:func:`getRectSubPix`,
|
||||
:ocv:func:`perspectiveTransform`
|
||||
|
||||
|
||||
|
||||
|
||||
initUndistortRectifyMap
|
||||
-----------------------
|
||||
Computes the undistortion and rectification transformation map.
|
||||
|
||||
.. ocv:function:: void initUndistortRectifyMap( InputArray cameraMatrix, InputArray distCoeffs, InputArray R, InputArray newCameraMatrix, Size size, int m1type, OutputArray map1, OutputArray map2 )
|
||||
|
||||
.. ocv:pyfunction:: cv2.initUndistortRectifyMap(cameraMatrix, distCoeffs, R, newCameraMatrix, size, m1type[, map1[, map2]]) -> map1, map2
|
||||
|
||||
.. ocv:cfunction:: void cvInitUndistortRectifyMap( const CvMat* camera_matrix, const CvMat* dist_coeffs, const CvMat * R, const CvMat* new_camera_matrix, CvArr* mapx, CvArr* mapy )
|
||||
.. ocv:cfunction:: void cvInitUndistortMap( const CvMat* camera_matrix, const CvMat* distortion_coeffs, CvArr* mapx, CvArr* mapy )
|
||||
|
||||
:param cameraMatrix: Input camera matrix :math:`A=\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}` .
|
||||
|
||||
:param distCoeffs: Input vector of distortion coefficients :math:`(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6]])` of 4, 5, or 8 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed.
|
||||
|
||||
:param R: Optional rectification transformation in the object space (3x3 matrix). ``R1`` or ``R2`` , computed by :ocv:func:`stereoRectify` can be passed here. If the matrix is empty, the identity transformation is assumed. In ``cvInitUndistortMap`` R assumed to be an identity matrix.
|
||||
|
||||
:param newCameraMatrix: New camera matrix :math:`A'=\vecthreethree{f_x'}{0}{c_x'}{0}{f_y'}{c_y'}{0}{0}{1}` .
|
||||
|
||||
:param size: Undistorted image size.
|
||||
|
||||
:param m1type: Type of the first output map that can be ``CV_32FC1`` or ``CV_16SC2`` . See :ocv:func:`convertMaps` for details.
|
||||
|
||||
:param map1: The first output map.
|
||||
|
||||
:param map2: The second output map.
|
||||
|
||||
The function computes the joint undistortion and rectification transformation and represents the result in the form of maps for
|
||||
:ocv:func:`remap` . The undistorted image looks like original, as if it is captured with a camera using the camera matrix ``=newCameraMatrix`` and zero distortion. In case of a monocular camera, ``newCameraMatrix`` is usually equal to ``cameraMatrix`` , or it can be computed by
|
||||
:ocv:func:`getOptimalNewCameraMatrix` for a better control over scaling. In case of a stereo camera, ``newCameraMatrix`` is normally set to ``P1`` or ``P2`` computed by
|
||||
:ocv:func:`stereoRectify` .
|
||||
|
||||
Also, this new camera is oriented differently in the coordinate space, according to ``R`` . That, for example, helps to align two heads of a stereo camera so that the epipolar lines on both images become horizontal and have the same y- coordinate (in case of a horizontally aligned stereo camera).
|
||||
|
||||
The function actually builds the maps for the inverse mapping algorithm that is used by
|
||||
:ocv:func:`remap` . That is, for each pixel
|
||||
:math:`(u, v)` in the destination (corrected and rectified) image, the function computes the corresponding coordinates in the source image (that is, in the original image from camera). The following process is applied:
|
||||
|
||||
.. math::
|
||||
|
||||
\begin{array}{l} x \leftarrow (u - {c'}_x)/{f'}_x \\ y \leftarrow (v - {c'}_y)/{f'}_y \\{[X\,Y\,W]} ^T \leftarrow R^{-1}*[x \, y \, 1]^T \\ x' \leftarrow X/W \\ y' \leftarrow Y/W \\ x" \leftarrow x' (1 + k_1 r^2 + k_2 r^4 + k_3 r^6) + 2p_1 x' y' + p_2(r^2 + 2 x'^2) \\ y" \leftarrow y' (1 + k_1 r^2 + k_2 r^4 + k_3 r^6) + p_1 (r^2 + 2 y'^2) + 2 p_2 x' y' \\ map_x(u,v) \leftarrow x" f_x + c_x \\ map_y(u,v) \leftarrow y" f_y + c_y \end{array}
|
||||
|
||||
where
|
||||
:math:`(k_1, k_2, p_1, p_2[, k_3])` are the distortion coefficients.
|
||||
|
||||
In case of a stereo camera, this function is called twice: once for each camera head, after
|
||||
:ocv:func:`stereoRectify` , which in its turn is called after
|
||||
:ocv:func:`stereoCalibrate` . But if the stereo camera was not calibrated, it is still possible to compute the rectification transformations directly from the fundamental matrix using
|
||||
:ocv:func:`stereoRectifyUncalibrated` . For each camera, the function computes homography ``H`` as the rectification transformation in a pixel domain, not a rotation matrix ``R`` in 3D space. ``R`` can be computed from ``H`` as
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{R} = \texttt{cameraMatrix} ^{-1} \cdot \texttt{H} \cdot \texttt{cameraMatrix}
|
||||
|
||||
where ``cameraMatrix`` can be chosen arbitrarily.
|
||||
|
||||
|
||||
|
||||
|
||||
getDefaultNewCameraMatrix
|
||||
-------------------------
|
||||
Returns the default new camera matrix.
|
||||
|
||||
.. ocv:function:: Mat getDefaultNewCameraMatrix(InputArray cameraMatrix, Size imgsize=Size(), bool centerPrincipalPoint=false )
|
||||
|
||||
.. ocv:pyfunction:: cv2.getDefaultNewCameraMatrix(cameraMatrix[, imgsize[, centerPrincipalPoint]]) -> retval
|
||||
|
||||
:param cameraMatrix: Input camera matrix.
|
||||
|
||||
:param imgsize: Camera view image size in pixels.
|
||||
|
||||
:param centerPrincipalPoint: Location of the principal point in the new camera matrix. The parameter indicates whether this location should be at the image center or not.
|
||||
|
||||
The function returns the camera matrix that is either an exact copy of the input ``cameraMatrix`` (when ``centerPrinicipalPoint=false`` ), or the modified one (when ``centerPrincipalPoint=true``).
|
||||
|
||||
In the latter case, the new camera matrix will be:
|
||||
|
||||
.. math::
|
||||
|
||||
\begin{bmatrix} f_x && 0 && ( \texttt{imgSize.width} -1)*0.5 \\ 0 && f_y && ( \texttt{imgSize.height} -1)*0.5 \\ 0 && 0 && 1 \end{bmatrix} ,
|
||||
|
||||
where
|
||||
:math:`f_x` and
|
||||
:math:`f_y` are
|
||||
:math:`(0,0)` and
|
||||
:math:`(1,1)` elements of ``cameraMatrix`` , respectively.
|
||||
|
||||
By default, the undistortion functions in OpenCV (see
|
||||
:ocv:func:`initUndistortRectifyMap`,
|
||||
:ocv:func:`undistort`) do not move the principal point. However, when you work with stereo, it is important to move the principal points in both views to the same y-coordinate (which is required by most of stereo correspondence algorithms), and may be to the same x-coordinate too. So, you can form the new camera matrix for each view where the principal points are located at the center.
|
||||
|
||||
|
||||
|
||||
|
||||
undistort
|
||||
-------------
|
||||
Transforms an image to compensate for lens distortion.
|
||||
|
||||
.. ocv:function:: void undistort( InputArray src, OutputArray dst, InputArray cameraMatrix, InputArray distCoeffs, InputArray newCameraMatrix=noArray() )
|
||||
|
||||
.. ocv:pyfunction:: cv2.undistort(src, cameraMatrix, distCoeffs[, dst[, newCameraMatrix]]) -> dst
|
||||
|
||||
.. ocv:cfunction:: void cvUndistort2( const CvArr* src, CvArr* dst, const CvMat* camera_matrix, const CvMat* distortion_coeffs, const CvMat* new_camera_matrix=0 )
|
||||
|
||||
:param src: Input (distorted) image.
|
||||
|
||||
:param dst: Output (corrected) image that has the same size and type as ``src`` .
|
||||
|
||||
:param cameraMatrix: Input camera matrix :math:`A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}` .
|
||||
|
||||
:param distCoeffs: Input vector of distortion coefficients :math:`(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6]])` of 4, 5, or 8 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed.
|
||||
|
||||
:param newCameraMatrix: Camera matrix of the distorted image. By default, it is the same as ``cameraMatrix`` but you may additionally scale and shift the result by using a different matrix.
|
||||
|
||||
The function transforms an image to compensate radial and tangential lens distortion.
|
||||
|
||||
The function is simply a combination of
|
||||
:ocv:func:`initUndistortRectifyMap` (with unity ``R`` ) and
|
||||
:ocv:func:`remap` (with bilinear interpolation). See the former function for details of the transformation being performed.
|
||||
|
||||
Those pixels in the destination image, for which there is no correspondent pixels in the source image, are filled with zeros (black color).
|
||||
|
||||
A particular subset of the source image that will be visible in the corrected image can be regulated by ``newCameraMatrix`` . You can use
|
||||
:ocv:func:`getOptimalNewCameraMatrix` to compute the appropriate ``newCameraMatrix`` depending on your requirements.
|
||||
|
||||
The camera matrix and the distortion parameters can be determined using
|
||||
:ocv:func:`calibrateCamera` . If the resolution of images is different from the resolution used at the calibration stage,
|
||||
:math:`f_x, f_y, c_x` and
|
||||
:math:`c_y` need to be scaled accordingly, while the distortion coefficients remain the same.
|
||||
|
||||
|
||||
|
||||
|
||||
undistortPoints
|
||||
-------------------
|
||||
Computes the ideal point coordinates from the observed point coordinates.
|
||||
|
||||
.. ocv:function:: void undistortPoints( InputArray src, OutputArray dst, InputArray cameraMatrix, InputArray distCoeffs, InputArray R=noArray(), InputArray P=noArray())
|
||||
|
||||
.. ocv:cfunction:: void cvUndistortPoints( const CvMat* src, CvMat* dst, const CvMat* camera_matrix, const CvMat* dist_coeffs, const CvMat* R=0, const CvMat* P=0 )
|
||||
|
||||
:param src: Observed point coordinates, 1xN or Nx1 2-channel (CV_32FC2 or CV_64FC2).
|
||||
|
||||
:param dst: Output ideal point coordinates after undistortion and reverse perspective transformation. If matrix ``P`` is identity or omitted, ``dst`` will contain normalized point coordinates.
|
||||
|
||||
:param cameraMatrix: Camera matrix :math:`\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}` .
|
||||
|
||||
:param distCoeffs: Input vector of distortion coefficients :math:`(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6]])` of 4, 5, or 8 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed.
|
||||
|
||||
:param R: Rectification transformation in the object space (3x3 matrix). ``R1`` or ``R2`` computed by :ocv:func:`stereoRectify` can be passed here. If the matrix is empty, the identity transformation is used.
|
||||
|
||||
:param P: New camera matrix (3x3) or new projection matrix (3x4). ``P1`` or ``P2`` computed by :ocv:func:`stereoRectify` can be passed here. If the matrix is empty, the identity new camera matrix is used.
|
||||
|
||||
The function is similar to
|
||||
:ocv:func:`undistort` and
|
||||
:ocv:func:`initUndistortRectifyMap` but it operates on a sparse set of points instead of a raster image. Also the function performs a reverse transformation to
|
||||
:ocv:func:`projectPoints` . In case of a 3D object, it does not reconstruct its 3D coordinates, but for a planar object, it does, up to a translation vector, if the proper ``R`` is specified. ::
|
||||
|
||||
// (u,v) is the input point, (u', v') is the output point
|
||||
// camera_matrix=[fx 0 cx; 0 fy cy; 0 0 1]
|
||||
// P=[fx' 0 cx' tx; 0 fy' cy' ty; 0 0 1 tz]
|
||||
x" = (u - cx)/fx
|
||||
y" = (v - cy)/fy
|
||||
(x',y') = undistort(x",y",dist_coeffs)
|
||||
[X,Y,W]T = R*[x' y' 1]T
|
||||
x = X/W, y = Y/W
|
||||
// only performed if P=[fx' 0 cx' [tx]; 0 fy' cy' [ty]; 0 0 1 [tz]] is specified
|
||||
u' = x*fx' + cx'
|
||||
v' = y*fy' + cy',
|
||||
|
||||
where ``undistort()`` is an approximate iterative algorithm that estimates the normalized original point coordinates out of the normalized distorted point coordinates ("normalized" means that the coordinates do not depend on the camera matrix).
|
||||
|
||||
The function can be used for both a stereo camera head or a monocular camera (when R is empty).
|
||||
@@ -1,514 +0,0 @@
|
||||
Histograms
|
||||
==========
|
||||
|
||||
.. highlight:: cpp
|
||||
|
||||
|
||||
|
||||
calcHist
|
||||
------------
|
||||
Calculates a histogram of a set of arrays.
|
||||
|
||||
.. ocv:function:: void calcHist( const Mat* images, int nimages, const int* channels, InputArray mask, OutputArray hist, int dims, const int* histSize, const float** ranges, bool uniform=true, bool accumulate=false )
|
||||
|
||||
.. ocv:function:: void calcHist( const Mat* images, int nimages, const int* channels, InputArray mask, SparseMat& hist, int dims, const int* histSize, const float** ranges, bool uniform=true, bool accumulate=false )
|
||||
|
||||
.. ocv:pyfunction:: cv2.calcHist(images, channels, mask, histSize, ranges[, hist[, accumulate]]) -> hist
|
||||
|
||||
.. ocv:cfunction:: void cvCalcHist( IplImage** image, CvHistogram* hist, int accumulate=0, const CvArr* mask=NULL )
|
||||
|
||||
:param images: Source arrays. They all should have the same depth, ``CV_8U`` or ``CV_32F`` , and the same size. Each of them can have an arbitrary number of channels.
|
||||
|
||||
:param nimages: Number of source images.
|
||||
|
||||
:param channels: List of the ``dims`` channels used to compute the histogram. The first array channels are numerated from 0 to ``images[0].channels()-1`` , the second array channels are counted from ``images[0].channels()`` to ``images[0].channels() + images[1].channels()-1``, and so on.
|
||||
|
||||
:param mask: Optional mask. If the matrix is not empty, it must be an 8-bit array of the same size as ``images[i]`` . The non-zero mask elements mark the array elements counted in the histogram.
|
||||
|
||||
:param hist: Output histogram, which is a dense or sparse ``dims`` -dimensional array.
|
||||
|
||||
:param dims: Histogram dimensionality that must be positive and not greater than ``CV_MAX_DIMS`` (equal to 32 in the current OpenCV version).
|
||||
|
||||
:param histSize: Array of histogram sizes in each dimension.
|
||||
|
||||
:param ranges: Array of the ``dims`` arrays of the histogram bin boundaries in each dimension. When the histogram is uniform ( ``uniform`` =true), then for each dimension ``i`` it is enough to specify the lower (inclusive) boundary :math:`L_0` of the 0-th histogram bin and the upper (exclusive) boundary :math:`U_{\texttt{histSize}[i]-1}` for the last histogram bin ``histSize[i]-1`` . That is, in case of a uniform histogram each of ``ranges[i]`` is an array of 2 elements. When the histogram is not uniform ( ``uniform=false`` ), then each of ``ranges[i]`` contains ``histSize[i]+1`` elements: :math:`L_0, U_0=L_1, U_1=L_2, ..., U_{\texttt{histSize[i]}-2}=L_{\texttt{histSize[i]}-1}, U_{\texttt{histSize[i]}-1}` . The array elements, that are not between :math:`L_0` and :math:`U_{\texttt{histSize[i]}-1}` , are not counted in the histogram.
|
||||
|
||||
:param uniform: Flag indicating whether the histogram is uniform or not (see above).
|
||||
|
||||
:param accumulate: Accumulation flag. If it is set, the histogram is not cleared in the beginning when it is allocated. This feature enables you to compute a single histogram from several sets of arrays, or to update the histogram in time.
|
||||
|
||||
The functions ``calcHist`` calculate the histogram of one or more
|
||||
arrays. The elements of a tuple used to increment
|
||||
a histogram bin are taken from the corresponding
|
||||
input arrays at the same location. The sample below shows how to compute a 2D Hue-Saturation histogram for a color image. ::
|
||||
|
||||
#include <opencv2/imgproc.hpp>
|
||||
#include <opencv2/highgui.hpp>
|
||||
|
||||
using namespace cv;
|
||||
|
||||
int main( int argc, char** argv )
|
||||
{
|
||||
Mat src, hsv;
|
||||
if( argc != 2 || !(src=imread(argv[1], 1)).data )
|
||||
return -1;
|
||||
|
||||
cvtColor(src, hsv, COLOR_BGR2HSV);
|
||||
|
||||
// Quantize the hue to 30 levels
|
||||
// and the saturation to 32 levels
|
||||
int hbins = 30, sbins = 32;
|
||||
int histSize[] = {hbins, sbins};
|
||||
// hue varies from 0 to 179, see cvtColor
|
||||
float hranges[] = { 0, 180 };
|
||||
// saturation varies from 0 (black-gray-white) to
|
||||
// 255 (pure spectrum color)
|
||||
float sranges[] = { 0, 256 };
|
||||
const float* ranges[] = { hranges, sranges };
|
||||
MatND hist;
|
||||
// we compute the histogram from the 0-th and 1-st channels
|
||||
int channels[] = {0, 1};
|
||||
|
||||
calcHist( &hsv, 1, channels, Mat(), // do not use mask
|
||||
hist, 2, histSize, ranges,
|
||||
true, // the histogram is uniform
|
||||
false );
|
||||
double maxVal=0;
|
||||
minMaxLoc(hist, 0, &maxVal, 0, 0);
|
||||
|
||||
int scale = 10;
|
||||
Mat histImg = Mat::zeros(sbins*scale, hbins*10, CV_8UC3);
|
||||
|
||||
for( int h = 0; h < hbins; h++ )
|
||||
for( int s = 0; s < sbins; s++ )
|
||||
{
|
||||
float binVal = hist.at<float>(h, s);
|
||||
int intensity = cvRound(binVal*255/maxVal);
|
||||
rectangle( histImg, Point(h*scale, s*scale),
|
||||
Point( (h+1)*scale - 1, (s+1)*scale - 1),
|
||||
Scalar::all(intensity),
|
||||
CV_FILLED );
|
||||
}
|
||||
|
||||
namedWindow( "Source", 1 );
|
||||
imshow( "Source", src );
|
||||
|
||||
namedWindow( "H-S Histogram", 1 );
|
||||
imshow( "H-S Histogram", histImg );
|
||||
waitKey();
|
||||
}
|
||||
|
||||
.. note::
|
||||
|
||||
* An example for creating histograms of an image can be found at opencv_source_code/samples/cpp/demhist.cpp
|
||||
|
||||
* (Python) An example for creating color histograms can be found at opencv_source/samples/python2/color_histogram.py
|
||||
* (Python) An example illustrating RGB and grayscale histogram plotting can be found at opencv_source/samples/python2/hist.py
|
||||
|
||||
|
||||
calcBackProject
|
||||
-------------------
|
||||
Calculates the back projection of a histogram.
|
||||
|
||||
.. ocv:function:: void calcBackProject( const Mat* images, int nimages, const int* channels, InputArray hist, OutputArray backProject, const float** ranges, double scale=1, bool uniform=true )
|
||||
|
||||
.. ocv:function:: void calcBackProject( const Mat* images, int nimages, const int* channels, const SparseMat& hist, OutputArray backProject, const float** ranges, double scale=1, bool uniform=true )
|
||||
|
||||
.. ocv:pyfunction:: cv2.calcBackProject(images, channels, hist, ranges, scale[, dst]) -> dst
|
||||
|
||||
.. ocv:cfunction:: void cvCalcBackProject( IplImage** image, CvArr* backProject, const CvHistogram* hist )
|
||||
|
||||
:param images: Source arrays. They all should have the same depth, ``CV_8U`` or ``CV_32F`` , and the same size. Each of them can have an arbitrary number of channels.
|
||||
|
||||
:param nimages: Number of source images.
|
||||
|
||||
:param channels: The list of channels used to compute the back projection. The number of channels must match the histogram dimensionality. The first array channels are numerated from 0 to ``images[0].channels()-1`` , the second array channels are counted from ``images[0].channels()`` to ``images[0].channels() + images[1].channels()-1``, and so on.
|
||||
|
||||
:param hist: Input histogram that can be dense or sparse.
|
||||
|
||||
:param backProject: Destination back projection array that is a single-channel array of the same size and depth as ``images[0]`` .
|
||||
|
||||
:param ranges: Array of arrays of the histogram bin boundaries in each dimension. See :ocv:func:`calcHist` .
|
||||
|
||||
:param scale: Optional scale factor for the output back projection.
|
||||
|
||||
:param uniform: Flag indicating whether the histogram is uniform or not (see above).
|
||||
|
||||
The functions ``calcBackProject`` calculate the back project of the histogram. That is, similarly to ``calcHist`` , at each location ``(x, y)`` the function collects the values from the selected channels in the input images and finds the corresponding histogram bin. But instead of incrementing it, the function reads the bin value, scales it by ``scale`` , and stores in ``backProject(x,y)`` . In terms of statistics, the function computes probability of each element value in respect with the empirical probability distribution represented by the histogram. See how, for example, you can find and track a bright-colored object in a scene:
|
||||
|
||||
#.
|
||||
Before tracking, show the object to the camera so that it covers almost the whole frame. Calculate a hue histogram. The histogram may have strong maximums, corresponding to the dominant colors in the object.
|
||||
|
||||
#.
|
||||
When tracking, calculate a back projection of a hue plane of each input video frame using that pre-computed histogram. Threshold the back projection to suppress weak colors. It may also make sense to suppress pixels with non-sufficient color saturation and too dark or too bright pixels.
|
||||
|
||||
#.
|
||||
Find connected components in the resulting picture and choose, for example, the largest component.
|
||||
|
||||
This is an approximate algorithm of the
|
||||
:ocv:func:`CamShift` color object tracker.
|
||||
|
||||
.. seealso:: :ocv:func:`calcHist`
|
||||
.. _compareHist:
|
||||
|
||||
compareHist
|
||||
-----------
|
||||
Compares two histograms.
|
||||
|
||||
.. ocv:function:: double compareHist( InputArray H1, InputArray H2, int method )
|
||||
|
||||
.. ocv:function:: double compareHist( const SparseMat& H1, const SparseMat& H2, int method )
|
||||
|
||||
.. ocv:pyfunction:: cv2.compareHist(H1, H2, method) -> retval
|
||||
|
||||
.. ocv:cfunction:: double cvCompareHist( const CvHistogram* hist1, const CvHistogram* hist2, int method )
|
||||
|
||||
:param H1: First compared histogram.
|
||||
|
||||
:param H2: Second compared histogram of the same size as ``H1`` .
|
||||
|
||||
:param method: Comparison method that could be one of the following:
|
||||
|
||||
* **CV_COMP_CORREL** Correlation
|
||||
|
||||
* **CV_COMP_CHISQR** Chi-Square
|
||||
|
||||
* **CV_COMP_CHISQR_ALT** Alternative Chi-Square
|
||||
|
||||
* **CV_COMP_INTERSECT** Intersection
|
||||
|
||||
* **CV_COMP_BHATTACHARYYA** Bhattacharyya distance
|
||||
|
||||
* **CV_COMP_HELLINGER** Synonym for ``CV_COMP_BHATTACHARYYA``
|
||||
|
||||
* **CV_COMP_KL_DIV** Kullback-Leibler divergence
|
||||
|
||||
The functions ``compareHist`` compare two dense or two sparse histograms using the specified method:
|
||||
|
||||
* Correlation (``method=CV_COMP_CORREL``)
|
||||
|
||||
.. math::
|
||||
|
||||
d(H_1,H_2) = \frac{\sum_I (H_1(I) - \bar{H_1}) (H_2(I) - \bar{H_2})}{\sqrt{\sum_I(H_1(I) - \bar{H_1})^2 \sum_I(H_2(I) - \bar{H_2})^2}}
|
||||
|
||||
where
|
||||
|
||||
.. math::
|
||||
|
||||
\bar{H_k} = \frac{1}{N} \sum _J H_k(J)
|
||||
|
||||
and
|
||||
:math:`N` is a total number of histogram bins.
|
||||
|
||||
* Chi-Square (``method=CV_COMP_CHISQR``)
|
||||
|
||||
.. math::
|
||||
|
||||
d(H_1,H_2) = \sum _I \frac{\left(H_1(I)-H_2(I)\right)^2}{H_1(I)}
|
||||
|
||||
* Alternative Chi-Square (``method=CV_COMP_CHISQR_ALT``)
|
||||
|
||||
.. math::
|
||||
|
||||
d(H_1,H_2) = 2 * \sum _I \frac{\left(H_1(I)-H_2(I)\right)^2}{H_1(I)+H_2(I)}
|
||||
|
||||
This alternative formula is regularly used for texture comparison. See e.g. [Puzicha1997]_.
|
||||
|
||||
* Intersection (``method=CV_COMP_INTERSECT``)
|
||||
|
||||
.. math::
|
||||
|
||||
d(H_1,H_2) = \sum _I \min (H_1(I), H_2(I))
|
||||
|
||||
* Bhattacharyya distance (``method=CV_COMP_BHATTACHARYYA`` or ``method=CV_COMP_HELLINGER``). In fact, OpenCV computes Hellinger distance, which is related to Bhattacharyya coefficient.
|
||||
|
||||
.. math::
|
||||
|
||||
d(H_1,H_2) = \sqrt{1 - \frac{1}{\sqrt{\bar{H_1} \bar{H_2} N^2}} \sum_I \sqrt{H_1(I) \cdot H_2(I)}}
|
||||
|
||||
* Kullback-Leibler divergence (``method=CV_COMP_KL_DIV``).
|
||||
|
||||
.. math::
|
||||
|
||||
d(H_1,H_2) = \sum _I H_1(I) \log \left(\frac{H_1(I)}{H_2(I)}\right)
|
||||
|
||||
The function returns
|
||||
:math:`d(H_1, H_2)` .
|
||||
|
||||
While the function works well with 1-, 2-, 3-dimensional dense histograms, it may not be suitable for high-dimensional sparse histograms. In such histograms, because of aliasing and sampling problems, the coordinates of non-zero histogram bins can slightly shift. To compare such histograms or more general sparse configurations of weighted points, consider using the
|
||||
:ocv:func:`EMD` function.
|
||||
|
||||
|
||||
|
||||
|
||||
EMD
|
||||
------
|
||||
Computes the "minimal work" distance between two weighted point configurations.
|
||||
|
||||
.. ocv:function:: float EMD( InputArray signature1, InputArray signature2, int distType, InputArray cost=noArray(), float* lowerBound=0, OutputArray flow=noArray() )
|
||||
|
||||
.. ocv:cfunction:: float cvCalcEMD2( const CvArr* signature1, const CvArr* signature2, int distance_type, CvDistanceFunction distance_func=NULL, const CvArr* cost_matrix=NULL, CvArr* flow=NULL, float* lower_bound=NULL, void* userdata=NULL )
|
||||
|
||||
:param signature1: First signature, a :math:`\texttt{size1}\times \texttt{dims}+1` floating-point matrix. Each row stores the point weight followed by the point coordinates. The matrix is allowed to have a single column (weights only) if the user-defined cost matrix is used.
|
||||
|
||||
:param signature2: Second signature of the same format as ``signature1`` , though the number of rows may be different. The total weights may be different. In this case an extra "dummy" point is added to either ``signature1`` or ``signature2`` .
|
||||
|
||||
:param distType: Used metric. ``CV_DIST_L1, CV_DIST_L2`` , and ``CV_DIST_C`` stand for one of the standard metrics. ``CV_DIST_USER`` means that a pre-calculated cost matrix ``cost`` is used.
|
||||
|
||||
:param distance_func: Custom distance function supported by the old interface. ``CvDistanceFunction`` is defined as: ::
|
||||
|
||||
typedef float (CV_CDECL * CvDistanceFunction)( const float* a,
|
||||
const float* b, void* userdata );
|
||||
|
||||
where ``a`` and ``b`` are point coordinates and ``userdata`` is the same as the last parameter.
|
||||
|
||||
:param cost: User-defined :math:`\texttt{size1}\times \texttt{size2}` cost matrix. Also, if a cost matrix is used, lower boundary ``lowerBound`` cannot be calculated because it needs a metric function.
|
||||
|
||||
:param lowerBound: Optional input/output parameter: lower boundary of a distance between the two signatures that is a distance between mass centers. The lower boundary may not be calculated if the user-defined cost matrix is used, the total weights of point configurations are not equal, or if the signatures consist of weights only (the signature matrices have a single column). You **must** initialize ``*lowerBound`` . If the calculated distance between mass centers is greater or equal to ``*lowerBound`` (it means that the signatures are far enough), the function does not calculate EMD. In any case ``*lowerBound`` is set to the calculated distance between mass centers on return. Thus, if you want to calculate both distance between mass centers and EMD, ``*lowerBound`` should be set to 0.
|
||||
|
||||
:param flow: Resultant :math:`\texttt{size1} \times \texttt{size2}` flow matrix: :math:`\texttt{flow}_{i,j}` is a flow from :math:`i` -th point of ``signature1`` to :math:`j` -th point of ``signature2`` .
|
||||
|
||||
:param userdata: Optional pointer directly passed to the custom distance function.
|
||||
|
||||
The function computes the earth mover distance and/or a lower boundary of the distance between the two weighted point configurations. One of the applications described in [RubnerSept98]_ is multi-dimensional histogram comparison for image retrieval. EMD is a transportation problem that is solved using some modification of a simplex algorithm, thus the complexity is exponential in the worst case, though, on average it is much faster. In the case of a real metric the lower boundary can be calculated even faster (using linear-time algorithm) and it can be used to determine roughly whether the two signatures are far enough so that they cannot relate to the same object.
|
||||
|
||||
|
||||
equalizeHist
|
||||
----------------
|
||||
Equalizes the histogram of a grayscale image.
|
||||
|
||||
.. ocv:function:: void equalizeHist( InputArray src, OutputArray dst )
|
||||
|
||||
.. ocv:pyfunction:: cv2.equalizeHist(src[, dst]) -> dst
|
||||
|
||||
.. ocv:cfunction:: void cvEqualizeHist( const CvArr* src, CvArr* dst )
|
||||
|
||||
:param src: Source 8-bit single channel image.
|
||||
|
||||
:param dst: Destination image of the same size and type as ``src`` .
|
||||
|
||||
The function equalizes the histogram of the input image using the following algorithm:
|
||||
|
||||
#.
|
||||
Calculate the histogram
|
||||
:math:`H` for ``src`` .
|
||||
|
||||
#.
|
||||
Normalize the histogram so that the sum of histogram bins is 255.
|
||||
|
||||
#.
|
||||
Compute the integral of the histogram:
|
||||
|
||||
.. math::
|
||||
|
||||
H'_i = \sum _{0 \le j < i} H(j)
|
||||
|
||||
#.
|
||||
Transform the image using
|
||||
:math:`H'` as a look-up table:
|
||||
:math:`\texttt{dst}(x,y) = H'(\texttt{src}(x,y))`
|
||||
|
||||
The algorithm normalizes the brightness and increases the contrast of the image.
|
||||
|
||||
|
||||
Extra Histogram Functions (C API)
|
||||
---------------------------------
|
||||
|
||||
The rest of the section describes additional C functions operating on ``CvHistogram``.
|
||||
|
||||
CalcBackProjectPatch
|
||||
--------------------
|
||||
Locates a template within an image by using a histogram comparison.
|
||||
|
||||
.. ocv:cfunction:: void cvCalcBackProjectPatch( IplImage** images, CvArr* dst, CvSize patch_size, CvHistogram* hist, int method, double factor )
|
||||
|
||||
:param images: Source images (though, you may pass CvMat** as well).
|
||||
|
||||
:param dst: Destination image.
|
||||
|
||||
:param patch_size: Size of the patch slid though the source image.
|
||||
|
||||
:param hist: Histogram.
|
||||
|
||||
:param method: Comparison method passed to :ocv:cfunc:`CompareHist` (see the function description).
|
||||
|
||||
:param factor: Normalization factor for histograms that affects the normalization scale of the destination image. Pass 1 if not sure.
|
||||
|
||||
The function calculates the back projection by comparing histograms of the source image patches with the given histogram. The function is similar to :ocv:func:`matchTemplate`, but instead of comparing the raster patch with all its possible positions within the search window, the function ``CalcBackProjectPatch`` compares histograms. See the algorithm diagram below:
|
||||
|
||||
.. image:: pics/backprojectpatch.png
|
||||
|
||||
|
||||
CalcProbDensity
|
||||
---------------
|
||||
Divides one histogram by another.
|
||||
|
||||
.. ocv:cfunction:: void cvCalcProbDensity( const CvHistogram* hist1, const CvHistogram* hist2, CvHistogram* dst_hist, double scale=255 )
|
||||
|
||||
:param hist1: First histogram (the divisor).
|
||||
|
||||
:param hist2: Second histogram.
|
||||
|
||||
:param dst_hist: Destination histogram.
|
||||
|
||||
:param scale: Scale factor for the destination histogram.
|
||||
|
||||
The function calculates the object probability density from two histograms as:
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{disthist} (I)= \forkthree{0}{if $\texttt{hist1}(I)=0$}{\texttt{scale}}{if $\texttt{hist1}(I) \ne 0$ and $\texttt{hist2}(I) > \texttt{hist1}(I)$}{\frac{\texttt{hist2}(I) \cdot \texttt{scale}}{\texttt{hist1}(I)}}{if $\texttt{hist1}(I) \ne 0$ and $\texttt{hist2}(I) \le \texttt{hist1}(I)$}
|
||||
|
||||
|
||||
ClearHist
|
||||
---------
|
||||
Clears the histogram.
|
||||
|
||||
.. ocv:cfunction:: void cvClearHist( CvHistogram* hist )
|
||||
|
||||
:param hist: Histogram.
|
||||
|
||||
The function sets all of the histogram bins to 0 in case of a dense histogram and removes all histogram bins in case of a sparse array.
|
||||
|
||||
|
||||
CopyHist
|
||||
--------
|
||||
Copies a histogram.
|
||||
|
||||
.. ocv:cfunction:: void cvCopyHist( const CvHistogram* src, CvHistogram** dst )
|
||||
|
||||
:param src: Source histogram.
|
||||
|
||||
:param dst: Pointer to the destination histogram.
|
||||
|
||||
The function makes a copy of the histogram. If the second histogram pointer ``*dst`` is NULL, a new histogram of the same size as ``src`` is created. Otherwise, both histograms must have equal types and sizes. Then the function copies the bin values of the source histogram to the destination histogram and sets the same bin value ranges as in ``src``.
|
||||
|
||||
.. _createhist:
|
||||
|
||||
CreateHist
|
||||
----------
|
||||
Creates a histogram.
|
||||
|
||||
.. ocv:cfunction:: CvHistogram* cvCreateHist( int dims, int* sizes, int type, float** ranges=NULL, int uniform=1 )
|
||||
|
||||
:param dims: Number of histogram dimensions.
|
||||
|
||||
:param sizes: Array of the histogram dimension sizes.
|
||||
|
||||
:param type: Histogram representation format. ``CV_HIST_ARRAY`` means that the histogram data is represented as a multi-dimensional dense array CvMatND. ``CV_HIST_SPARSE`` means that histogram data is represented as a multi-dimensional sparse array ``CvSparseMat``.
|
||||
|
||||
:param ranges: Array of ranges for the histogram bins. Its meaning depends on the ``uniform`` parameter value. The ranges are used when the histogram is calculated or backprojected to determine which histogram bin corresponds to which value/tuple of values from the input image(s).
|
||||
|
||||
:param uniform: Uniformity flag. If not zero, the histogram has evenly
|
||||
spaced bins and for every :math:`0<=i<cDims` ``ranges[i]``
|
||||
is an array of two numbers: lower and upper boundaries for the i-th
|
||||
histogram dimension.
|
||||
The whole range [lower,upper] is then split
|
||||
into ``dims[i]`` equal parts to determine the ``i``-th input
|
||||
tuple value ranges for every histogram bin. And if ``uniform=0`` ,
|
||||
then the ``i``-th element of the ``ranges`` array contains ``dims[i]+1`` elements: :math:`\texttt{lower}_0, \texttt{upper}_0,
|
||||
\texttt{lower}_1, \texttt{upper}_1 = \texttt{lower}_2,
|
||||
...
|
||||
\texttt{upper}_{dims[i]-1}`
|
||||
where :math:`\texttt{lower}_j` and :math:`\texttt{upper}_j`
|
||||
are lower and upper
|
||||
boundaries of the ``i``-th input tuple value for the ``j``-th
|
||||
bin, respectively. In either case, the input values that are beyond
|
||||
the specified range for a histogram bin are not counted by :ocv:cfunc:`CalcHist` and filled with 0 by :ocv:cfunc:`CalcBackProject`.
|
||||
|
||||
The function creates a histogram of the specified size and returns a pointer to the created histogram. If the array ``ranges`` is 0, the histogram bin ranges must be specified later via the function :ocv:cfunc:`SetHistBinRanges`. Though :ocv:cfunc:`CalcHist` and :ocv:cfunc:`CalcBackProject` may process 8-bit images without setting bin ranges, they assume they are equally spaced in 0 to 255 bins.
|
||||
|
||||
|
||||
GetMinMaxHistValue
|
||||
------------------
|
||||
Finds the minimum and maximum histogram bins.
|
||||
|
||||
.. ocv:cfunction:: void cvGetMinMaxHistValue( const CvHistogram* hist, float* min_value, float* max_value, int* min_idx=NULL, int* max_idx=NULL )
|
||||
|
||||
:param hist: Histogram.
|
||||
|
||||
:param min_value: Pointer to the minimum value of the histogram.
|
||||
|
||||
:param max_value: Pointer to the maximum value of the histogram.
|
||||
|
||||
:param min_idx: Pointer to the array of coordinates for the minimum.
|
||||
|
||||
:param max_idx: Pointer to the array of coordinates for the maximum.
|
||||
|
||||
The function finds the minimum and maximum histogram bins and their positions. All of output arguments are optional. Among several extremas with the same value the ones with the minimum index (in the lexicographical order) are returned. In case of several maximums or minimums, the earliest in the lexicographical order (extrema locations) is returned.
|
||||
|
||||
|
||||
MakeHistHeaderForArray
|
||||
----------------------
|
||||
Makes a histogram out of an array.
|
||||
|
||||
.. ocv:cfunction:: CvHistogram* cvMakeHistHeaderForArray( int dims, int* sizes, CvHistogram* hist, float* data, float** ranges=NULL, int uniform=1 )
|
||||
|
||||
:param dims: Number of the histogram dimensions.
|
||||
|
||||
:param sizes: Array of the histogram dimension sizes.
|
||||
|
||||
:param hist: Histogram header initialized by the function.
|
||||
|
||||
:param data: Array used to store histogram bins.
|
||||
|
||||
:param ranges: Histogram bin ranges. See :ocv:cfunc:`CreateHist` for details.
|
||||
|
||||
:param uniform: Uniformity flag. See :ocv:cfunc:`CreateHist` for details.
|
||||
|
||||
The function initializes the histogram, whose header and bins are allocated by the user. :ocv:cfunc:`ReleaseHist` does not need to be called afterwards. Only dense histograms can be initialized this way. The function returns ``hist``.
|
||||
|
||||
NormalizeHist
|
||||
-------------
|
||||
Normalizes the histogram.
|
||||
|
||||
.. ocv:cfunction:: void cvNormalizeHist( CvHistogram* hist, double factor )
|
||||
|
||||
:param hist: Pointer to the histogram.
|
||||
|
||||
:param factor: Normalization factor.
|
||||
|
||||
The function normalizes the histogram bins by scaling them so that the sum of the bins becomes equal to ``factor``.
|
||||
|
||||
|
||||
ReleaseHist
|
||||
-----------
|
||||
Releases the histogram.
|
||||
|
||||
.. ocv:cfunction:: void cvReleaseHist( CvHistogram** hist )
|
||||
|
||||
:param hist: Double pointer to the released histogram.
|
||||
|
||||
The function releases the histogram (header and the data). The pointer to the histogram is cleared by the function. If ``*hist`` pointer is already ``NULL``, the function does nothing.
|
||||
|
||||
|
||||
SetHistBinRanges
|
||||
----------------
|
||||
Sets the bounds of the histogram bins.
|
||||
|
||||
.. ocv:cfunction:: void cvSetHistBinRanges( CvHistogram* hist, float** ranges, int uniform=1 )
|
||||
|
||||
:param hist: Histogram.
|
||||
|
||||
:param ranges: Array of bin ranges arrays. See :ocv:cfunc:`CreateHist` for details.
|
||||
|
||||
:param uniform: Uniformity flag. See :ocv:cfunc:`CreateHist` for details.
|
||||
|
||||
This is a standalone function for setting bin ranges in the histogram. For a more detailed description of the parameters ``ranges`` and ``uniform``, see the :ocv:cfunc:`CalcHist` function that can initialize the ranges as well. Ranges for the histogram bins must be set before the histogram is calculated or the backproject of the histogram is calculated.
|
||||
|
||||
|
||||
ThreshHist
|
||||
----------
|
||||
Thresholds the histogram.
|
||||
|
||||
.. ocv:cfunction:: void cvThreshHist( CvHistogram* hist, double threshold )
|
||||
|
||||
:param hist: Pointer to the histogram.
|
||||
|
||||
:param threshold: Threshold level.
|
||||
|
||||
The function clears histogram bins that are below the specified threshold.
|
||||
|
||||
|
||||
.. [RubnerSept98] Y. Rubner. C. Tomasi, L.J. Guibas. *The Earth Mover’s Distance as a Metric for Image Retrieval*. Technical Report STAN-CS-TN-98-86, Department of Computer Science, Stanford University, September 1998.
|
||||
.. [Puzicha1997] Puzicha, J., Hofmann, T., and Buhmann, J. *Non-parametric similarity measures for unsupervised texture segmentation and image retrieval.* In Proc. IEEE Conf. Computer Vision and Pattern Recognition, San Juan, Puerto Rico, pp. 267-272, 1997.
|
||||
@@ -1,19 +0,0 @@
|
||||
*************************
|
||||
imgproc. Image Processing
|
||||
*************************
|
||||
|
||||
.. highlight:: cpp
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 2
|
||||
|
||||
filtering
|
||||
geometric_transformations
|
||||
miscellaneous_transformations
|
||||
drawing_functions
|
||||
colormaps
|
||||
histograms
|
||||
structural_analysis_and_shape_descriptors
|
||||
motion_analysis_and_object_tracking
|
||||
feature_detection
|
||||
object_detection
|
||||
@@ -1,813 +0,0 @@
|
||||
Miscellaneous Image Transformations
|
||||
===================================
|
||||
|
||||
.. highlight:: cpp
|
||||
|
||||
|
||||
adaptiveThreshold
|
||||
---------------------
|
||||
Applies an adaptive threshold to an array.
|
||||
|
||||
.. ocv:function:: void adaptiveThreshold( InputArray src, OutputArray dst, double maxValue, int adaptiveMethod, int thresholdType, int blockSize, double C )
|
||||
|
||||
.. ocv:pyfunction:: cv2.adaptiveThreshold(src, maxValue, adaptiveMethod, thresholdType, blockSize, C[, dst]) -> dst
|
||||
|
||||
.. ocv:cfunction:: void cvAdaptiveThreshold( const CvArr* src, CvArr* dst, double max_value, int adaptive_method=CV_ADAPTIVE_THRESH_MEAN_C, int threshold_type=CV_THRESH_BINARY, int block_size=3, double param1=5 )
|
||||
|
||||
:param src: Source 8-bit single-channel image.
|
||||
|
||||
:param dst: Destination image of the same size and the same type as ``src`` .
|
||||
|
||||
:param maxValue: Non-zero value assigned to the pixels for which the condition is satisfied. See the details below.
|
||||
|
||||
:param adaptiveMethod: Adaptive thresholding algorithm to use, ``ADAPTIVE_THRESH_MEAN_C`` or ``ADAPTIVE_THRESH_GAUSSIAN_C`` . See the details below.
|
||||
|
||||
:param thresholdType: Thresholding type that must be either ``THRESH_BINARY`` or ``THRESH_BINARY_INV`` .
|
||||
|
||||
:param blockSize: Size of a pixel neighborhood that is used to calculate a threshold value for the pixel: 3, 5, 7, and so on.
|
||||
|
||||
:param C: Constant subtracted from the mean or weighted mean (see the details below). Normally, it is positive but may be zero or negative as well.
|
||||
|
||||
The function transforms a grayscale image to a binary image according to the formulae:
|
||||
|
||||
* **THRESH_BINARY**
|
||||
|
||||
.. math::
|
||||
|
||||
dst(x,y) = \fork{\texttt{maxValue}}{if $src(x,y) > T(x,y)$}{0}{otherwise}
|
||||
|
||||
* **THRESH_BINARY_INV**
|
||||
|
||||
.. math::
|
||||
|
||||
dst(x,y) = \fork{0}{if $src(x,y) > T(x,y)$}{\texttt{maxValue}}{otherwise}
|
||||
|
||||
where
|
||||
:math:`T(x,y)` is a threshold calculated individually for each pixel.
|
||||
|
||||
*
|
||||
For the method ``ADAPTIVE_THRESH_MEAN_C`` , the threshold value
|
||||
:math:`T(x,y)` is a mean of the
|
||||
:math:`\texttt{blockSize} \times \texttt{blockSize}` neighborhood of
|
||||
:math:`(x, y)` minus ``C`` .
|
||||
|
||||
*
|
||||
For the method ``ADAPTIVE_THRESH_GAUSSIAN_C`` , the threshold value
|
||||
:math:`T(x, y)` is a weighted sum (cross-correlation with a Gaussian window) of the
|
||||
:math:`\texttt{blockSize} \times \texttt{blockSize}` neighborhood of
|
||||
:math:`(x, y)` minus ``C`` . The default sigma (standard deviation) is used for the specified ``blockSize`` . See
|
||||
:ocv:func:`getGaussianKernel` .
|
||||
|
||||
The function can process the image in-place.
|
||||
|
||||
.. seealso::
|
||||
|
||||
:ocv:func:`threshold`,
|
||||
:ocv:func:`blur`,
|
||||
:ocv:func:`GaussianBlur`
|
||||
|
||||
|
||||
|
||||
cvtColor
|
||||
--------
|
||||
Converts an image from one color space to another.
|
||||
|
||||
.. ocv:function:: void cvtColor( InputArray src, OutputArray dst, int code, int dstCn=0 )
|
||||
|
||||
.. ocv:pyfunction:: cv2.cvtColor(src, code[, dst[, dstCn]]) -> dst
|
||||
|
||||
.. ocv:cfunction:: void cvCvtColor( const CvArr* src, CvArr* dst, int code )
|
||||
|
||||
:param src: input image: 8-bit unsigned, 16-bit unsigned ( ``CV_16UC...`` ), or single-precision floating-point.
|
||||
|
||||
:param dst: output image of the same size and depth as ``src``.
|
||||
|
||||
:param code: color space conversion code (see the description below).
|
||||
|
||||
:param dstCn: number of channels in the destination image; if the parameter is 0, the number of the channels is derived automatically from ``src`` and ``code`` .
|
||||
|
||||
The function converts an input image from one color
|
||||
space to another. In case of a transformation to-from RGB color space, the order of the channels should be specified explicitly (RGB or BGR).
|
||||
Note that the default color format in OpenCV is often referred to as RGB but it is actually BGR (the bytes are reversed). So the first byte in a standard (24-bit) color image will be an 8-bit Blue component, the second byte will be Green, and the third byte will be Red. The fourth, fifth, and sixth bytes would then be the second pixel (Blue, then Green, then Red), and so on.
|
||||
|
||||
The conventional ranges for R, G, and B channel values are:
|
||||
|
||||
*
|
||||
0 to 255 for ``CV_8U`` images
|
||||
|
||||
*
|
||||
0 to 65535 for ``CV_16U`` images
|
||||
|
||||
*
|
||||
0 to 1 for ``CV_32F`` images
|
||||
|
||||
In case of linear transformations, the range does not matter.
|
||||
But in case of a non-linear transformation, an input RGB image should be normalized to the proper value range to get the correct results, for example, for RGB
|
||||
:math:`\rightarrow` L*u*v* transformation. For example, if you have a 32-bit floating-point image directly converted from an 8-bit image without any scaling, then it will have the 0..255 value range instead of 0..1 assumed by the function. So, before calling ``cvtColor`` , you need first to scale the image down: ::
|
||||
|
||||
img *= 1./255;
|
||||
cvtColor(img, img, COLOR_BGR2Luv);
|
||||
|
||||
If you use ``cvtColor`` with 8-bit images, the conversion will have some information lost. For many applications, this will not be noticeable but it is recommended to use 32-bit images in applications that need the full range of colors or that convert an image before an operation and then convert back.
|
||||
|
||||
If conversion adds the alpha channel, its value will set to the maximum of corresponding channel range: 255 for ``CV_8U``, 65535 for ``CV_16U``, 1 for ``CV_32F``.
|
||||
|
||||
The function can do the following transformations:
|
||||
|
||||
*
|
||||
RGB :math:`\leftrightarrow` GRAY ( ``COLOR_BGR2GRAY, COLOR_RGB2GRAY, COLOR_GRAY2BGR, COLOR_GRAY2RGB`` )
|
||||
Transformations within RGB space like adding/removing the alpha channel, reversing the channel order, conversion to/from 16-bit RGB color (R5:G6:B5 or R5:G5:B5), as well as conversion to/from grayscale using:
|
||||
|
||||
.. math::
|
||||
|
||||
\text{RGB[A] to Gray:} \quad Y \leftarrow 0.299 \cdot R + 0.587 \cdot G + 0.114 \cdot B
|
||||
|
||||
and
|
||||
|
||||
.. math::
|
||||
|
||||
\text{Gray to RGB[A]:} \quad R \leftarrow Y, G \leftarrow Y, B \leftarrow Y, A \leftarrow \max (ChannelRange)
|
||||
|
||||
The conversion from a RGB image to gray is done with:
|
||||
|
||||
::
|
||||
|
||||
cvtColor(src, bwsrc, COLOR_RGB2GRAY);
|
||||
|
||||
..
|
||||
|
||||
More advanced channel reordering can also be done with
|
||||
:ocv:func:`mixChannels` .
|
||||
|
||||
*
|
||||
RGB
|
||||
:math:`\leftrightarrow` CIE XYZ.Rec 709 with D65 white point ( ``COLOR_BGR2XYZ, COLOR_RGB2XYZ, COLOR_XYZ2BGR, COLOR_XYZ2RGB`` ):
|
||||
|
||||
.. math::
|
||||
|
||||
\begin{bmatrix} X \\ Y \\ Z
|
||||
\end{bmatrix} \leftarrow \begin{bmatrix} 0.412453 & 0.357580 & 0.180423 \\ 0.212671 & 0.715160 & 0.072169 \\ 0.019334 & 0.119193 & 0.950227
|
||||
\end{bmatrix} \cdot \begin{bmatrix} R \\ G \\ B
|
||||
\end{bmatrix}
|
||||
|
||||
.. math::
|
||||
|
||||
\begin{bmatrix} R \\ G \\ B
|
||||
\end{bmatrix} \leftarrow \begin{bmatrix} 3.240479 & -1.53715 & -0.498535 \\ -0.969256 & 1.875991 & 0.041556 \\ 0.055648 & -0.204043 & 1.057311
|
||||
\end{bmatrix} \cdot \begin{bmatrix} X \\ Y \\ Z
|
||||
\end{bmatrix}
|
||||
|
||||
:math:`X`, :math:`Y` and
|
||||
:math:`Z` cover the whole value range (in case of floating-point images,
|
||||
:math:`Z` may exceed 1).
|
||||
|
||||
*
|
||||
RGB
|
||||
:math:`\leftrightarrow` YCrCb JPEG (or YCC) ( ``COLOR_BGR2YCrCb, COLOR_RGB2YCrCb, COLOR_YCrCb2BGR, COLOR_YCrCb2RGB`` )
|
||||
|
||||
.. math::
|
||||
|
||||
Y \leftarrow 0.299 \cdot R + 0.587 \cdot G + 0.114 \cdot B
|
||||
|
||||
.. math::
|
||||
|
||||
Cr \leftarrow (R-Y) \cdot 0.713 + delta
|
||||
|
||||
.. math::
|
||||
|
||||
Cb \leftarrow (B-Y) \cdot 0.564 + delta
|
||||
|
||||
.. math::
|
||||
|
||||
R \leftarrow Y + 1.403 \cdot (Cr - delta)
|
||||
|
||||
.. math::
|
||||
|
||||
G \leftarrow Y - 0.714 \cdot (Cr - delta) - 0.344 \cdot (Cb - delta)
|
||||
|
||||
.. math::
|
||||
|
||||
B \leftarrow Y + 1.773 \cdot (Cb - delta)
|
||||
|
||||
where
|
||||
|
||||
.. math::
|
||||
|
||||
delta = \left \{ \begin{array}{l l} 128 & \mbox{for 8-bit images} \\ 32768 & \mbox{for 16-bit images} \\ 0.5 & \mbox{for floating-point images} \end{array} \right .
|
||||
|
||||
Y, Cr, and Cb cover the whole value range.
|
||||
|
||||
*
|
||||
RGB :math:`\leftrightarrow` HSV ( ``COLOR_BGR2HSV, COLOR_RGB2HSV, COLOR_HSV2BGR, COLOR_HSV2RGB`` )
|
||||
In case of 8-bit and 16-bit images,
|
||||
R, G, and B are converted to the floating-point format and scaled to fit the 0 to 1 range.
|
||||
|
||||
.. math::
|
||||
|
||||
V \leftarrow max(R,G,B)
|
||||
|
||||
.. math::
|
||||
|
||||
S \leftarrow \fork{\frac{V-min(R,G,B)}{V}}{if $V \neq 0$}{0}{otherwise}
|
||||
|
||||
.. math::
|
||||
|
||||
H \leftarrow \forkthree{{60(G - B)}/{(V-min(R,G,B))}}{if $V=R$}{{120+60(B - R)}/{(V-min(R,G,B))}}{if $V=G$}{{240+60(R - G)}/{(V-min(R,G,B))}}{if $V=B$}
|
||||
|
||||
If
|
||||
:math:`H<0` then
|
||||
:math:`H \leftarrow H+360` . On output
|
||||
:math:`0 \leq V \leq 1`, :math:`0 \leq S \leq 1`, :math:`0 \leq H \leq 360` .
|
||||
|
||||
The values are then converted to the destination data type:
|
||||
|
||||
* 8-bit images
|
||||
|
||||
.. math::
|
||||
|
||||
V \leftarrow 255 V, S \leftarrow 255 S, H \leftarrow H/2 \text{(to fit to 0 to 255)}
|
||||
|
||||
* 16-bit images (currently not supported)
|
||||
|
||||
.. math::
|
||||
|
||||
V <- 65535 V, S <- 65535 S, H <- H
|
||||
|
||||
* 32-bit images
|
||||
H, S, and V are left as is
|
||||
|
||||
*
|
||||
RGB :math:`\leftrightarrow` HLS ( ``COLOR_BGR2HLS, COLOR_RGB2HLS, COLOR_HLS2BGR, COLOR_HLS2RGB`` ).
|
||||
In case of 8-bit and 16-bit images,
|
||||
R, G, and B are converted to the floating-point format and scaled to fit the 0 to 1 range.
|
||||
|
||||
.. math::
|
||||
|
||||
V_{max} \leftarrow {max}(R,G,B)
|
||||
|
||||
.. math::
|
||||
|
||||
V_{min} \leftarrow {min}(R,G,B)
|
||||
|
||||
.. math::
|
||||
|
||||
L \leftarrow \frac{V_{max} + V_{min}}{2}
|
||||
|
||||
.. math::
|
||||
|
||||
S \leftarrow \fork { \frac{V_{max} - V_{min}}{V_{max} + V_{min}} }{if $L < 0.5$ }
|
||||
{ \frac{V_{max} - V_{min}}{2 - (V_{max} + V_{min})} }{if $L \ge 0.5$ }
|
||||
|
||||
.. math::
|
||||
|
||||
H \leftarrow \forkthree {{60(G - B)}/{S}}{if $V_{max}=R$ }
|
||||
{{120+60(B - R)}/{S}}{if $V_{max}=G$ }
|
||||
{{240+60(R - G)}/{S}}{if $V_{max}=B$ }
|
||||
|
||||
If
|
||||
:math:`H<0` then
|
||||
:math:`H \leftarrow H+360` . On output
|
||||
:math:`0 \leq L \leq 1`, :math:`0 \leq S \leq 1`, :math:`0 \leq H \leq 360` .
|
||||
|
||||
The values are then converted to the destination data type:
|
||||
|
||||
* 8-bit images
|
||||
|
||||
.. math::
|
||||
|
||||
V \leftarrow 255 \cdot V, S \leftarrow 255 \cdot S, H \leftarrow H/2 \; \text{(to fit to 0 to 255)}
|
||||
|
||||
* 16-bit images (currently not supported)
|
||||
|
||||
.. math::
|
||||
|
||||
V <- 65535 \cdot V, S <- 65535 \cdot S, H <- H
|
||||
|
||||
* 32-bit images
|
||||
H, S, V are left as is
|
||||
|
||||
*
|
||||
RGB :math:`\leftrightarrow` CIE L*a*b* ( ``COLOR_BGR2Lab, COLOR_RGB2Lab, COLOR_Lab2BGR, COLOR_Lab2RGB`` ).
|
||||
In case of 8-bit and 16-bit images,
|
||||
R, G, and B are converted to the floating-point format and scaled to fit the 0 to 1 range.
|
||||
|
||||
.. math::
|
||||
|
||||
\vecthree{X}{Y}{Z} \leftarrow \vecthreethree{0.412453}{0.357580}{0.180423}{0.212671}{0.715160}{0.072169}{0.019334}{0.119193}{0.950227} \cdot \vecthree{R}{G}{B}
|
||||
|
||||
.. math::
|
||||
|
||||
X \leftarrow X/X_n, \text{where} X_n = 0.950456
|
||||
|
||||
.. math::
|
||||
|
||||
Z \leftarrow Z/Z_n, \text{where} Z_n = 1.088754
|
||||
|
||||
.. math::
|
||||
|
||||
L \leftarrow \fork{116*Y^{1/3}-16}{for $Y>0.008856$}{903.3*Y}{for $Y \le 0.008856$}
|
||||
|
||||
.. math::
|
||||
|
||||
a \leftarrow 500 (f(X)-f(Y)) + delta
|
||||
|
||||
.. math::
|
||||
|
||||
b \leftarrow 200 (f(Y)-f(Z)) + delta
|
||||
|
||||
where
|
||||
|
||||
.. math::
|
||||
|
||||
f(t)= \fork{t^{1/3}}{for $t>0.008856$}{7.787 t+16/116}{for $t\leq 0.008856$}
|
||||
|
||||
and
|
||||
|
||||
.. math::
|
||||
|
||||
delta = \fork{128}{for 8-bit images}{0}{for floating-point images}
|
||||
|
||||
This outputs
|
||||
:math:`0 \leq L \leq 100`, :math:`-127 \leq a \leq 127`, :math:`-127 \leq b \leq 127` . The values are then converted to the destination data type:
|
||||
|
||||
* 8-bit images
|
||||
|
||||
.. math::
|
||||
|
||||
L \leftarrow L*255/100, \; a \leftarrow a + 128, \; b \leftarrow b + 128
|
||||
|
||||
* 16-bit images
|
||||
(currently not supported)
|
||||
|
||||
* 32-bit images
|
||||
L, a, and b are left as is
|
||||
|
||||
*
|
||||
RGB :math:`\leftrightarrow` CIE L*u*v* ( ``COLOR_BGR2Luv, COLOR_RGB2Luv, COLOR_Luv2BGR, COLOR_Luv2RGB`` ).
|
||||
In case of 8-bit and 16-bit images,
|
||||
R, G, and B are converted to the floating-point format and scaled to fit 0 to 1 range.
|
||||
|
||||
.. math::
|
||||
|
||||
\vecthree{X}{Y}{Z} \leftarrow \vecthreethree{0.412453}{0.357580}{0.180423}{0.212671}{0.715160}{0.072169}{0.019334}{0.119193}{0.950227} \cdot \vecthree{R}{G}{B}
|
||||
|
||||
.. math::
|
||||
|
||||
L \leftarrow \fork{116 Y^{1/3}}{for $Y>0.008856$}{903.3 Y}{for $Y\leq 0.008856$}
|
||||
|
||||
.. math::
|
||||
|
||||
u' \leftarrow 4*X/(X + 15*Y + 3 Z)
|
||||
|
||||
.. math::
|
||||
|
||||
v' \leftarrow 9*Y/(X + 15*Y + 3 Z)
|
||||
|
||||
.. math::
|
||||
|
||||
u \leftarrow 13*L*(u' - u_n) \quad \text{where} \quad u_n=0.19793943
|
||||
|
||||
.. math::
|
||||
|
||||
v \leftarrow 13*L*(v' - v_n) \quad \text{where} \quad v_n=0.46831096
|
||||
|
||||
This outputs
|
||||
:math:`0 \leq L \leq 100`, :math:`-134 \leq u \leq 220`, :math:`-140 \leq v \leq 122` .
|
||||
|
||||
The values are then converted to the destination data type:
|
||||
|
||||
* 8-bit images
|
||||
|
||||
.. math::
|
||||
|
||||
L \leftarrow 255/100 L, \; u \leftarrow 255/354 (u + 134), \; v \leftarrow 255/262 (v + 140)
|
||||
|
||||
* 16-bit images
|
||||
(currently not supported)
|
||||
|
||||
* 32-bit images
|
||||
L, u, and v are left as is
|
||||
|
||||
The above formulae for converting RGB to/from various color spaces have been taken from multiple sources on the web, primarily from the Charles Poynton site
|
||||
http://www.poynton.com/ColorFAQ.html
|
||||
|
||||
*
|
||||
Bayer :math:`\rightarrow` RGB ( ``COLOR_BayerBG2BGR, COLOR_BayerGB2BGR, COLOR_BayerRG2BGR, COLOR_BayerGR2BGR, COLOR_BayerBG2RGB, COLOR_BayerGB2RGB, COLOR_BayerRG2RGB, COLOR_BayerGR2RGB`` ). The Bayer pattern is widely used in CCD and CMOS cameras. It enables you to get color pictures from a single plane where R,G, and B pixels (sensors of a particular component) are interleaved as follows:
|
||||
|
||||
.. image:: pics/bayer.png
|
||||
|
||||
The output RGB components of a pixel are interpolated from 1, 2, or
|
||||
4 neighbors of the pixel having the same color. There are several
|
||||
modifications of the above pattern that can be achieved by shifting
|
||||
the pattern one pixel left and/or one pixel up. The two letters
|
||||
:math:`C_1` and
|
||||
:math:`C_2` in the conversion constants ``CV_Bayer`` :math:`C_1 C_2` ``2BGR`` and ``CV_Bayer`` :math:`C_1 C_2` ``2RGB`` indicate the particular pattern
|
||||
type. These are components from the second row, second and third
|
||||
columns, respectively. For example, the above pattern has a very
|
||||
popular "BG" type.
|
||||
|
||||
|
||||
distanceTransform
|
||||
-----------------
|
||||
Calculates the distance to the closest zero pixel for each pixel of the source image.
|
||||
|
||||
.. ocv:function:: void distanceTransform( InputArray src, OutputArray dst, int distanceType, int maskSize, int dstType=CV_32F )
|
||||
|
||||
.. ocv:function:: void distanceTransform( InputArray src, OutputArray dst, OutputArray labels, int distanceType, int maskSize, int labelType=DIST_LABEL_CCOMP )
|
||||
|
||||
.. ocv:pyfunction:: cv2.distanceTransform(src, distanceType, maskSize[, dst]) -> dst
|
||||
|
||||
.. ocv:cfunction:: void cvDistTransform( const CvArr* src, CvArr* dst, int distance_type=CV_DIST_L2, int mask_size=3, const float* mask=NULL, CvArr* labels=NULL, int labelType=CV_DIST_LABEL_CCOMP )
|
||||
|
||||
:param src: 8-bit, single-channel (binary) source image.
|
||||
|
||||
:param dst: Output image with calculated distances. It is a 8-bit or 32-bit floating-point, single-channel image of the same size as ``src`` .
|
||||
|
||||
:param distanceType: Type of distance. It can be ``CV_DIST_L1, CV_DIST_L2`` , or ``CV_DIST_C`` .
|
||||
|
||||
:param maskSize: Size of the distance transform mask. It can be 3, 5, or ``CV_DIST_MASK_PRECISE`` (the latter option is only supported by the first function). In case of the ``CV_DIST_L1`` or ``CV_DIST_C`` distance type, the parameter is forced to 3 because a :math:`3\times 3` mask gives the same result as :math:`5\times 5` or any larger aperture.
|
||||
|
||||
:param dstType: Type of output image. It can be ``CV_8U`` or ``CV_32F``. Type ``CV_8U`` can be used only for the first variant of the function and ``distanceType == CV_DIST_L1``.
|
||||
|
||||
:param labels: Optional output 2D array of labels (the discrete Voronoi diagram). It has the type ``CV_32SC1`` and the same size as ``src`` . See the details below.
|
||||
|
||||
:param labelType: Type of the label array to build. If ``labelType==DIST_LABEL_CCOMP`` then each connected component of zeros in ``src`` (as well as all the non-zero pixels closest to the connected component) will be assigned the same label. If ``labelType==DIST_LABEL_PIXEL`` then each zero pixel (and all the non-zero pixels closest to it) gets its own label.
|
||||
|
||||
The functions ``distanceTransform`` calculate the approximate or precise
|
||||
distance from every binary image pixel to the nearest zero pixel.
|
||||
For zero image pixels, the distance will obviously be zero.
|
||||
|
||||
When ``maskSize == CV_DIST_MASK_PRECISE`` and ``distanceType == CV_DIST_L2`` , the function runs the algorithm described in [Felzenszwalb04]_. This algorithm is parallelized with the TBB library.
|
||||
|
||||
In other cases, the algorithm
|
||||
[Borgefors86]_
|
||||
is used. This means that
|
||||
for a pixel the function finds the shortest path to the nearest zero pixel
|
||||
consisting of basic shifts: horizontal,
|
||||
vertical, diagonal, or knight's move (the latest is available for a
|
||||
:math:`5\times 5` mask). The overall distance is calculated as a sum of these
|
||||
basic distances. Since the distance function should be symmetric,
|
||||
all of the horizontal and vertical shifts must have the same cost (denoted as ``a`` ), all the diagonal shifts must have the
|
||||
same cost (denoted as ``b`` ), and all knight's moves must have
|
||||
the same cost (denoted as ``c`` ). For the ``CV_DIST_C`` and ``CV_DIST_L1`` types, the distance is calculated precisely,
|
||||
whereas for ``CV_DIST_L2`` (Euclidean distance) the distance
|
||||
can be calculated only with a relative error (a
|
||||
:math:`5\times 5` mask
|
||||
gives more accurate results). For ``a``,``b`` , and ``c`` , OpenCV uses the values suggested in the original paper:
|
||||
|
||||
.. table::
|
||||
|
||||
============== =================== ======================
|
||||
``CV_DIST_C`` :math:`(3\times 3)` a = 1, b = 1 \
|
||||
============== =================== ======================
|
||||
``CV_DIST_L1`` :math:`(3\times 3)` a = 1, b = 2 \
|
||||
``CV_DIST_L2`` :math:`(3\times 3)` a=0.955, b=1.3693 \
|
||||
``CV_DIST_L2`` :math:`(5\times 5)` a=1, b=1.4, c=2.1969 \
|
||||
============== =================== ======================
|
||||
|
||||
Typically, for a fast, coarse distance estimation ``CV_DIST_L2``, a
|
||||
:math:`3\times 3` mask is used. For a more accurate distance estimation ``CV_DIST_L2`` , a
|
||||
:math:`5\times 5` mask or the precise algorithm is used.
|
||||
Note that both the precise and the approximate algorithms are linear on the number of pixels.
|
||||
|
||||
The second variant of the function does not only compute the minimum distance for each pixel
|
||||
:math:`(x, y)` but also identifies the nearest connected
|
||||
component consisting of zero pixels (``labelType==DIST_LABEL_CCOMP``) or the nearest zero pixel (``labelType==DIST_LABEL_PIXEL``). Index of the component/pixel is stored in
|
||||
:math:`\texttt{labels}(x, y)` .
|
||||
When ``labelType==DIST_LABEL_CCOMP``, the function automatically finds connected components of zero pixels in the input image and marks them with distinct labels. When ``labelType==DIST_LABEL_CCOMP``, the function scans through the input image and marks all the zero pixels with distinct labels.
|
||||
|
||||
In this mode, the complexity is still linear.
|
||||
That is, the function provides a very fast way to compute the Voronoi diagram for a binary image.
|
||||
Currently, the second variant can use only the approximate distance transform algorithm, i.e. ``maskSize=CV_DIST_MASK_PRECISE`` is not supported yet.
|
||||
|
||||
.. note::
|
||||
|
||||
* An example on using the distance transform can be found at opencv_source_code/samples/cpp/distrans.cpp
|
||||
|
||||
* (Python) An example on using the distance transform can be found at opencv_source/samples/python2/distrans.py
|
||||
|
||||
floodFill
|
||||
---------
|
||||
Fills a connected component with the given color.
|
||||
|
||||
.. ocv:function:: int floodFill( InputOutputArray image, Point seedPoint, Scalar newVal, Rect* rect=0, Scalar loDiff=Scalar(), Scalar upDiff=Scalar(), int flags=4 )
|
||||
|
||||
.. ocv:function:: int floodFill( InputOutputArray image, InputOutputArray mask, Point seedPoint, Scalar newVal, Rect* rect=0, Scalar loDiff=Scalar(), Scalar upDiff=Scalar(), int flags=4 )
|
||||
|
||||
.. ocv:pyfunction:: cv2.floodFill(image, mask, seedPoint, newVal[, loDiff[, upDiff[, flags]]]) -> retval, image, mask, rect
|
||||
|
||||
.. ocv:cfunction:: void cvFloodFill( CvArr* image, CvPoint seed_point, CvScalar new_val, CvScalar lo_diff=cvScalarAll(0), CvScalar up_diff=cvScalarAll(0), CvConnectedComp* comp=NULL, int flags=4, CvArr* mask=NULL )
|
||||
|
||||
:param image: Input/output 1- or 3-channel, 8-bit, or floating-point image. It is modified by the function unless the ``FLOODFILL_MASK_ONLY`` flag is set in the second variant of the function. See the details below.
|
||||
|
||||
:param mask: Operation mask that should be a single-channel 8-bit image, 2 pixels wider and 2 pixels taller than ``image``. Since this is both an input and output parameter, you must take responsibility of initializing it. Flood-filling cannot go across non-zero pixels in the input mask. For example, an edge detector output can be used as a mask to stop filling at edges. On output, pixels in the mask corresponding to filled pixels in the image are set to 1 or to the a value specified in ``flags`` as described below. It is therefore possible to use the same mask in multiple calls to the function to make sure the filled areas do not overlap.
|
||||
|
||||
.. note:: Since the mask is larger than the filled image, a pixel :math:`(x, y)` in ``image`` corresponds to the pixel :math:`(x+1, y+1)` in the ``mask`` .
|
||||
|
||||
:param seedPoint: Starting point.
|
||||
|
||||
:param newVal: New value of the repainted domain pixels.
|
||||
|
||||
:param loDiff: Maximal lower brightness/color difference between the currently observed pixel and one of its neighbors belonging to the component, or a seed pixel being added to the component.
|
||||
|
||||
:param upDiff: Maximal upper brightness/color difference between the currently observed pixel and one of its neighbors belonging to the component, or a seed pixel being added to the component.
|
||||
|
||||
:param rect: Optional output parameter set by the function to the minimum bounding rectangle of the repainted domain.
|
||||
|
||||
:param flags: Operation flags. The first 8 bits contain a connectivity value. The default value of 4 means that only the four nearest neighbor pixels (those that share an edge) are considered. A connectivity value of 8 means that the eight nearest neighbor pixels (those that share a corner) will be considered. The next 8 bits (8-16) contain a value between 1 and 255 with which to fill the ``mask`` (the default value is 1). For example, ``4 | ( 255 << 8 )`` will consider 4 nearest neighbours and fill the mask with a value of 255. The following additional options occupy higher bits and therefore may be further combined with the connectivity and mask fill values using bit-wise or (``|``):
|
||||
|
||||
* **FLOODFILL_FIXED_RANGE** If set, the difference between the current pixel and seed pixel is considered. Otherwise, the difference between neighbor pixels is considered (that is, the range is floating).
|
||||
|
||||
* **FLOODFILL_MASK_ONLY** If set, the function does not change the image ( ``newVal`` is ignored), and only fills the mask with the value specified in bits 8-16 of ``flags`` as described above. This option only make sense in function variants that have the ``mask`` parameter.
|
||||
|
||||
The functions ``floodFill`` fill a connected component starting from the seed point with the specified color. The connectivity is determined by the color/brightness closeness of the neighbor pixels. The pixel at
|
||||
:math:`(x,y)` is considered to belong to the repainted domain if:
|
||||
|
||||
*
|
||||
.. math::
|
||||
|
||||
\texttt{src} (x',y')- \texttt{loDiff} \leq \texttt{src} (x,y) \leq \texttt{src} (x',y')+ \texttt{upDiff}
|
||||
|
||||
in case of a grayscale image and floating range
|
||||
|
||||
*
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)- \texttt{loDiff} \leq \texttt{src} (x,y) \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)+ \texttt{upDiff}
|
||||
|
||||
in case of a grayscale image and fixed range
|
||||
|
||||
*
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{src} (x',y')_r- \texttt{loDiff} _r \leq \texttt{src} (x,y)_r \leq \texttt{src} (x',y')_r+ \texttt{upDiff} _r,
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{src} (x',y')_g- \texttt{loDiff} _g \leq \texttt{src} (x,y)_g \leq \texttt{src} (x',y')_g+ \texttt{upDiff} _g
|
||||
|
||||
and
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{src} (x',y')_b- \texttt{loDiff} _b \leq \texttt{src} (x,y)_b \leq \texttt{src} (x',y')_b+ \texttt{upDiff} _b
|
||||
|
||||
in case of a color image and floating range
|
||||
|
||||
|
||||
*
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_r- \texttt{loDiff} _r \leq \texttt{src} (x,y)_r \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_r+ \texttt{upDiff} _r,
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_g- \texttt{loDiff} _g \leq \texttt{src} (x,y)_g \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_g+ \texttt{upDiff} _g
|
||||
|
||||
and
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_b- \texttt{loDiff} _b \leq \texttt{src} (x,y)_b \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_b+ \texttt{upDiff} _b
|
||||
|
||||
in case of a color image and fixed range
|
||||
|
||||
where
|
||||
:math:`src(x',y')` is the value of one of pixel neighbors that is already known to belong to the component. That is, to be added to the connected component, a color/brightness of the pixel should be close enough to:
|
||||
|
||||
*
|
||||
Color/brightness of one of its neighbors that already belong to the connected component in case of a floating range.
|
||||
|
||||
*
|
||||
Color/brightness of the seed point in case of a fixed range.
|
||||
|
||||
Use these functions to either mark a connected component with the specified color in-place, or build a mask and then extract the contour, or copy the region to another image, and so on.
|
||||
|
||||
.. seealso:: :ocv:func:`findContours`
|
||||
|
||||
.. note::
|
||||
|
||||
* An example using the FloodFill technique can be found at opencv_source_code/samples/cpp/ffilldemo.cpp
|
||||
|
||||
* (Python) An example using the FloodFill technique can be found at opencv_source_code/samples/python2/floodfill.cpp
|
||||
|
||||
integral
|
||||
--------
|
||||
Calculates the integral of an image.
|
||||
|
||||
.. ocv:function:: void integral( InputArray src, OutputArray sum, int sdepth=-1 )
|
||||
|
||||
.. ocv:function:: void integral( InputArray src, OutputArray sum, OutputArray sqsum, int sdepth=-1, int sqdepth=-1 )
|
||||
|
||||
.. ocv:function:: void integral( InputArray src, OutputArray sum, OutputArray sqsum, OutputArray tilted, int sdepth=-1, int sqdepth=-1 )
|
||||
|
||||
.. ocv:pyfunction:: cv2.integral(src[, sum[, sdepth]]) -> sum
|
||||
|
||||
.. ocv:pyfunction:: cv2.integral2(src[, sum[, sqsum[, sdepth[, sqdepth]]]]) -> sum, sqsum
|
||||
|
||||
.. ocv:pyfunction:: cv2.integral3(src[, sum[, sqsum[, tilted[, sdepth[, sqdepth]]]]]) -> sum, sqsum, tilted
|
||||
|
||||
.. ocv:cfunction:: void cvIntegral( const CvArr* image, CvArr* sum, CvArr* sqsum=NULL, CvArr* tilted_sum=NULL )
|
||||
|
||||
:param image: input image as :math:`W \times H`, 8-bit or floating-point (32f or 64f).
|
||||
|
||||
:param sum: integral image as :math:`(W+1)\times (H+1)` , 32-bit integer or floating-point (32f or 64f).
|
||||
|
||||
:param sqsum: integral image for squared pixel values; it is :math:`(W+1)\times (H+1)`, double-precision floating-point (64f) array.
|
||||
|
||||
:param tilted: integral for the image rotated by 45 degrees; it is :math:`(W+1)\times (H+1)` array with the same data type as ``sum``.
|
||||
|
||||
:param sdepth: desired depth of the integral and the tilted integral images, ``CV_32S``, ``CV_32F``, or ``CV_64F``.
|
||||
|
||||
:param sqdepth: desired depth of the integral image of squared pixel values, ``CV_32F`` or ``CV_64F``.
|
||||
|
||||
The functions calculate one or more integral images for the source image as follows:
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{sum} (X,Y) = \sum _{x<X,y<Y} \texttt{image} (x,y)
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{sqsum} (X,Y) = \sum _{x<X,y<Y} \texttt{image} (x,y)^2
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{tilted} (X,Y) = \sum _{y<Y,abs(x-X+1) \leq Y-y-1} \texttt{image} (x,y)
|
||||
|
||||
Using these integral images, you can calculate sum, mean, and standard deviation over a specific up-right or rotated rectangular region of the image in a constant time, for example:
|
||||
|
||||
.. math::
|
||||
|
||||
\sum _{x_1 \leq x < x_2, \, y_1 \leq y < y_2} \texttt{image} (x,y) = \texttt{sum} (x_2,y_2)- \texttt{sum} (x_1,y_2)- \texttt{sum} (x_2,y_1)+ \texttt{sum} (x_1,y_1)
|
||||
|
||||
It makes possible to do a fast blurring or fast block correlation with a variable window size, for example. In case of multi-channel images, sums for each channel are accumulated independently.
|
||||
|
||||
As a practical example, the next figure shows the calculation of the integral of a straight rectangle ``Rect(3,3,3,2)`` and of a tilted rectangle ``Rect(5,1,2,3)`` . The selected pixels in the original ``image`` are shown, as well as the relative pixels in the integral images ``sum`` and ``tilted`` .
|
||||
|
||||
.. image:: pics/integral.png
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
threshold
|
||||
---------
|
||||
Applies a fixed-level threshold to each array element.
|
||||
|
||||
.. ocv:function:: double threshold( InputArray src, OutputArray dst, double thresh, double maxval, int type )
|
||||
|
||||
.. ocv:pyfunction:: cv2.threshold(src, thresh, maxval, type[, dst]) -> retval, dst
|
||||
|
||||
.. ocv:cfunction:: double cvThreshold( const CvArr* src, CvArr* dst, double threshold, double max_value, int threshold_type )
|
||||
|
||||
:param src: input array (single-channel, 8-bit or 32-bit floating point).
|
||||
|
||||
:param dst: output array of the same size and type as ``src``.
|
||||
|
||||
:param thresh: threshold value.
|
||||
|
||||
:param maxval: maximum value to use with the ``THRESH_BINARY`` and ``THRESH_BINARY_INV`` thresholding types.
|
||||
|
||||
:param type: thresholding type (see the details below).
|
||||
|
||||
The function applies fixed-level thresholding
|
||||
to a single-channel array. The function is typically used to get a
|
||||
bi-level (binary) image out of a grayscale image (
|
||||
:ocv:func:`compare` could
|
||||
be also used for this purpose) or for removing a noise, that is, filtering
|
||||
out pixels with too small or too large values. There are several
|
||||
types of thresholding supported by the function. They are determined by ``type`` :
|
||||
|
||||
* **THRESH_BINARY**
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{dst} (x,y) = \fork{\texttt{maxval}}{if $\texttt{src}(x,y) > \texttt{thresh}$}{0}{otherwise}
|
||||
|
||||
* **THRESH_BINARY_INV**
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{dst} (x,y) = \fork{0}{if $\texttt{src}(x,y) > \texttt{thresh}$}{\texttt{maxval}}{otherwise}
|
||||
|
||||
* **THRESH_TRUNC**
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{dst} (x,y) = \fork{\texttt{threshold}}{if $\texttt{src}(x,y) > \texttt{thresh}$}{\texttt{src}(x,y)}{otherwise}
|
||||
|
||||
* **THRESH_TOZERO**
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{dst} (x,y) = \fork{\texttt{src}(x,y)}{if $\texttt{src}(x,y) > \texttt{thresh}$}{0}{otherwise}
|
||||
|
||||
* **THRESH_TOZERO_INV**
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{dst} (x,y) = \fork{0}{if $\texttt{src}(x,y) > \texttt{thresh}$}{\texttt{src}(x,y)}{otherwise}
|
||||
|
||||
Also, the special values ``THRESH_OTSU`` or ``THRESH_TRIANGLE`` may be combined with
|
||||
one of the above values. In these cases, the function determines the optimal threshold
|
||||
value using the Otsu's or Triangle algorithm and uses it instead of the specified ``thresh`` .
|
||||
The function returns the computed threshold value.
|
||||
Currently, the Otsu's and Triangle methods are implemented only for 8-bit images.
|
||||
|
||||
|
||||
.. image:: pics/threshold.png
|
||||
|
||||
.. seealso::
|
||||
|
||||
:ocv:func:`adaptiveThreshold`,
|
||||
:ocv:func:`findContours`,
|
||||
:ocv:func:`compare`,
|
||||
:ocv:func:`min`,
|
||||
:ocv:func:`max`
|
||||
|
||||
|
||||
watershed
|
||||
---------
|
||||
Performs a marker-based image segmentation using the watershed algorithm.
|
||||
|
||||
.. ocv:function:: void watershed( InputArray image, InputOutputArray markers )
|
||||
|
||||
.. ocv:cfunction:: void cvWatershed( const CvArr* image, CvArr* markers )
|
||||
|
||||
.. ocv:pyfunction:: cv2.watershed(image, markers) -> markers
|
||||
|
||||
:param image: Input 8-bit 3-channel image.
|
||||
|
||||
:param markers: Input/output 32-bit single-channel image (map) of markers. It should have the same size as ``image`` .
|
||||
|
||||
The function implements one of the variants of watershed, non-parametric marker-based segmentation algorithm, described in [Meyer92]_.
|
||||
|
||||
Before passing the image to the function, you have to roughly outline the desired regions in the image ``markers`` with positive (``>0``) indices. So, every region is represented as one or more connected components with the pixel values 1, 2, 3, and so on. Such markers can be retrieved from a binary mask using :ocv:func:`findContours` and :ocv:func:`drawContours` (see the ``watershed.cpp`` demo). The markers are "seeds" of the future image regions. All the other pixels in ``markers`` , whose relation to the outlined regions is not known and should be defined by the algorithm, should be set to 0's. In the function output, each pixel in markers is set to a value of the "seed" components or to -1 at boundaries between the regions.
|
||||
|
||||
Visual demonstration and usage example of the function can be found in the OpenCV samples directory (see the ``watershed.cpp`` demo).
|
||||
|
||||
.. note:: Any two neighbor connected components are not necessarily separated by a watershed boundary (-1's pixels); for example, they can touch each other in the initial marker image passed to the function.
|
||||
|
||||
.. seealso:: :ocv:func:`findContours`
|
||||
|
||||
.. note::
|
||||
|
||||
* An example using the watershed algorithm can be found at opencv_source_code/samples/cpp/watershed.cpp
|
||||
|
||||
* (Python) An example using the watershed algorithm can be found at opencv_source_code/samples/python2/watershed.py
|
||||
|
||||
grabCut
|
||||
-------
|
||||
Runs the GrabCut algorithm.
|
||||
|
||||
.. ocv:function:: void grabCut( InputArray img, InputOutputArray mask, Rect rect, InputOutputArray bgdModel, InputOutputArray fgdModel, int iterCount, int mode=GC_EVAL )
|
||||
|
||||
.. ocv:pyfunction:: cv2.grabCut(img, mask, rect, bgdModel, fgdModel, iterCount[, mode]) -> mask, bgdModel, fgdModel
|
||||
|
||||
:param img: Input 8-bit 3-channel image.
|
||||
|
||||
:param mask: Input/output 8-bit single-channel mask. The mask is initialized by the function when ``mode`` is set to ``GC_INIT_WITH_RECT``. Its elements may have one of following values:
|
||||
|
||||
* **GC_BGD** defines an obvious background pixels.
|
||||
|
||||
* **GC_FGD** defines an obvious foreground (object) pixel.
|
||||
|
||||
* **GC_PR_BGD** defines a possible background pixel.
|
||||
|
||||
* **GC_PR_FGD** defines a possible foreground pixel.
|
||||
|
||||
:param rect: ROI containing a segmented object. The pixels outside of the ROI are marked as "obvious background". The parameter is only used when ``mode==GC_INIT_WITH_RECT`` .
|
||||
|
||||
:param bgdModel: Temporary array for the background model. Do not modify it while you are processing the same image.
|
||||
|
||||
:param fgdModel: Temporary arrays for the foreground model. Do not modify it while you are processing the same image.
|
||||
|
||||
:param iterCount: Number of iterations the algorithm should make before returning the result. Note that the result can be refined with further calls with ``mode==GC_INIT_WITH_MASK`` or ``mode==GC_EVAL`` .
|
||||
|
||||
:param mode: Operation mode that could be one of the following:
|
||||
|
||||
* **GC_INIT_WITH_RECT** The function initializes the state and the mask using the provided rectangle. After that it runs ``iterCount`` iterations of the algorithm.
|
||||
|
||||
* **GC_INIT_WITH_MASK** The function initializes the state using the provided mask. Note that ``GC_INIT_WITH_RECT`` and ``GC_INIT_WITH_MASK`` can be combined. Then, all the pixels outside of the ROI are automatically initialized with ``GC_BGD`` .
|
||||
|
||||
* **GC_EVAL** The value means that the algorithm should just resume.
|
||||
|
||||
The function implements the `GrabCut image segmentation algorithm <http://en.wikipedia.org/wiki/GrabCut>`_.
|
||||
See the sample ``grabcut.cpp`` to learn how to use the function.
|
||||
|
||||
.. [Borgefors86] Borgefors, Gunilla, *Distance transformations in digital images*. Comput. Vision Graph. Image Process. 34 3, pp 344–371 (1986)
|
||||
|
||||
.. [Felzenszwalb04] Felzenszwalb, Pedro F. and Huttenlocher, Daniel P. *Distance Transforms of Sampled Functions*, TR2004-1963, TR2004-1963 (2004)
|
||||
|
||||
.. [Meyer92] Meyer, F. *Color Image Segmentation*, ICIP92, 1992
|
||||
|
||||
|
||||
.. note::
|
||||
|
||||
* An example using the GrabCut algorithm can be found at opencv_source_code/samples/cpp/grabcut.cpp
|
||||
|
||||
* (Python) An example using the GrabCut algorithm can be found at opencv_source_code/samples/python2/grabcut.py
|
||||
@@ -1,213 +0,0 @@
|
||||
Motion Analysis and Object Tracking
|
||||
===================================
|
||||
|
||||
.. highlight:: cpp
|
||||
|
||||
accumulate
|
||||
--------------
|
||||
Adds an image to the accumulator.
|
||||
|
||||
.. ocv:function:: void accumulate( InputArray src, InputOutputArray dst, InputArray mask=noArray() )
|
||||
|
||||
.. ocv:pyfunction:: cv2.accumulate(src, dst[, mask]) -> dst
|
||||
|
||||
.. ocv:cfunction:: void cvAcc( const CvArr* image, CvArr* sum, const CvArr* mask=NULL )
|
||||
|
||||
:param src: Input image as 1- or 3-channel, 8-bit or 32-bit floating point.
|
||||
|
||||
:param dst: Accumulator image with the same number of channels as input image, 32-bit or 64-bit floating-point.
|
||||
|
||||
:param mask: Optional operation mask.
|
||||
|
||||
The function adds ``src`` or some of its elements to ``dst`` :
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{dst} (x,y) \leftarrow \texttt{dst} (x,y) + \texttt{src} (x,y) \quad \text{if} \quad \texttt{mask} (x,y) \ne 0
|
||||
|
||||
The function supports multi-channel images. Each channel is processed independently.
|
||||
|
||||
The functions ``accumulate*`` can be used, for example, to collect statistics of a scene background viewed by a still camera and for the further foreground-background segmentation.
|
||||
|
||||
.. seealso::
|
||||
|
||||
:ocv:func:`accumulateSquare`,
|
||||
:ocv:func:`accumulateProduct`,
|
||||
:ocv:func:`accumulateWeighted`
|
||||
|
||||
|
||||
|
||||
accumulateSquare
|
||||
--------------------
|
||||
Adds the square of a source image to the accumulator.
|
||||
|
||||
.. ocv:function:: void accumulateSquare( InputArray src, InputOutputArray dst, InputArray mask=noArray() )
|
||||
|
||||
.. ocv:pyfunction:: cv2.accumulateSquare(src, dst[, mask]) -> dst
|
||||
|
||||
.. ocv:cfunction:: void cvSquareAcc( const CvArr* image, CvArr* sqsum, const CvArr* mask=NULL )
|
||||
|
||||
:param src: Input image as 1- or 3-channel, 8-bit or 32-bit floating point.
|
||||
|
||||
:param dst: Accumulator image with the same number of channels as input image, 32-bit or 64-bit floating-point.
|
||||
|
||||
:param mask: Optional operation mask.
|
||||
|
||||
The function adds the input image ``src`` or its selected region, raised to a power of 2, to the accumulator ``dst`` :
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{dst} (x,y) \leftarrow \texttt{dst} (x,y) + \texttt{src} (x,y)^2 \quad \text{if} \quad \texttt{mask} (x,y) \ne 0
|
||||
|
||||
The function supports multi-channel images. Each channel is processed independently.
|
||||
|
||||
.. seealso::
|
||||
|
||||
:ocv:func:`accumulateSquare`,
|
||||
:ocv:func:`accumulateProduct`,
|
||||
:ocv:func:`accumulateWeighted`
|
||||
|
||||
|
||||
|
||||
accumulateProduct
|
||||
---------------------
|
||||
Adds the per-element product of two input images to the accumulator.
|
||||
|
||||
.. ocv:function:: void accumulateProduct( InputArray src1, InputArray src2, InputOutputArray dst, InputArray mask=noArray() )
|
||||
|
||||
.. ocv:pyfunction:: cv2.accumulateProduct(src1, src2, dst[, mask]) -> dst
|
||||
|
||||
.. ocv:cfunction:: void cvMultiplyAcc( const CvArr* image1, const CvArr* image2, CvArr* acc, const CvArr* mask=NULL )
|
||||
|
||||
:param src1: First input image, 1- or 3-channel, 8-bit or 32-bit floating point.
|
||||
|
||||
:param src2: Second input image of the same type and the same size as ``src1`` .
|
||||
|
||||
:param dst: Accumulator with the same number of channels as input images, 32-bit or 64-bit floating-point.
|
||||
|
||||
:param mask: Optional operation mask.
|
||||
|
||||
The function adds the product of two images or their selected regions to the accumulator ``dst`` :
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{dst} (x,y) \leftarrow \texttt{dst} (x,y) + \texttt{src1} (x,y) \cdot \texttt{src2} (x,y) \quad \text{if} \quad \texttt{mask} (x,y) \ne 0
|
||||
|
||||
The function supports multi-channel images. Each channel is processed independently.
|
||||
|
||||
.. seealso::
|
||||
|
||||
:ocv:func:`accumulate`,
|
||||
:ocv:func:`accumulateSquare`,
|
||||
:ocv:func:`accumulateWeighted`
|
||||
|
||||
|
||||
|
||||
accumulateWeighted
|
||||
----------------------
|
||||
Updates a running average.
|
||||
|
||||
.. ocv:function:: void accumulateWeighted( InputArray src, InputOutputArray dst, double alpha, InputArray mask=noArray() )
|
||||
|
||||
.. ocv:pyfunction:: cv2.accumulateWeighted(src, dst, alpha[, mask]) -> dst
|
||||
|
||||
.. ocv:cfunction:: void cvRunningAvg( const CvArr* image, CvArr* acc, double alpha, const CvArr* mask=NULL )
|
||||
|
||||
:param src: Input image as 1- or 3-channel, 8-bit or 32-bit floating point.
|
||||
|
||||
:param dst: Accumulator image with the same number of channels as input image, 32-bit or 64-bit floating-point.
|
||||
|
||||
:param alpha: Weight of the input image.
|
||||
|
||||
:param mask: Optional operation mask.
|
||||
|
||||
The function calculates the weighted sum of the input image ``src`` and the accumulator ``dst`` so that ``dst`` becomes a running average of a frame sequence:
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{dst} (x,y) \leftarrow (1- \texttt{alpha} ) \cdot \texttt{dst} (x,y) + \texttt{alpha} \cdot \texttt{src} (x,y) \quad \text{if} \quad \texttt{mask} (x,y) \ne 0
|
||||
|
||||
That is, ``alpha`` regulates the update speed (how fast the accumulator "forgets" about earlier images).
|
||||
The function supports multi-channel images. Each channel is processed independently.
|
||||
|
||||
.. seealso::
|
||||
|
||||
:ocv:func:`accumulate`,
|
||||
:ocv:func:`accumulateSquare`,
|
||||
:ocv:func:`accumulateProduct`
|
||||
|
||||
|
||||
|
||||
phaseCorrelate
|
||||
--------------
|
||||
The function is used to detect translational shifts that occur between two images. The operation takes advantage of the Fourier shift theorem for detecting the translational shift in the frequency domain. It can be used for fast image registration as well as motion estimation. For more information please see http://en.wikipedia.org/wiki/Phase\_correlation .
|
||||
|
||||
Calculates the cross-power spectrum of two supplied source arrays. The arrays are padded if needed with :ocv:func:`getOptimalDFTSize`.
|
||||
|
||||
.. ocv:function:: Point2d phaseCorrelate(InputArray src1, InputArray src2, InputArray window = noArray(), double* response = 0)
|
||||
|
||||
:param src1: Source floating point array (CV_32FC1 or CV_64FC1)
|
||||
:param src2: Source floating point array (CV_32FC1 or CV_64FC1)
|
||||
:param window: Floating point array with windowing coefficients to reduce edge effects (optional).
|
||||
:param response: Signal power within the 5x5 centroid around the peak, between 0 and 1 (optional).
|
||||
|
||||
Return value: detected phase shift (sub-pixel) between the two arrays.
|
||||
|
||||
The function performs the following equations
|
||||
|
||||
* First it applies a Hanning window (see http://en.wikipedia.org/wiki/Hann\_function) to each image to remove possible edge effects. This window is cached until the array size changes to speed up processing time.
|
||||
|
||||
* Next it computes the forward DFTs of each source array:
|
||||
|
||||
.. math::
|
||||
|
||||
\mathbf{G}_a = \mathcal{F}\{src_1\}, \; \mathbf{G}_b = \mathcal{F}\{src_2\}
|
||||
|
||||
where
|
||||
:math:`\mathcal{F}` is the forward DFT.
|
||||
|
||||
* It then computes the cross-power spectrum of each frequency domain array:
|
||||
|
||||
.. math::
|
||||
|
||||
R = \frac{ \mathbf{G}_a \mathbf{G}_b^*}{|\mathbf{G}_a \mathbf{G}_b^*|}
|
||||
|
||||
* Next the cross-correlation is converted back into the time domain via the inverse DFT:
|
||||
|
||||
.. math::
|
||||
|
||||
r = \mathcal{F}^{-1}\{R\}
|
||||
|
||||
* Finally, it computes the peak location and computes a 5x5 weighted centroid around the peak to achieve sub-pixel accuracy.
|
||||
|
||||
.. math::
|
||||
|
||||
(\Delta x, \Delta y) = \texttt{weightedCentroid} \{\arg \max_{(x, y)}\{r\}\}
|
||||
|
||||
* If non-zero, the response parameter is computed as the sum of the elements of r within the 5x5 centroid around the peak location. It is normalized to a maximum of 1 (meaning there is a single peak) and will be smaller when there are multiple peaks.
|
||||
|
||||
.. seealso::
|
||||
:ocv:func:`dft`,
|
||||
:ocv:func:`getOptimalDFTSize`,
|
||||
:ocv:func:`idft`,
|
||||
:ocv:func:`mulSpectrums`
|
||||
:ocv:func:`createHanningWindow`
|
||||
|
||||
createHanningWindow
|
||||
-------------------------------
|
||||
This function computes a Hanning window coefficients in two dimensions. See http://en.wikipedia.org/wiki/Hann\_function and http://en.wikipedia.org/wiki/Window\_function for more information.
|
||||
|
||||
.. ocv:function:: void createHanningWindow(OutputArray dst, Size winSize, int type)
|
||||
|
||||
:param dst: Destination array to place Hann coefficients in
|
||||
:param winSize: The window size specifications
|
||||
:param type: Created array type
|
||||
|
||||
An example is shown below: ::
|
||||
|
||||
// create hanning window of size 100x100 and type CV_32F
|
||||
Mat hann;
|
||||
createHanningWindow(hann, Size(100, 100), CV_32F);
|
||||
|
||||
.. seealso::
|
||||
:ocv:func:`phaseCorrelate`
|
||||
@@ -1,79 +0,0 @@
|
||||
Object Detection
|
||||
================
|
||||
|
||||
.. highlight:: cpp
|
||||
|
||||
matchTemplate
|
||||
-----------------
|
||||
Compares a template against overlapped image regions.
|
||||
|
||||
.. ocv:function:: void matchTemplate( InputArray image, InputArray templ, OutputArray result, int method )
|
||||
|
||||
.. ocv:pyfunction:: cv2.matchTemplate(image, templ, method[, result]) -> result
|
||||
|
||||
.. ocv:cfunction:: void cvMatchTemplate( const CvArr* image, const CvArr* templ, CvArr* result, int method )
|
||||
|
||||
:param image: Image where the search is running. It must be 8-bit or 32-bit floating-point.
|
||||
|
||||
:param templ: Searched template. It must be not greater than the source image and have the same data type.
|
||||
|
||||
:param result: Map of comparison results. It must be single-channel 32-bit floating-point. If ``image`` is :math:`W \times H` and ``templ`` is :math:`w \times h` , then ``result`` is :math:`(W-w+1) \times (H-h+1)` .
|
||||
|
||||
:param method: Parameter specifying the comparison method (see below).
|
||||
|
||||
The function slides through ``image`` , compares the
|
||||
overlapped patches of size
|
||||
:math:`w \times h` against ``templ`` using the specified method and stores the comparison results in ``result`` . Here are the formulae for the available comparison
|
||||
methods (
|
||||
:math:`I` denotes ``image``, :math:`T` ``template``, :math:`R` ``result`` ). The summation is done over template and/or the
|
||||
image patch:
|
||||
:math:`x' = 0...w-1, y' = 0...h-1`
|
||||
|
||||
* method=CV\_TM\_SQDIFF
|
||||
|
||||
.. math::
|
||||
|
||||
R(x,y)= \sum _{x',y'} (T(x',y')-I(x+x',y+y'))^2
|
||||
|
||||
* method=CV\_TM\_SQDIFF\_NORMED
|
||||
|
||||
.. math::
|
||||
|
||||
R(x,y)= \frac{\sum_{x',y'} (T(x',y')-I(x+x',y+y'))^2}{\sqrt{\sum_{x',y'}T(x',y')^2 \cdot \sum_{x',y'} I(x+x',y+y')^2}}
|
||||
|
||||
* method=CV\_TM\_CCORR
|
||||
|
||||
.. math::
|
||||
|
||||
R(x,y)= \sum _{x',y'} (T(x',y') \cdot I(x+x',y+y'))
|
||||
|
||||
* method=CV\_TM\_CCORR\_NORMED
|
||||
|
||||
.. math::
|
||||
|
||||
R(x,y)= \frac{\sum_{x',y'} (T(x',y') \cdot I(x+x',y+y'))}{\sqrt{\sum_{x',y'}T(x',y')^2 \cdot \sum_{x',y'} I(x+x',y+y')^2}}
|
||||
|
||||
* method=CV\_TM\_CCOEFF
|
||||
|
||||
.. math::
|
||||
|
||||
R(x,y)= \sum _{x',y'} (T'(x',y') \cdot I'(x+x',y+y'))
|
||||
|
||||
where
|
||||
|
||||
.. math::
|
||||
|
||||
\begin{array}{l} T'(x',y')=T(x',y') - 1/(w \cdot h) \cdot \sum _{x'',y''} T(x'',y'') \\ I'(x+x',y+y')=I(x+x',y+y') - 1/(w \cdot h) \cdot \sum _{x'',y''} I(x+x'',y+y'') \end{array}
|
||||
|
||||
* method=CV\_TM\_CCOEFF\_NORMED
|
||||
|
||||
.. math::
|
||||
|
||||
R(x,y)= \frac{ \sum_{x',y'} (T'(x',y') \cdot I'(x+x',y+y')) }{ \sqrt{\sum_{x',y'}T'(x',y')^2 \cdot \sum_{x',y'} I'(x+x',y+y')^2} }
|
||||
|
||||
After the function finishes the comparison, the best matches can be found as global minimums (when ``CV_TM_SQDIFF`` was used) or maximums (when ``CV_TM_CCORR`` or ``CV_TM_CCOEFF`` was used) using the
|
||||
:ocv:func:`minMaxLoc` function. In case of a color image, template summation in the numerator and each sum in the denominator is done over all of the channels and separate mean values are used for each channel. That is, the function can take a color template and a color image. The result will still be a single-channel image, which is easier to analyze.
|
||||
|
||||
.. note::
|
||||
|
||||
* (Python) An example on how to match mouse selected regions in an image can be found at opencv_source_code/samples/python2/mouse_and_match.py
|
||||
@@ -1,746 +0,0 @@
|
||||
Structural Analysis and Shape Descriptors
|
||||
=========================================
|
||||
|
||||
.. highlight:: cpp
|
||||
|
||||
moments
|
||||
-----------
|
||||
Calculates all of the moments up to the third order of a polygon or rasterized shape.
|
||||
|
||||
.. ocv:function:: Moments moments( InputArray array, bool binaryImage=false )
|
||||
|
||||
.. ocv:pyfunction:: cv2.moments(array[, binaryImage]) -> retval
|
||||
|
||||
.. ocv:cfunction:: void cvMoments( const CvArr* arr, CvMoments* moments, int binary=0 )
|
||||
|
||||
:param array: Raster image (single-channel, 8-bit or floating-point 2D array) or an array ( :math:`1 \times N` or :math:`N \times 1` ) of 2D points (``Point`` or ``Point2f`` ).
|
||||
|
||||
:param binaryImage: If it is true, all non-zero image pixels are treated as 1's. The parameter is used for images only.
|
||||
|
||||
:param moments: Output moments.
|
||||
|
||||
The function computes moments, up to the 3rd order, of a vector shape or a rasterized shape. The results are returned in the structure ``Moments`` defined as: ::
|
||||
|
||||
class Moments
|
||||
{
|
||||
public:
|
||||
Moments();
|
||||
Moments(double m00, double m10, double m01, double m20, double m11,
|
||||
double m02, double m30, double m21, double m12, double m03 );
|
||||
Moments( const CvMoments& moments );
|
||||
operator CvMoments() const;
|
||||
|
||||
// spatial moments
|
||||
double m00, m10, m01, m20, m11, m02, m30, m21, m12, m03;
|
||||
// central moments
|
||||
double mu20, mu11, mu02, mu30, mu21, mu12, mu03;
|
||||
// central normalized moments
|
||||
double nu20, nu11, nu02, nu30, nu21, nu12, nu03;
|
||||
}
|
||||
|
||||
In case of a raster image, the spatial moments :math:`\texttt{Moments::m}_{ji}` are computed as:
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{m} _{ji}= \sum _{x,y} \left ( \texttt{array} (x,y) \cdot x^j \cdot y^i \right )
|
||||
|
||||
The central moments
|
||||
:math:`\texttt{Moments::mu}_{ji}` are computed as:
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{mu} _{ji}= \sum _{x,y} \left ( \texttt{array} (x,y) \cdot (x - \bar{x} )^j \cdot (y - \bar{y} )^i \right )
|
||||
|
||||
where
|
||||
:math:`(\bar{x}, \bar{y})` is the mass center:
|
||||
|
||||
.. math::
|
||||
|
||||
\bar{x} = \frac{\texttt{m}_{10}}{\texttt{m}_{00}} , \; \bar{y} = \frac{\texttt{m}_{01}}{\texttt{m}_{00}}
|
||||
|
||||
The normalized central moments
|
||||
:math:`\texttt{Moments::nu}_{ij}` are computed as:
|
||||
|
||||
.. math::
|
||||
|
||||
\texttt{nu} _{ji}= \frac{\texttt{mu}_{ji}}{\texttt{m}_{00}^{(i+j)/2+1}} .
|
||||
|
||||
.. note::
|
||||
|
||||
:math:`\texttt{mu}_{00}=\texttt{m}_{00}`,
|
||||
:math:`\texttt{nu}_{00}=1`
|
||||
:math:`\texttt{nu}_{10}=\texttt{mu}_{10}=\texttt{mu}_{01}=\texttt{mu}_{10}=0` , hence the values are not stored.
|
||||
|
||||
The moments of a contour are defined in the same way but computed using the Green's formula (see http://en.wikipedia.org/wiki/Green_theorem). So, due to a limited raster resolution, the moments computed for a contour are slightly different from the moments computed for the same rasterized contour.
|
||||
|
||||
.. note::
|
||||
|
||||
Since the contour moments are computed using Green formula, you may get seemingly odd results for contours with self-intersections, e.g. a zero area (``m00``) for butterfly-shaped contours.
|
||||
|
||||
.. seealso::
|
||||
|
||||
:ocv:func:`contourArea`,
|
||||
:ocv:func:`arcLength`
|
||||
|
||||
|
||||
|
||||
HuMoments
|
||||
-------------
|
||||
Calculates seven Hu invariants.
|
||||
|
||||
.. ocv:function:: void HuMoments( const Moments& m, OutputArray hu )
|
||||
|
||||
.. ocv:function:: void HuMoments( const Moments& moments, double hu[7] )
|
||||
|
||||
.. ocv:pyfunction:: cv2.HuMoments(m[, hu]) -> hu
|
||||
|
||||
.. ocv:cfunction:: void cvGetHuMoments( CvMoments* moments, CvHuMoments* hu_moments )
|
||||
|
||||
:param moments: Input moments computed with :ocv:func:`moments` .
|
||||
:param hu: Output Hu invariants.
|
||||
|
||||
The function calculates seven Hu invariants (introduced in [Hu62]_; see also
|
||||
http://en.wikipedia.org/wiki/Image_moment) defined as:
|
||||
|
||||
.. math::
|
||||
|
||||
\begin{array}{l} hu[0]= \eta _{20}+ \eta _{02} \\ hu[1]=( \eta _{20}- \eta _{02})^{2}+4 \eta _{11}^{2} \\ hu[2]=( \eta _{30}-3 \eta _{12})^{2}+ (3 \eta _{21}- \eta _{03})^{2} \\ hu[3]=( \eta _{30}+ \eta _{12})^{2}+ ( \eta _{21}+ \eta _{03})^{2} \\ hu[4]=( \eta _{30}-3 \eta _{12})( \eta _{30}+ \eta _{12})[( \eta _{30}+ \eta _{12})^{2}-3( \eta _{21}+ \eta _{03})^{2}]+(3 \eta _{21}- \eta _{03})( \eta _{21}+ \eta _{03})[3( \eta _{30}+ \eta _{12})^{2}-( \eta _{21}+ \eta _{03})^{2}] \\ hu[5]=( \eta _{20}- \eta _{02})[( \eta _{30}+ \eta _{12})^{2}- ( \eta _{21}+ \eta _{03})^{2}]+4 \eta _{11}( \eta _{30}+ \eta _{12})( \eta _{21}+ \eta _{03}) \\ hu[6]=(3 \eta _{21}- \eta _{03})( \eta _{21}+ \eta _{03})[3( \eta _{30}+ \eta _{12})^{2}-( \eta _{21}+ \eta _{03})^{2}]-( \eta _{30}-3 \eta _{12})( \eta _{21}+ \eta _{03})[3( \eta _{30}+ \eta _{12})^{2}-( \eta _{21}+ \eta _{03})^{2}] \\ \end{array}
|
||||
|
||||
where
|
||||
:math:`\eta_{ji}` stands for
|
||||
:math:`\texttt{Moments::nu}_{ji}` .
|
||||
|
||||
These values are proved to be invariants to the image scale, rotation, and reflection except the seventh one, whose sign is changed by reflection. This invariance is proved with the assumption of infinite image resolution. In case of raster images, the computed Hu invariants for the original and transformed images are a bit different.
|
||||
|
||||
.. seealso:: :ocv:func:`matchShapes`
|
||||
|
||||
connectedComponents
|
||||
-----------------------
|
||||
computes the connected components labeled image of boolean image ``image`` with 4 or 8 way connectivity - returns N, the total number of labels [0, N-1] where 0 represents the background label. ltype specifies the output label image type, an important consideration based on the total number of labels or alternatively the total number of pixels in the source image.
|
||||
|
||||
.. ocv:function:: int connectedComponents(InputArray image, OutputArray labels, int connectivity = 8, int ltype=CV_32S)
|
||||
|
||||
.. ocv:function:: int connectedComponentsWithStats(InputArray image, OutputArray labels, OutputArray stats, OutputArray centroids, int connectivity = 8, int ltype=CV_32S)
|
||||
|
||||
:param image: the image to be labeled
|
||||
|
||||
:param labels: destination labeled image
|
||||
|
||||
:param connectivity: 8 or 4 for 8-way or 4-way connectivity respectively
|
||||
|
||||
:param ltype: output image label type. Currently CV_32S and CV_16U are supported.
|
||||
|
||||
:param statsv: statistics output for each label, including the background label, see below for available statistics. Statistics are accessed via statsv(label, COLUMN) where available columns are defined below.
|
||||
|
||||
* **CC_STAT_LEFT** The leftmost (x) coordinate which is the inclusive start of the bounding box in the horizontal
|
||||
direction.
|
||||
|
||||
* **CC_STAT_TOP** The topmost (y) coordinate which is the inclusive start of the bounding box in the vertical
|
||||
direction.
|
||||
|
||||
* **CC_STAT_WIDTH** The horizontal size of the bounding box
|
||||
|
||||
* **CC_STAT_HEIGHT** The vertical size of the bounding box
|
||||
|
||||
* **CC_STAT_AREA** The total area (in pixels) of the connected component
|
||||
|
||||
:param centroids: floating point centroid (x,y) output for each label, including the background label
|
||||
|
||||
|
||||
findContours
|
||||
----------------
|
||||
Finds contours in a binary image.
|
||||
|
||||
.. ocv:function:: void findContours( InputOutputArray image, OutputArrayOfArrays contours, OutputArray hierarchy, int mode, int method, Point offset=Point())
|
||||
|
||||
.. ocv:function:: void findContours( InputOutputArray image, OutputArrayOfArrays contours, int mode, int method, Point offset=Point())
|
||||
|
||||
.. ocv:pyfunction:: cv2.findContours(image, mode, method[, contours[, hierarchy[, offset]]]) -> image, contours, hierarchy
|
||||
|
||||
.. ocv:cfunction:: int cvFindContours( CvArr* image, CvMemStorage* storage, CvSeq** first_contour, int header_size=sizeof(CvContour), int mode=CV_RETR_LIST, int method=CV_CHAIN_APPROX_SIMPLE, CvPoint offset=cvPoint(0,0) )
|
||||
|
||||
:param image: Source, an 8-bit single-channel image. Non-zero pixels are treated as 1's. Zero pixels remain 0's, so the image is treated as ``binary`` . You can use :ocv:func:`compare` , :ocv:func:`inRange` , :ocv:func:`threshold` , :ocv:func:`adaptiveThreshold` , :ocv:func:`Canny` , and others to create a binary image out of a grayscale or color one. The function modifies the ``image`` while extracting the contours. If mode equals to ``CV_RETR_CCOMP`` or ``CV_RETR_FLOODFILL``, the input can also be a 32-bit integer image of labels (``CV_32SC1``).
|
||||
|
||||
:param contours: Detected contours. Each contour is stored as a vector of points.
|
||||
|
||||
:param hierarchy: Optional output vector, containing information about the image topology. It has as many elements as the number of contours. For each i-th contour ``contours[i]`` , the elements ``hierarchy[i][0]`` , ``hiearchy[i][1]`` , ``hiearchy[i][2]`` , and ``hiearchy[i][3]`` are set to 0-based indices in ``contours`` of the next and previous contours at the same hierarchical level, the first child contour and the parent contour, respectively. If for the contour ``i`` there are no next, previous, parent, or nested contours, the corresponding elements of ``hierarchy[i]`` will be negative.
|
||||
|
||||
:param mode: Contour retrieval mode (if you use Python see also a note below).
|
||||
|
||||
* **CV_RETR_EXTERNAL** retrieves only the extreme outer contours. It sets ``hierarchy[i][2]=hierarchy[i][3]=-1`` for all the contours.
|
||||
|
||||
* **CV_RETR_LIST** retrieves all of the contours without establishing any hierarchical relationships.
|
||||
|
||||
* **CV_RETR_CCOMP** retrieves all of the contours and organizes them into a two-level hierarchy. At the top level, there are external boundaries of the components. At the second level, there are boundaries of the holes. If there is another contour inside a hole of a connected component, it is still put at the top level.
|
||||
|
||||
* **CV_RETR_TREE** retrieves all of the contours and reconstructs a full hierarchy of nested contours. This full hierarchy is built and shown in the OpenCV ``contours.c`` demo.
|
||||
|
||||
:param method: Contour approximation method (if you use Python see also a note below).
|
||||
|
||||
* **CV_CHAIN_APPROX_NONE** stores absolutely all the contour points. That is, any 2 subsequent points ``(x1,y1)`` and ``(x2,y2)`` of the contour will be either horizontal, vertical or diagonal neighbors, that is, ``max(abs(x1-x2),abs(y2-y1))==1``.
|
||||
|
||||
* **CV_CHAIN_APPROX_SIMPLE** compresses horizontal, vertical, and diagonal segments and leaves only their end points. For example, an up-right rectangular contour is encoded with 4 points.
|
||||
|
||||
* **CV_CHAIN_APPROX_TC89_L1,CV_CHAIN_APPROX_TC89_KCOS** applies one of the flavors of the Teh-Chin chain approximation algorithm. See [TehChin89]_ for details.
|
||||
|
||||
:param offset: Optional offset by which every contour point is shifted. This is useful if the contours are extracted from the image ROI and then they should be analyzed in the whole image context.
|
||||
|
||||
The function retrieves contours from the binary image using the algorithm
|
||||
[Suzuki85]_. The contours are a useful tool for shape analysis and object detection and recognition. See ``squares.c`` in the OpenCV sample directory.
|
||||
|
||||
.. note:: Source ``image`` is modified by this function. Also, the function does not take into account 1-pixel border of the image (it's filled with 0's and used for neighbor analysis in the algorithm), therefore the contours touching the image border will be clipped.
|
||||
|
||||
.. note:: If you use the new Python interface then the ``CV_`` prefix has to be omitted in contour retrieval mode and contour approximation method parameters (for example, use ``cv2.RETR_LIST`` and ``cv2.CHAIN_APPROX_NONE`` parameters). If you use the old Python interface then these parameters have the ``CV_`` prefix (for example, use ``cv.CV_RETR_LIST`` and ``cv.CV_CHAIN_APPROX_NONE``).
|
||||
|
||||
.. note::
|
||||
|
||||
* An example using the findContour functionality can be found at opencv_source_code/samples/cpp/contours2.cpp
|
||||
* An example using findContours to clean up a background segmentation result at opencv_source_code/samples/cpp/segment_objects.cpp
|
||||
|
||||
* (Python) An example using the findContour functionality can be found at opencv_source/samples/python2/contours.py
|
||||
* (Python) An example of detecting squares in an image can be found at opencv_source/samples/python2/squares.py
|
||||
|
||||
|
||||
approxPolyDP
|
||||
----------------
|
||||
Approximates a polygonal curve(s) with the specified precision.
|
||||
|
||||
.. ocv:function:: void approxPolyDP( InputArray curve, OutputArray approxCurve, double epsilon, bool closed )
|
||||
|
||||
.. ocv:pyfunction:: cv2.approxPolyDP(curve, epsilon, closed[, approxCurve]) -> approxCurve
|
||||
|
||||
.. ocv:cfunction:: CvSeq* cvApproxPoly( const void* src_seq, int header_size, CvMemStorage* storage, int method, double eps, int recursive=0 )
|
||||
|
||||
:param curve: Input vector of a 2D point stored in:
|
||||
|
||||
* ``std::vector`` or ``Mat`` (C++ interface)
|
||||
|
||||
* ``Nx2`` numpy array (Python interface)
|
||||
|
||||
* ``CvSeq`` or `` ``CvMat`` (C interface)
|
||||
|
||||
:param approxCurve: Result of the approximation. The type should match the type of the input curve. In case of C interface the approximated curve is stored in the memory storage and pointer to it is returned.
|
||||
|
||||
:param epsilon: Parameter specifying the approximation accuracy. This is the maximum distance between the original curve and its approximation.
|
||||
|
||||
:param closed: If true, the approximated curve is closed (its first and last vertices are connected). Otherwise, it is not closed.
|
||||
|
||||
:param header_size: Header size of the approximated curve. Normally, ``sizeof(CvContour)`` is used.
|
||||
|
||||
:param storage: Memory storage where the approximated curve is stored.
|
||||
|
||||
:param method: Contour approximation algorithm. Only ``CV_POLY_APPROX_DP`` is supported.
|
||||
|
||||
:param recursive: Recursion flag. If it is non-zero and ``curve`` is ``CvSeq*``, the function ``cvApproxPoly`` approximates all the contours accessible from ``curve`` by ``h_next`` and ``v_next`` links.
|
||||
|
||||
The functions ``approxPolyDP`` approximate a curve or a polygon with another curve/polygon with less vertices so that the distance between them is less or equal to the specified precision. It uses the Douglas-Peucker algorithm
|
||||
http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm
|
||||
|
||||
See https://github.com/Itseez/opencv/tree/master/samples/cpp/contours2.cpp for the function usage model.
|
||||
|
||||
|
||||
ApproxChains
|
||||
-------------
|
||||
Approximates Freeman chain(s) with a polygonal curve.
|
||||
|
||||
.. ocv:cfunction:: CvSeq* cvApproxChains( CvSeq* src_seq, CvMemStorage* storage, int method=CV_CHAIN_APPROX_SIMPLE, double parameter=0, int minimal_perimeter=0, int recursive=0 )
|
||||
|
||||
:param src_seq: Pointer to the approximated Freeman chain that can refer to other chains.
|
||||
|
||||
:param storage: Storage location for the resulting polylines.
|
||||
|
||||
:param method: Approximation method (see the description of the function :ocv:cfunc:`FindContours` ).
|
||||
|
||||
:param parameter: Method parameter (not used now).
|
||||
|
||||
:param minimal_perimeter: Approximates only those contours whose perimeters are not less than ``minimal_perimeter`` . Other chains are removed from the resulting structure.
|
||||
|
||||
:param recursive: Recursion flag. If it is non-zero, the function approximates all chains that can be obtained from ``chain`` by using the ``h_next`` or ``v_next`` links. Otherwise, the single input chain is approximated.
|
||||
|
||||
This is a standalone contour approximation routine, not represented in the new interface. When :ocv:cfunc:`FindContours` retrieves contours as Freeman chains, it calls the function to get approximated contours, represented as polygons.
|
||||
|
||||
|
||||
arcLength
|
||||
-------------
|
||||
Calculates a contour perimeter or a curve length.
|
||||
|
||||
.. ocv:function:: double arcLength( InputArray curve, bool closed )
|
||||
|
||||
.. ocv:pyfunction:: cv2.arcLength(curve, closed) -> retval
|
||||
|
||||
.. ocv:cfunction:: double cvArcLength( const void* curve, CvSlice slice=CV_WHOLE_SEQ, int is_closed=-1 )
|
||||
|
||||
:param curve: Input vector of 2D points, stored in ``std::vector`` or ``Mat``.
|
||||
|
||||
:param closed: Flag indicating whether the curve is closed or not.
|
||||
|
||||
The function computes a curve length or a closed contour perimeter.
|
||||
|
||||
|
||||
|
||||
boundingRect
|
||||
----------------
|
||||
Calculates the up-right bounding rectangle of a point set.
|
||||
|
||||
.. ocv:function:: Rect boundingRect( InputArray points )
|
||||
|
||||
.. ocv:pyfunction:: cv2.boundingRect(points) -> retval
|
||||
|
||||
.. ocv:cfunction:: CvRect cvBoundingRect( CvArr* points, int update=0 )
|
||||
|
||||
:param points: Input 2D point set, stored in ``std::vector`` or ``Mat``.
|
||||
|
||||
The function calculates and returns the minimal up-right bounding rectangle for the specified point set.
|
||||
|
||||
|
||||
contourArea
|
||||
---------------
|
||||
Calculates a contour area.
|
||||
|
||||
.. ocv:function:: double contourArea( InputArray contour, bool oriented=false )
|
||||
|
||||
.. ocv:pyfunction:: cv2.contourArea(contour[, oriented]) -> retval
|
||||
|
||||
.. ocv:cfunction:: double cvContourArea( const CvArr* contour, CvSlice slice=CV_WHOLE_SEQ, int oriented=0 )
|
||||
|
||||
:param contour: Input vector of 2D points (contour vertices), stored in ``std::vector`` or ``Mat``.
|
||||
|
||||
:param oriented: Oriented area flag. If it is true, the function returns a signed area value, depending on the contour orientation (clockwise or counter-clockwise). Using this feature you can determine orientation of a contour by taking the sign of an area. By default, the parameter is ``false``, which means that the absolute value is returned.
|
||||
|
||||
The function computes a contour area. Similarly to
|
||||
:ocv:func:`moments` , the area is computed using the Green formula. Thus, the returned area and the number of non-zero pixels, if you draw the contour using
|
||||
:ocv:func:`drawContours` or
|
||||
:ocv:func:`fillPoly` , can be different.
|
||||
Also, the function will most certainly give a wrong results for contours with self-intersections.
|
||||
|
||||
Example: ::
|
||||
|
||||
vector<Point> contour;
|
||||
contour.push_back(Point2f(0, 0));
|
||||
contour.push_back(Point2f(10, 0));
|
||||
contour.push_back(Point2f(10, 10));
|
||||
contour.push_back(Point2f(5, 4));
|
||||
|
||||
double area0 = contourArea(contour);
|
||||
vector<Point> approx;
|
||||
approxPolyDP(contour, approx, 5, true);
|
||||
double area1 = contourArea(approx);
|
||||
|
||||
cout << "area0 =" << area0 << endl <<
|
||||
"area1 =" << area1 << endl <<
|
||||
"approx poly vertices" << approx.size() << endl;
|
||||
|
||||
|
||||
|
||||
convexHull
|
||||
--------------
|
||||
Finds the convex hull of a point set.
|
||||
|
||||
.. ocv:function:: void convexHull( InputArray points, OutputArray hull, bool clockwise=false, bool returnPoints=true )
|
||||
|
||||
.. ocv:pyfunction:: cv2.convexHull(points[, hull[, clockwise[, returnPoints]]]) -> hull
|
||||
|
||||
.. ocv:cfunction:: CvSeq* cvConvexHull2( const CvArr* input, void* hull_storage=NULL, int orientation=CV_CLOCKWISE, int return_points=0 )
|
||||
|
||||
:param points: Input 2D point set, stored in ``std::vector`` or ``Mat``.
|
||||
|
||||
:param hull: Output convex hull. It is either an integer vector of indices or vector of points. In the first case, the ``hull`` elements are 0-based indices of the convex hull points in the original array (since the set of convex hull points is a subset of the original point set). In the second case, ``hull`` elements are the convex hull points themselves.
|
||||
|
||||
:param hull_storage: Output memory storage in the old API (``cvConvexHull2`` returns a sequence containing the convex hull points or their indices).
|
||||
|
||||
:param clockwise: Orientation flag. If it is true, the output convex hull is oriented clockwise. Otherwise, it is oriented counter-clockwise. The assumed coordinate system has its X axis pointing to the right, and its Y axis pointing upwards.
|
||||
|
||||
:param orientation: Convex hull orientation parameter in the old API, ``CV_CLOCKWISE`` or ``CV_COUNTERCLOCKWISE``.
|
||||
|
||||
:param returnPoints: Operation flag. In case of a matrix, when the flag is true, the function returns convex hull points. Otherwise, it returns indices of the convex hull points. When the output array is ``std::vector``, the flag is ignored, and the output depends on the type of the vector: ``std::vector<int>`` implies ``returnPoints=true``, ``std::vector<Point>`` implies ``returnPoints=false``.
|
||||
|
||||
The functions find the convex hull of a 2D point set using the Sklansky's algorithm
|
||||
[Sklansky82]_
|
||||
that has
|
||||
*O(N logN)* complexity in the current implementation. See the OpenCV sample ``convexhull.cpp`` that demonstrates the usage of different function variants.
|
||||
|
||||
.. note::
|
||||
|
||||
* An example using the convexHull functionality can be found at opencv_source_code/samples/cpp/convexhull.cpp
|
||||
|
||||
|
||||
convexityDefects
|
||||
----------------
|
||||
Finds the convexity defects of a contour.
|
||||
|
||||
.. ocv:function:: void convexityDefects( InputArray contour, InputArray convexhull, OutputArray convexityDefects )
|
||||
|
||||
.. ocv:pyfunction:: cv2.convexityDefects(contour, convexhull[, convexityDefects]) -> convexityDefects
|
||||
|
||||
.. ocv:cfunction:: CvSeq* cvConvexityDefects( const CvArr* contour, const CvArr* convexhull, CvMemStorage* storage=NULL )
|
||||
|
||||
:param contour: Input contour.
|
||||
|
||||
:param convexhull: Convex hull obtained using :ocv:func:`convexHull` that should contain indices of the contour points that make the hull.
|
||||
|
||||
:param convexityDefects: The output vector of convexity defects. In C++ and the new Python/Java interface each convexity defect is represented as 4-element integer vector (a.k.a. ``cv::Vec4i``): ``(start_index, end_index, farthest_pt_index, fixpt_depth)``, where indices are 0-based indices in the original contour of the convexity defect beginning, end and the farthest point, and ``fixpt_depth`` is fixed-point approximation (with 8 fractional bits) of the distance between the farthest contour point and the hull. That is, to get the floating-point value of the depth will be ``fixpt_depth/256.0``. In C interface convexity defect is represented by ``CvConvexityDefect`` structure - see below.
|
||||
|
||||
:param storage: Container for the output sequence of convexity defects. If it is NULL, the contour or hull (in that order) storage is used.
|
||||
|
||||
The function finds all convexity defects of the input contour and returns a sequence of the ``CvConvexityDefect`` structures, where ``CvConvexityDetect`` is defined as: ::
|
||||
|
||||
struct CvConvexityDefect
|
||||
{
|
||||
CvPoint* start; // point of the contour where the defect begins
|
||||
CvPoint* end; // point of the contour where the defect ends
|
||||
CvPoint* depth_point; // the farthest from the convex hull point within the defect
|
||||
float depth; // distance between the farthest point and the convex hull
|
||||
};
|
||||
|
||||
The figure below displays convexity defects of a hand contour:
|
||||
|
||||
.. image:: pics/defects.png
|
||||
|
||||
fitEllipse
|
||||
--------------
|
||||
Fits an ellipse around a set of 2D points.
|
||||
|
||||
.. ocv:function:: RotatedRect fitEllipse( InputArray points )
|
||||
|
||||
.. ocv:pyfunction:: cv2.fitEllipse(points) -> retval
|
||||
|
||||
.. ocv:cfunction:: CvBox2D cvFitEllipse2( const CvArr* points )
|
||||
|
||||
:param points: Input 2D point set, stored in:
|
||||
|
||||
* ``std::vector<>`` or ``Mat`` (C++ interface)
|
||||
|
||||
* ``CvSeq*`` or ``CvMat*`` (C interface)
|
||||
|
||||
* Nx2 numpy array (Python interface)
|
||||
|
||||
The function calculates the ellipse that fits (in a least-squares sense) a set of 2D points best of all. It returns the rotated rectangle in which the ellipse is inscribed. The algorithm [Fitzgibbon95]_ is used.
|
||||
Developer should keep in mind that it is possible that the returned ellipse/rotatedRect data contains negative indices, due to the data points being close to the border of the containing Mat element.
|
||||
|
||||
.. note::
|
||||
|
||||
* An example using the fitEllipse technique can be found at opencv_source_code/samples/cpp/fitellipse.cpp
|
||||
|
||||
|
||||
fitLine
|
||||
-----------
|
||||
Fits a line to a 2D or 3D point set.
|
||||
|
||||
.. ocv:function:: void fitLine( InputArray points, OutputArray line, int distType, double param, double reps, double aeps )
|
||||
|
||||
.. ocv:pyfunction:: cv2.fitLine(points, distType, param, reps, aeps[, line]) -> line
|
||||
|
||||
.. ocv:cfunction:: void cvFitLine( const CvArr* points, int dist_type, double param, double reps, double aeps, float* line )
|
||||
|
||||
:param points: Input vector of 2D or 3D points, stored in ``std::vector<>`` or ``Mat``.
|
||||
|
||||
:param line: Output line parameters. In case of 2D fitting, it should be a vector of 4 elements (like ``Vec4f``) - ``(vx, vy, x0, y0)``, where ``(vx, vy)`` is a normalized vector collinear to the line and ``(x0, y0)`` is a point on the line. In case of 3D fitting, it should be a vector of 6 elements (like ``Vec6f``) - ``(vx, vy, vz, x0, y0, z0)``, where ``(vx, vy, vz)`` is a normalized vector collinear to the line and ``(x0, y0, z0)`` is a point on the line.
|
||||
|
||||
:param distType: Distance used by the M-estimator (see the discussion below).
|
||||
|
||||
:param param: Numerical parameter ( ``C`` ) for some types of distances. If it is 0, an optimal value is chosen.
|
||||
|
||||
:param reps: Sufficient accuracy for the radius (distance between the coordinate origin and the line).
|
||||
|
||||
:param aeps: Sufficient accuracy for the angle. 0.01 would be a good default value for ``reps`` and ``aeps``.
|
||||
|
||||
The function ``fitLine`` fits a line to a 2D or 3D point set by minimizing
|
||||
:math:`\sum_i \rho(r_i)` where
|
||||
:math:`r_i` is a distance between the
|
||||
:math:`i^{th}` point, the line and
|
||||
:math:`\rho(r)` is a distance function, one of the following:
|
||||
|
||||
* distType=CV\_DIST\_L2
|
||||
|
||||
.. math::
|
||||
|
||||
\rho (r) = r^2/2 \quad \text{(the simplest and the fastest least-squares method)}
|
||||
|
||||
* distType=CV\_DIST\_L1
|
||||
|
||||
.. math::
|
||||
|
||||
\rho (r) = r
|
||||
|
||||
* distType=CV\_DIST\_L12
|
||||
|
||||
.. math::
|
||||
|
||||
\rho (r) = 2 \cdot ( \sqrt{1 + \frac{r^2}{2}} - 1)
|
||||
|
||||
* distType=CV\_DIST\_FAIR
|
||||
|
||||
.. math::
|
||||
|
||||
\rho \left (r \right ) = C^2 \cdot \left ( \frac{r}{C} - \log{\left(1 + \frac{r}{C}\right)} \right ) \quad \text{where} \quad C=1.3998
|
||||
|
||||
* distType=CV\_DIST\_WELSCH
|
||||
|
||||
.. math::
|
||||
|
||||
\rho \left (r \right ) = \frac{C^2}{2} \cdot \left ( 1 - \exp{\left(-\left(\frac{r}{C}\right)^2\right)} \right ) \quad \text{where} \quad C=2.9846
|
||||
|
||||
* distType=CV\_DIST\_HUBER
|
||||
|
||||
.. math::
|
||||
|
||||
\rho (r) = \fork{r^2/2}{if $r < C$}{C \cdot (r-C/2)}{otherwise} \quad \text{where} \quad C=1.345
|
||||
|
||||
The algorithm is based on the M-estimator (
|
||||
http://en.wikipedia.org/wiki/M-estimator
|
||||
) technique that iteratively fits the line using the weighted least-squares algorithm. After each iteration the weights
|
||||
:math:`w_i` are adjusted to be inversely proportional to
|
||||
:math:`\rho(r_i)` .
|
||||
|
||||
.. Sample code:
|
||||
|
||||
* (Python) An example of robust line fitting can be found at opencv_source_code/samples/python2/fitline.py
|
||||
|
||||
|
||||
isContourConvex
|
||||
-------------------
|
||||
Tests a contour convexity.
|
||||
|
||||
.. ocv:function:: bool isContourConvex( InputArray contour )
|
||||
|
||||
.. ocv:pyfunction:: cv2.isContourConvex(contour) -> retval
|
||||
|
||||
.. ocv:cfunction:: int cvCheckContourConvexity( const CvArr* contour )
|
||||
|
||||
:param contour: Input vector of 2D points, stored in:
|
||||
|
||||
* ``std::vector<>`` or ``Mat`` (C++ interface)
|
||||
|
||||
* ``CvSeq*`` or ``CvMat*`` (C interface)
|
||||
|
||||
* Nx2 numpy array (Python interface)
|
||||
|
||||
The function tests whether the input contour is convex or not. The contour must be simple, that is, without self-intersections. Otherwise, the function output is undefined.
|
||||
|
||||
|
||||
|
||||
minAreaRect
|
||||
---------------
|
||||
Finds a rotated rectangle of the minimum area enclosing the input 2D point set.
|
||||
|
||||
.. ocv:function:: RotatedRect minAreaRect( InputArray points )
|
||||
|
||||
.. ocv:pyfunction:: cv2.minAreaRect(points) -> retval
|
||||
|
||||
.. ocv:cfunction:: CvBox2D cvMinAreaRect2( const CvArr* points, CvMemStorage* storage=NULL )
|
||||
|
||||
:param points: Input vector of 2D points, stored in:
|
||||
|
||||
* ``std::vector<>`` or ``Mat`` (C++ interface)
|
||||
|
||||
* ``CvSeq*`` or ``CvMat*`` (C interface)
|
||||
|
||||
* Nx2 numpy array (Python interface)
|
||||
|
||||
The function calculates and returns the minimum-area bounding rectangle (possibly rotated) for a specified point set. See the OpenCV sample ``minarea.cpp`` .
|
||||
Developer should keep in mind that the returned rotatedRect can contain negative indices when data is close the the containing Mat element boundary.
|
||||
|
||||
|
||||
boxPoints
|
||||
-----------
|
||||
Finds the four vertices of a rotated rect. Useful to draw the rotated rectangle.
|
||||
|
||||
.. ocv:function:: void boxPoints(RotatedRect box, OutputArray points)
|
||||
|
||||
.. ocv:pyfunction:: cv2.boxPoints(box[, points]) -> points
|
||||
|
||||
.. ocv:cfunction:: void cvBoxPoints( CvBox2D box, CvPoint2D32f pt[4] )
|
||||
|
||||
:param box: The input rotated rectangle. It may be the output of .. ocv:function:: minAreaRect.
|
||||
|
||||
:param points: The output array of four vertices of rectangles.
|
||||
|
||||
The function finds the four vertices of a rotated rectangle. This function is useful to draw the rectangle. In C++, instead of using this function, you can directly use box.points() method. Please visit the `tutorial on bounding rectangle <http://docs.opencv.org/doc/tutorials/imgproc/shapedescriptors/bounding_rects_circles/bounding_rects_circles.html#bounding-rects-circles>`_ for more information.
|
||||
|
||||
|
||||
|
||||
minEnclosingTriangle
|
||||
----------------------
|
||||
Finds a triangle of minimum area enclosing a 2D point set and returns its area.
|
||||
|
||||
.. ocv:function:: double minEnclosingTriangle( InputArray points, OutputArray triangle )
|
||||
|
||||
.. ocv:pyfunction:: cv2.minEnclosingTriangle(points[, triangle]) -> retval, triangle
|
||||
|
||||
:param points: Input vector of 2D points with depth ``CV_32S`` or ``CV_32F``, stored in:
|
||||
|
||||
* ``std::vector<>`` or ``Mat`` (C++ interface)
|
||||
|
||||
* Nx2 numpy array (Python interface)
|
||||
|
||||
:param triangle: Output vector of three 2D points defining the vertices of the triangle. The depth of the OutputArray must be ``CV_32F``.
|
||||
|
||||
The function finds a triangle of minimum area enclosing the given set of 2D points and returns its area. The output for a given 2D point set is shown in the image below. 2D points are depicted in *red* and the enclosing triangle in *yellow*.
|
||||
|
||||
.. image:: pics/minenclosingtriangle.png
|
||||
:height: 250px
|
||||
:width: 250px
|
||||
:alt: Sample output of the minimum enclosing triangle function
|
||||
|
||||
The implementation of the algorithm is based on O'Rourke's [ORourke86]_ and Klee and Laskowski's [KleeLaskowski85]_ papers. O'Rourke provides a
|
||||
:math:`\theta(n)`
|
||||
algorithm for finding the minimal enclosing triangle of a 2D convex polygon with ``n`` vertices. Since the :ocv:func:`minEnclosingTriangle` function takes a 2D point set as input an additional preprocessing step of computing the convex hull of the 2D point set is required. The complexity of the :ocv:func:`convexHull` function is
|
||||
:math:`O(n log(n))` which is higher than
|
||||
:math:`\theta(n)`.
|
||||
Thus the overall complexity of the function is
|
||||
:math:`O(n log(n))`.
|
||||
|
||||
.. note:: See ``opencv_source/samples/cpp/minarea.cpp`` for a usage example.
|
||||
|
||||
|
||||
|
||||
minEnclosingCircle
|
||||
----------------------
|
||||
Finds a circle of the minimum area enclosing a 2D point set.
|
||||
|
||||
.. ocv:function:: void minEnclosingCircle( InputArray points, Point2f& center, float& radius )
|
||||
|
||||
.. ocv:pyfunction:: cv2.minEnclosingCircle(points) -> center, radius
|
||||
|
||||
.. ocv:cfunction:: int cvMinEnclosingCircle( const CvArr* points, CvPoint2D32f* center, float* radius )
|
||||
|
||||
:param points: Input vector of 2D points, stored in:
|
||||
|
||||
* ``std::vector<>`` or ``Mat`` (C++ interface)
|
||||
|
||||
* ``CvSeq*`` or ``CvMat*`` (C interface)
|
||||
|
||||
* Nx2 numpy array (Python interface)
|
||||
|
||||
:param center: Output center of the circle.
|
||||
|
||||
:param radius: Output radius of the circle.
|
||||
|
||||
The function finds the minimal enclosing circle of a 2D point set using an iterative algorithm. See the OpenCV sample ``minarea.cpp`` .
|
||||
|
||||
|
||||
|
||||
matchShapes
|
||||
---------------
|
||||
Compares two shapes.
|
||||
|
||||
.. ocv:function:: double matchShapes( InputArray contour1, InputArray contour2, int method, double parameter )
|
||||
|
||||
.. ocv:pyfunction:: cv2.matchShapes(contour1, contour2, method, parameter) -> retval
|
||||
|
||||
.. ocv:cfunction:: double cvMatchShapes( const void* object1, const void* object2, int method, double parameter=0 )
|
||||
|
||||
:param object1: First contour or grayscale image.
|
||||
|
||||
:param object2: Second contour or grayscale image.
|
||||
|
||||
:param method: Comparison method: ``CV_CONTOURS_MATCH_I1`` , \ ``CV_CONTOURS_MATCH_I2`` \
|
||||
or ``CV_CONTOURS_MATCH_I3`` (see the details below).
|
||||
|
||||
:param parameter: Method-specific parameter (not supported now).
|
||||
|
||||
The function compares two shapes. All three implemented methods use the Hu invariants (see
|
||||
:ocv:func:`HuMoments` ) as follows (
|
||||
:math:`A` denotes ``object1``,:math:`B` denotes ``object2`` ):
|
||||
|
||||
* method=CV_CONTOURS_MATCH_I1
|
||||
|
||||
.. math::
|
||||
|
||||
I_1(A,B) = \sum _{i=1...7} \left | \frac{1}{m^A_i} - \frac{1}{m^B_i} \right |
|
||||
|
||||
* method=CV_CONTOURS_MATCH_I2
|
||||
|
||||
.. math::
|
||||
|
||||
I_2(A,B) = \sum _{i=1...7} \left | m^A_i - m^B_i \right |
|
||||
|
||||
* method=CV_CONTOURS_MATCH_I3
|
||||
|
||||
.. math::
|
||||
|
||||
I_3(A,B) = \max _{i=1...7} \frac{ \left| m^A_i - m^B_i \right| }{ \left| m^A_i \right| }
|
||||
|
||||
where
|
||||
|
||||
.. math::
|
||||
|
||||
\begin{array}{l} m^A_i = \mathrm{sign} (h^A_i) \cdot \log{h^A_i} \\ m^B_i = \mathrm{sign} (h^B_i) \cdot \log{h^B_i} \end{array}
|
||||
|
||||
and
|
||||
:math:`h^A_i, h^B_i` are the Hu moments of
|
||||
:math:`A` and
|
||||
:math:`B` , respectively.
|
||||
|
||||
|
||||
|
||||
pointPolygonTest
|
||||
--------------------
|
||||
Performs a point-in-contour test.
|
||||
|
||||
.. ocv:function:: double pointPolygonTest( InputArray contour, Point2f pt, bool measureDist )
|
||||
|
||||
.. ocv:pyfunction:: cv2.pointPolygonTest(contour, pt, measureDist) -> retval
|
||||
|
||||
.. ocv:cfunction:: double cvPointPolygonTest( const CvArr* contour, CvPoint2D32f pt, int measure_dist )
|
||||
|
||||
:param contour: Input contour.
|
||||
|
||||
:param pt: Point tested against the contour.
|
||||
|
||||
:param measureDist: If true, the function estimates the signed distance from the point to the nearest contour edge. Otherwise, the function only checks if the point is inside a contour or not.
|
||||
|
||||
The function determines whether the
|
||||
point is inside a contour, outside, or lies on an edge (or coincides
|
||||
with a vertex). It returns positive (inside), negative (outside), or zero (on an edge) value,
|
||||
correspondingly. When ``measureDist=false`` , the return value
|
||||
is +1, -1, and 0, respectively. Otherwise, the return value
|
||||
is a signed distance between the point and the nearest contour
|
||||
edge.
|
||||
|
||||
See below a sample output of the function where each image pixel is tested against the contour.
|
||||
|
||||
.. image:: pics/pointpolygon.png
|
||||
|
||||
.. [Fitzgibbon95] Andrew W. Fitzgibbon, R.B.Fisher. *A Buyer's Guide to Conic Fitting*. Proc.5th British Machine Vision Conference, Birmingham, pp. 513-522, 1995.
|
||||
|
||||
.. [Hu62] M. Hu. *Visual Pattern Recognition by Moment Invariants*, IRE Transactions on Information Theory, 8:2, pp. 179-187, 1962.
|
||||
|
||||
.. [KleeLaskowski85] Klee, V. and Laskowski, M.C., *Finding the smallest triangles containing a given convex polygon*, Journal of Algorithms, vol. 6, no. 3, pp. 359-375 (1985)
|
||||
|
||||
.. [ORourke86] O’Rourke, J., Aggarwal, A., Maddila, S., and Baldwin, M., *An optimal algorithm for finding minimal enclosing triangles*, Journal of Algorithms, vol. 7, no. 2, pp. 258-269 (1986)
|
||||
|
||||
.. [Sklansky82] Sklansky, J., *Finding the Convex Hull of a Simple Polygon*. PRL 1 $number, pp 79-83 (1982)
|
||||
|
||||
.. [Suzuki85] Suzuki, S. and Abe, K., *Topological Structural Analysis of Digitized Binary Images by Border Following*. CVGIP 30 1, pp 32-46 (1985)
|
||||
|
||||
.. [TehChin89] Teh, C.H. and Chin, R.T., *On the Detection of Dominant Points on Digital Curve*. PAMI 11 8, pp 859-872 (1989)
|
||||
|
||||
|
||||
|
||||
rotatedRectangleIntersection
|
||||
-------------------------------
|
||||
Finds out if there is any intersection between two rotated rectangles. If there is then the vertices of the interesecting region are returned as well.
|
||||
|
||||
.. ocv:function:: int rotatedRectangleIntersection( const RotatedRect& rect1, const RotatedRect& rect2, OutputArray intersectingRegion )
|
||||
.. ocv:pyfunction:: cv2.rotatedRectangleIntersection( rect1, rect2 ) -> retval, intersectingRegion
|
||||
|
||||
:param rect1: First rectangle
|
||||
|
||||
:param rect2: Second rectangle
|
||||
|
||||
:param intersectingRegion: The output array of the verticies of the intersecting region. It returns at most 8 vertices. Stored as ``std::vector<cv::Point2f>`` or ``cv::Mat`` as Mx1 of type CV_32FC2.
|
||||
|
||||
:param pointCount: The number of vertices.
|
||||
|
||||
The following values are returned by the function:
|
||||
|
||||
* INTERSECT_NONE=0 - No intersection
|
||||
|
||||
* INTERSECT_PARTIAL=1 - There is a partial intersection
|
||||
|
||||
* INTERSECT_FULL=2 - One of the rectangle is fully enclosed in the other
|
||||
|
||||
Below are some examples of intersection configurations. The hatched pattern indicates the intersecting region and the red vertices are returned by the function.
|
||||
|
||||
.. image:: pics/intersection.png
|
||||
Reference in New Issue
Block a user