posted by 심재형 2017. 11. 15. 13:43

matchShapes

Compares two shapes.

C++: double matchShapes(InputArray contour1, InputArray contour2, int method, double parameter)
Python: cv2.matchShapes(contour1, contour2, method, parameter) → retval
C: double cvMatchShapes(const void* object1, const void* object2, int method, double parameter=0 )
Python: cv.MatchShapes(object1, object2, method, parameter=0) → float
Parameters:
  • object1 – First contour or grayscale image.
  • object2 – Second contour or grayscale image.
  • method – Comparison method: CV_CONTOURS_MATCH_I1 , CV_CONTOURS_MATCH_I2 or CV_CONTOURS_MATCH_I3 (see the details below).
  • parameter – Method-specific parameter (not supported now).

The function compares two shapes. All three implemented methods use the Hu invariants (see HuMoments() ) as follows ( A denotes object1,:math:B denotes object2 ):

  • method=CV_CONTOURS_MATCH_I1

    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

    I_2(A,B) =  \sum _{i=1...7}  \left | m^A_i - m^B_i  \right |

  • method=CV_CONTOURS_MATCH_I3

    I_3(A,B) =  \max _{i=1...7}  \frac{ \left| m^A_i - m^B_i \right| }{ \left| m^A_i \right| }

where

\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 h^A_i, h^B_i are the Hu moments of A and B , respectively.

posted by 심재형 2017. 11. 15. 13:42

minAreaRect

Finds a rotated rectangle of the minimum area enclosing the input 2D point set.

C++: RotatedRect minAreaRect(InputArray points)
Python: cv2.minAreaRect(points) → retval
C: CvBox2D cvMinAreaRect2(const CvArr* points, CvMemStorage* storage=NULL )
Python: cv.MinAreaRect2(points, storage=None) → Box2D
Parameters: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.

posted by 심재형 2017. 11. 15. 13:15

minEnclosingCircle

Finds a circle of the minimum area enclosing a 2D point set.

C++: void minEnclosingCircle(InputArray points, Point2f& center, float& radius)
Python: cv2.minEnclosingCircle(points) → center, radius
C: int cvMinEnclosingCircle(const CvArr* points, CvPoint2D32f* center, float* radius)
Python: cv.MinEnclosingCircle(points)-> (int, center, radius)
Parameters:
  • points –

    Input vector of 2D points, stored in:

    • std::vector<> or Mat (C++ interface)
    • CvSeq* or CvMat* (C interface)
    • Nx2 numpy array (Python interface)
  • center – Output center of the circle.
  • 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 .

'OpenCV' 카테고리의 다른 글

matchShapes  (0) 2017.11.15
내부 최소사각형 - minAreaRect  (0) 2017.11.15
적당한 선으로 채우기 fitLine  (0) 2017.11.15
구멍 채우기 - fitEllipse  (0) 2017.11.15
형태 볼록함 결점찾기, 구멍찾기 - convexityDefects  (0) 2017.11.15
posted by 심재형 2017. 11. 15. 13:15

fitLine

Fits a line to a 2D or 3D point set.

C++: void fitLine(InputArray points, OutputArray line, int distType, double param, double reps, double aeps)
Python: cv2.fitLine(points, distType, param, reps, aeps[, line]) → line
C: void cvFitLine(const CvArr* points, int dist_type, double param, double reps, double aeps, float* line)
Python: cv.FitLine(points, dist_type, param, reps, aeps) → line
Parameters:
  • points – Input vector of 2D or 3D points, stored in std::vector<> or Mat.
  • 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.
  • distType – Distance used by the M-estimator (see the discussion below).
  • param – Numerical parameter ( C ) for some types of distances. If it is 0, an optimal value is chosen.
  • reps – Sufficient accuracy for the radius (distance between the coordinate origin and the line).
  • 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 \sum_i \rho(r_i) where r_i is a distance between the i^{th} point, the line and \rho(r) is a distance function, one of the following:

  • distType=CV_DIST_L2

    \rho (r) = r^2/2  \quad \text{(the simplest and the fastest least-squares method)}

  • distType=CV_DIST_L1

    \rho (r) = r

  • distType=CV_DIST_L12

    \rho (r) = 2  \cdot ( \sqrt{1 + \frac{r^2}{2}} - 1)

  • distType=CV_DIST_FAIR

    \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

    \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

    \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 w_i are adjusted to be inversely proportional to \rho(r_i)

posted by 심재형 2017. 11. 15. 13:14

fitEllipse

Fits an ellipse around a set of 2D points.

C++: RotatedRect fitEllipse(InputArray points)
Python: cv2.fitEllipse(points) → retval
C: CvBox2D cvFitEllipse2(const CvArr* points)
Python: cv.FitEllipse2(points) → Box2D
Parameters: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


posted by 심재형 2017. 11. 15. 13:14

convexityDefects

Finds the convexity defects of a contour.

C++: void convexityDefects(InputArray contour, InputArray convexhull, OutputArray convexityDefects)
Python: cv2.convexityDefects(contour, convexhull[, convexityDefects]) → convexityDefects
C: CvSeq* cvConvexityDefects(const CvArr* contour, const CvArr* convexhull, CvMemStorage* storage=NULL )
Python: cv.ConvexityDefects(contour, convexhull, storage) → convexityDefects
Parameters:
  • contour – Input contour.
  • convexhull – Convex hull obtained using convexHull() that should contain indices of the contour points that make the hull.
  • 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 CvConvexityDefectstructure - see below.
  • 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:

../../../_images/defects.png

'OpenCV' 카테고리의 다른 글

적당한 선으로 채우기 fitLine  (0) 2017.11.15
구멍 채우기 - fitEllipse  (0) 2017.11.15
형태 넓이 구하기 - contourArea  (0) 2017.11.15
윤곽선 그리기 - DrawContours  (0) 2017.11.15
윤곽선 정보 찾기 - findContours  (0) 2017.11.15
posted by 심재형 2017. 11. 15. 13:11

contourArea

Calculates a contour area.

C++: double contourArea(InputArray contour, bool oriented=false )
Python: cv2.contourArea(contour[, oriented]) → retval
C: double cvContourArea(const CvArr* contour, CvSlice slice=CV_WHOLE_SEQ, int oriented=0 )
Python: cv.ContourArea(contour, slice=CV_WHOLE_SEQ) → float
Parameters:
  • contour – Input vector of 2D points (contour vertices), stored in std::vector or Mat.
  • 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 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 drawContours() or 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.

C++: void convexHull(InputArray points, OutputArray hull, bool clockwise=false, bool returnPoints=true )
Python: cv2.convexHull(points[, hull[, clockwise[, returnPoints]]]) → hull
C: CvSeq* cvConvexHull2(const CvArr* input, void* hull_storage=NULL, int orientation=CV_CLOCKWISE, int return_points=0 )
Python: cv.ConvexHull2(points, storage, orientation=CV_CLOCKWISE, return_points=0) → convexHull
Parameters:
  • points – Input 2D point set, stored in std::vector or Mat.
  • 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.
  • hull_storage – Output memory storage in the old API (cvConvexHull2 returns a sequence containing the convex hull points or their indices).
  • 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.
  • orientation – Convex hull orientation parameter in the old API, CV_CLOCKWISE or CV_COUNTERCLOCKWISE.
  • 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=truestd::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


'OpenCV' 카테고리의 다른 글

구멍 채우기 - fitEllipse  (0) 2017.11.15
형태 볼록함 결점찾기, 구멍찾기 - convexityDefects  (0) 2017.11.15
윤곽선 그리기 - DrawContours  (0) 2017.11.15
윤곽선 정보 찾기 - findContours  (0) 2017.11.15
ROI설정  (0) 2017.11.11
posted by 심재형 2017. 11. 15. 13:10

drawContours

Draws contours outlines or filled contours.

C++: void drawContours(InputOutputArray image, InputArrayOfArrays contours, int contourIdx, const Scalar& color, int thickness=1, int lineType=8, InputArray hierarchy=noArray(), int maxLevel=INT_MAX, Point offset=Point() )
Python: cv2.drawContours(image, contours, contourIdx, color[, thickness[, lineType[, hierarchy[, maxLevel[, offset]]]]]) → None
C: void cvDrawContours(CvArr* img, CvSeq* contour, CvScalar externalColor, CvScalar holeColor, int maxLevel, int thickness=1, int lineType=8 )
Python: cv.DrawContours(img, contour, external_color, hole_color, max_level, thickness=1, lineType=8, offset=(0, 0)) → None
Parameters:
  • image – Destination image.
  • contours – All the input contours. Each contour is stored as a point vector.
  • contourIdx – Parameter indicating a contour to draw. If it is negative, all the contours are drawn.
  • color – Color of the contours.
  • thickness – Thickness of lines the contours are drawn with. If it is negative (for example, thickness=CV_FILLED ), the contour interiors are drawn.
  • lineType – Line connectivity. See line() for details.
  • hierarchy – Optional information about hierarchy. It is only needed if you want to draw only some of the contours (see maxLevel ).
  • 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.
  • offset – Optional contour shift parameter. Shift all the drawn contours by the specified \texttt{offset}=(dx,dy).
  • contour – Pointer to the first contour.
  • externalColor – Color of external contours.
  • holeColor – Color of internal contours (holes).

The function draws contour outlines in the image if \texttt{thickness} \ge 0 or fills the area bounded by the contours if \texttt{thickness}<0. The example below shows how to retrieve connected components from the binary image and label them:

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

using namespace cv;

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,
        CV_RETR_CCOMP, CV_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, CV_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


'OpenCV' 카테고리의 다른 글

형태 볼록함 결점찾기, 구멍찾기 - convexityDefects  (0) 2017.11.15
형태 넓이 구하기 - contourArea  (0) 2017.11.15
윤곽선 정보 찾기 - findContours  (0) 2017.11.15
ROI설정  (0) 2017.11.11
블러함수들  (0) 2017.11.11
posted by 심재형 2017. 11. 15. 13:10

findContours

Finds contours in a binary image.

C++: void findContours(InputOutputArray image, OutputArrayOfArrays contours, OutputArray hierarchy, int mode, int method, Point offset=Point())
C++: void findContours(InputOutputArray image, OutputArrayOfArrays contours, int mode, int method, Point offset=Point())
Python: cv2.findContours(image, mode, method[, contours[, hierarchy[, offset]]]) → contours, hierarchy
C: 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) )
Python: cv.FindContours(image, storage, mode=CV_RETR_LIST, method=CV_CHAIN_APPROX_SIMPLE, offset=(0, 0)) → contours
Parameters:
  • 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 compare() , inRange() , threshold() , adaptiveThreshold() , 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).
  • contours – Detected contours. Each contour is stored as a vector of points.
  • 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 ofhierarchy[i] will be negative.
  • 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.
  • 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.
  • 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


'OpenCV' 카테고리의 다른 글

형태 넓이 구하기 - contourArea  (0) 2017.11.15
윤곽선 그리기 - DrawContours  (0) 2017.11.15
ROI설정  (0) 2017.11.11
블러함수들  (0) 2017.11.11
merge, split 함수  (0) 2017.11.11
posted by 심재형 2017. 11. 11. 00:35

#include "opencv.hpp"

using namespace cv;

using namespace std;

int main()

{

Mat A(10, 10, CV_32F);

for (int i = 0; i < A.rows; i++)

for (int j = 0; j < A.cols; j++)

A.at<float>(i, j) = (float)(i*A.cols + j);

cout << "A=" << A.size() << "=" << A << endl;


Mat B = A(Range(5, 8), Range(3, 6));

cout << "B=" << B.size() << "=" << B << endl;


Size wholeSize; Point ofs;

B.locateROI(wholeSize, ofs);

cout << "wholeSize=" << wholeSize << "ofs=" << ofs << endl;


Mat C = B.adjustROI(1, 1, 1, 1);

cout << "B=" << B.size() << "B=" << B << endl;

cout << "C=" << C.size() << "C=" << C << endl;

return 0;

}


#include <opencv\cv.h>

#include <opencv\highgui.h>


using namespace cv;

using namespace std;


int main(){


// 이미지 불러오기 (read image).

Mat image = imread("image.jpg");


// 에러 처리 (error).

if ( !image.data ) {

return -1;

}


// 관심영역 설정 (set ROI (X, Y, W, H)).

Rect rect(100, 30, 150, 300);


// 관심영역 자르기 (Crop ROI).

Mat subImage = image(rect);


// show

imshow("image", subImage);


waitKey(0);


return 0;

}



#다른방법


#include "opencv.hpp"

using namespace cv;

using namespace std;

int main()

{

Mat_<uchar> A(10, 10);

for (int i = 0; i < A.rows; i++)

for (int j = 0; j < A.cols; j++)

A(i, j) = (uchar)(i*A.cols + j);

cout << "A = " << A << endl;


Mat_<uchar> B = A(Range(5, 8), Range(3, 6));

cout << "B = " << B << endl;


Mat_<uchar> C = B.adjustROI(1, 1, 1, 1);

cout << "B = " << B << endl;

cout << "C = " << C << endl;


Mat D = A(Rect(0, 0, 5, 5));

cout << "D = " << D << endl;


Range ranges[2] = { Range(5, 8), Range(3, 6) };

Mat E = A(ranges);

cout << "E = " << E << endl;

return 0;

}

'OpenCV' 카테고리의 다른 글

윤곽선 그리기 - DrawContours  (0) 2017.11.15
윤곽선 정보 찾기 - findContours  (0) 2017.11.15
블러함수들  (0) 2017.11.11
merge, split 함수  (0) 2017.11.11
inrange 이진화 영상  (0) 2017.11.11