public class Imgproc
extends java.lang.Object
| Constructor and Description |
|---|
Imgproc() |
| Modifier and Type | Method and Description |
|---|---|
static void |
accumulate(Mat src,
Mat dst)
Adds an image to the accumulator.
|
static void |
accumulate(Mat src,
Mat dst,
Mat mask)
Adds an image to the accumulator.
|
static void |
accumulateProduct(Mat src1,
Mat src2,
Mat dst)
Adds the per-element product of two input images to the accumulator.
|
static void |
accumulateProduct(Mat src1,
Mat src2,
Mat dst,
Mat mask)
Adds the per-element product of two input images to the accumulator.
|
static void |
accumulateSquare(Mat src,
Mat dst)
Adds the square of a source image to the accumulator.
|
static void |
accumulateSquare(Mat src,
Mat dst,
Mat mask)
Adds the square of a source image to the accumulator.
|
static void |
accumulateWeighted(Mat src,
Mat dst,
double alpha)
Updates a running average.
|
static void |
accumulateWeighted(Mat src,
Mat dst,
double alpha,
Mat mask)
Updates a running average.
|
static void |
adaptiveBilateralFilter(Mat src,
Mat dst,
Size ksize,
double sigmaSpace)
Applies the adaptive bilateral filter to an image.
|
static void |
adaptiveBilateralFilter(Mat src,
Mat dst,
Size ksize,
double sigmaSpace,
double maxSigmaColor,
Point anchor)
Applies the adaptive bilateral filter to an image.
|
static void |
adaptiveBilateralFilter(Mat src,
Mat dst,
Size ksize,
double sigmaSpace,
double maxSigmaColor,
Point anchor,
int borderType)
Applies the adaptive bilateral filter to an image.
|
static void |
adaptiveThreshold(Mat src,
Mat dst,
double maxValue,
int adaptiveMethod,
int thresholdType,
int blockSize,
double C)
Applies an adaptive threshold to an array.
|
static void |
approxPolyDP(MatOfPoint2f curve,
MatOfPoint2f approxCurve,
double epsilon,
boolean closed)
Approximates a polygonal curve(s) with the specified precision.
|
static double |
arcLength(MatOfPoint2f curve,
boolean closed)
Calculates a contour perimeter or a curve length.
|
static void |
bilateralFilter(Mat src,
Mat dst,
int d,
double sigmaColor,
double sigmaSpace)
Applies the bilateral filter to an image.
|
static void |
bilateralFilter(Mat src,
Mat dst,
int d,
double sigmaColor,
double sigmaSpace,
int borderType)
Applies the bilateral filter to an image.
|
static void |
blur(Mat src,
Mat dst,
Size ksize)
Blurs an image using the normalized box filter.
|
static void |
blur(Mat src,
Mat dst,
Size ksize,
Point anchor)
Blurs an image using the normalized box filter.
|
static void |
blur(Mat src,
Mat dst,
Size ksize,
Point anchor,
int borderType)
Blurs an image using the normalized box filter.
|
static int |
borderInterpolate(int p,
int len,
int borderType)
Computes the source location of an extrapolated pixel.
|
static Rect |
boundingRect(MatOfPoint points)
Calculates the up-right bounding rectangle of a point set.
|
static void |
boxFilter(Mat src,
Mat dst,
int ddepth,
Size ksize)
Blurs an image using the box filter.
|
static void |
boxFilter(Mat src,
Mat dst,
int ddepth,
Size ksize,
Point anchor,
boolean normalize)
Blurs an image using the box filter.
|
static void |
boxFilter(Mat src,
Mat dst,
int ddepth,
Size ksize,
Point anchor,
boolean normalize,
int borderType)
Blurs an image using the box filter.
|
static void |
calcBackProject(java.util.List<Mat> images,
MatOfInt channels,
Mat hist,
Mat dst,
MatOfFloat ranges,
double scale)
Calculates the back projection of a histogram.
|
static void |
calcHist(java.util.List<Mat> images,
MatOfInt channels,
Mat mask,
Mat hist,
MatOfInt histSize,
MatOfFloat ranges)
Calculates a histogram of a set of arrays.
|
static void |
calcHist(java.util.List<Mat> images,
MatOfInt channels,
Mat mask,
Mat hist,
MatOfInt histSize,
MatOfFloat ranges,
boolean accumulate)
Calculates a histogram of a set of arrays.
|
static void |
Canny(Mat image,
Mat edges,
double threshold1,
double threshold2)
Finds edges in an image using the [Canny86] algorithm.
|
static void |
Canny(Mat image,
Mat edges,
double threshold1,
double threshold2,
int apertureSize,
boolean L2gradient)
Finds edges in an image using the [Canny86] algorithm.
|
static double |
compareHist(Mat H1,
Mat H2,
int method)
Compares two histograms.
|
static double |
contourArea(Mat contour)
Calculates a contour area.
|
static double |
contourArea(Mat contour,
boolean oriented)
Calculates a contour area.
|
static void |
convertMaps(Mat map1,
Mat map2,
Mat dstmap1,
Mat dstmap2,
int dstmap1type)
Converts image transformation maps from one representation to another.
|
static void |
convertMaps(Mat map1,
Mat map2,
Mat dstmap1,
Mat dstmap2,
int dstmap1type,
boolean nninterpolation)
Converts image transformation maps from one representation to another.
|
static void |
convexHull(MatOfPoint points,
MatOfInt hull)
Finds the convex hull of a point set.
|
static void |
convexHull(MatOfPoint points,
MatOfInt hull,
boolean clockwise)
Finds the convex hull of a point set.
|
static void |
convexityDefects(MatOfPoint contour,
MatOfInt convexhull,
MatOfInt4 convexityDefects)
Finds the convexity defects of a contour.
|
static void |
copyMakeBorder(Mat src,
Mat dst,
int top,
int bottom,
int left,
int right,
int borderType)
Forms a border around an image.
|
static void |
copyMakeBorder(Mat src,
Mat dst,
int top,
int bottom,
int left,
int right,
int borderType,
Scalar value)
Forms a border around an image.
|
static void |
cornerEigenValsAndVecs(Mat src,
Mat dst,
int blockSize,
int ksize)
Calculates eigenvalues and eigenvectors of image blocks for corner detection.
|
static void |
cornerEigenValsAndVecs(Mat src,
Mat dst,
int blockSize,
int ksize,
int borderType)
Calculates eigenvalues and eigenvectors of image blocks for corner detection.
|
static void |
cornerHarris(Mat src,
Mat dst,
int blockSize,
int ksize,
double k)
Harris edge detector.
|
static void |
cornerHarris(Mat src,
Mat dst,
int blockSize,
int ksize,
double k,
int borderType)
Harris edge detector.
|
static void |
cornerMinEigenVal(Mat src,
Mat dst,
int blockSize)
Calculates the minimal eigenvalue of gradient matrices for corner detection.
|
static void |
cornerMinEigenVal(Mat src,
Mat dst,
int blockSize,
int ksize)
Calculates the minimal eigenvalue of gradient matrices for corner detection.
|
static void |
cornerMinEigenVal(Mat src,
Mat dst,
int blockSize,
int ksize,
int borderType)
Calculates the minimal eigenvalue of gradient matrices for corner detection.
|
static void |
cornerSubPix(Mat image,
MatOfPoint2f corners,
Size winSize,
Size zeroZone,
TermCriteria criteria)
Refines the corner locations.
|
static void |
createHanningWindow(Mat dst,
Size winSize,
int type)
This function computes a Hanning window coefficients in two dimensions.
|
static void |
cvtColor(Mat src,
Mat dst,
int code)
Converts an image from one color space to another.
|
static void |
cvtColor(Mat src,
Mat dst,
int code,
int dstCn)
Converts an image from one color space to another.
|
static void |
dilate(Mat src,
Mat dst,
Mat kernel)
Dilates an image by using a specific structuring element.
|
static void |
dilate(Mat src,
Mat dst,
Mat kernel,
Point anchor,
int iterations)
Dilates an image by using a specific structuring element.
|
static void |
dilate(Mat src,
Mat dst,
Mat kernel,
Point anchor,
int iterations,
int borderType,
Scalar borderValue)
Dilates an image by using a specific structuring element.
|
static void |
distanceTransform(Mat src,
Mat dst,
int distanceType,
int maskSize)
Calculates the distance to the closest zero pixel for each pixel of the
source image.
|
static void |
distanceTransformWithLabels(Mat src,
Mat dst,
Mat labels,
int distanceType,
int maskSize)
Calculates the distance to the closest zero pixel for each pixel of the
source image.
|
static void |
distanceTransformWithLabels(Mat src,
Mat dst,
Mat labels,
int distanceType,
int maskSize,
int labelType)
Calculates the distance to the closest zero pixel for each pixel of the
source image.
|
static void |
drawContours(Mat image,
java.util.List<MatOfPoint> contours,
int contourIdx,
Scalar color)
Draws contours outlines or filled contours.
|
static void |
drawContours(Mat image,
java.util.List<MatOfPoint> contours,
int contourIdx,
Scalar color,
int thickness)
Draws contours outlines or filled contours.
|
static void |
drawContours(Mat image,
java.util.List<MatOfPoint> contours,
int contourIdx,
Scalar color,
int thickness,
int lineType,
Mat hierarchy,
int maxLevel,
Point offset)
Draws contours outlines or filled contours.
|
static void |
equalizeHist(Mat src,
Mat dst)
Equalizes the histogram of a grayscale image.
|
static void |
erode(Mat src,
Mat dst,
Mat kernel)
Erodes an image by using a specific structuring element.
|
static void |
erode(Mat src,
Mat dst,
Mat kernel,
Point anchor,
int iterations)
Erodes an image by using a specific structuring element.
|
static void |
erode(Mat src,
Mat dst,
Mat kernel,
Point anchor,
int iterations,
int borderType,
Scalar borderValue)
Erodes an image by using a specific structuring element.
|
static void |
filter2D(Mat src,
Mat dst,
int ddepth,
Mat kernel)
Convolves an image with the kernel.
|
static void |
filter2D(Mat src,
Mat dst,
int ddepth,
Mat kernel,
Point anchor,
double delta)
Convolves an image with the kernel.
|
static void |
filter2D(Mat src,
Mat dst,
int ddepth,
Mat kernel,
Point anchor,
double delta,
int borderType)
Convolves an image with the kernel.
|
static void |
findContours(Mat image,
java.util.List<MatOfPoint> contours,
Mat hierarchy,
int mode,
int method)
Finds contours in a binary image.
|
static void |
findContours(Mat image,
java.util.List<MatOfPoint> contours,
Mat hierarchy,
int mode,
int method,
Point offset)
Finds contours in a binary image.
|
static RotatedRect |
fitEllipse(MatOfPoint2f points)
Fits an ellipse around a set of 2D points.
|
static void |
fitLine(Mat points,
Mat line,
int distType,
double param,
double reps,
double aeps)
Fits a line to a 2D or 3D point set.
|
static int |
floodFill(Mat image,
Mat mask,
Point seedPoint,
Scalar newVal)
Fills a connected component with the given color.
|
static int |
floodFill(Mat image,
Mat mask,
Point seedPoint,
Scalar newVal,
Rect rect,
Scalar loDiff,
Scalar upDiff,
int flags)
Fills a connected component with the given color.
|
static void |
GaussianBlur(Mat src,
Mat dst,
Size ksize,
double sigmaX)
Blurs an image using a Gaussian filter.
|
static void |
GaussianBlur(Mat src,
Mat dst,
Size ksize,
double sigmaX,
double sigmaY)
Blurs an image using a Gaussian filter.
|
static void |
GaussianBlur(Mat src,
Mat dst,
Size ksize,
double sigmaX,
double sigmaY,
int borderType)
Blurs an image using a Gaussian filter.
|
static Mat |
getAffineTransform(MatOfPoint2f src,
MatOfPoint2f dst)
Calculates an affine transform from three pairs of the corresponding points.
|
static Mat |
getDefaultNewCameraMatrix(Mat cameraMatrix)
Returns the default new camera matrix.
|
static Mat |
getDefaultNewCameraMatrix(Mat cameraMatrix,
Size imgsize,
boolean centerPrincipalPoint)
Returns the default new camera matrix.
|
static void |
getDerivKernels(Mat kx,
Mat ky,
int dx,
int dy,
int ksize)
Returns filter coefficients for computing spatial image derivatives.
|
static void |
getDerivKernels(Mat kx,
Mat ky,
int dx,
int dy,
int ksize,
boolean normalize,
int ktype)
Returns filter coefficients for computing spatial image derivatives.
|
static Mat |
getGaborKernel(Size ksize,
double sigma,
double theta,
double lambd,
double gamma) |
static Mat |
getGaborKernel(Size ksize,
double sigma,
double theta,
double lambd,
double gamma,
double psi,
int ktype) |
static Mat |
getGaussianKernel(int ksize,
double sigma)
Returns Gaussian filter coefficients.
|
static Mat |
getGaussianKernel(int ksize,
double sigma,
int ktype)
Returns Gaussian filter coefficients.
|
static Mat |
getPerspectiveTransform(Mat src,
Mat dst)
Calculates a perspective transform from four pairs of the corresponding
points.
|
static void |
getRectSubPix(Mat image,
Size patchSize,
Point center,
Mat patch)
Retrieves a pixel rectangle from an image with sub-pixel accuracy.
|
static void |
getRectSubPix(Mat image,
Size patchSize,
Point center,
Mat patch,
int patchType)
Retrieves a pixel rectangle from an image with sub-pixel accuracy.
|
static Mat |
getRotationMatrix2D(Point center,
double angle,
double scale)
Calculates an affine matrix of 2D rotation.
|
static Mat |
getStructuringElement(int shape,
Size ksize)
Returns a structuring element of the specified size and shape for
morphological operations.
|
static Mat |
getStructuringElement(int shape,
Size ksize,
Point anchor)
Returns a structuring element of the specified size and shape for
morphological operations.
|
static void |
goodFeaturesToTrack(Mat image,
MatOfPoint corners,
int maxCorners,
double qualityLevel,
double minDistance)
Determines strong corners on an image.
|
static void |
goodFeaturesToTrack(Mat image,
MatOfPoint corners,
int maxCorners,
double qualityLevel,
double minDistance,
Mat mask,
int blockSize,
boolean useHarrisDetector,
double k)
Determines strong corners on an image.
|
static void |
grabCut(Mat img,
Mat mask,
Rect rect,
Mat bgdModel,
Mat fgdModel,
int iterCount)
Runs the GrabCut algorithm.
|
static void |
grabCut(Mat img,
Mat mask,
Rect rect,
Mat bgdModel,
Mat fgdModel,
int iterCount,
int mode)
Runs the GrabCut algorithm.
|
static void |
HoughCircles(Mat image,
Mat circles,
int method,
double dp,
double minDist)
Finds circles in a grayscale image using the Hough transform.
|
static void |
HoughCircles(Mat image,
Mat circles,
int method,
double dp,
double minDist,
double param1,
double param2,
int minRadius,
int maxRadius)
Finds circles in a grayscale image using the Hough transform.
|
static void |
HoughLines(Mat image,
Mat lines,
double rho,
double theta,
int threshold)
Finds lines in a binary image using the standard Hough transform.
|
static void |
HoughLines(Mat image,
Mat lines,
double rho,
double theta,
int threshold,
double srn,
double stn)
Finds lines in a binary image using the standard Hough transform.
|
static void |
HoughLinesP(Mat image,
Mat lines,
double rho,
double theta,
int threshold)
Finds line segments in a binary image using the probabilistic Hough
transform.
|
static void |
HoughLinesP(Mat image,
Mat lines,
double rho,
double theta,
int threshold,
double minLineLength,
double maxLineGap)
Finds line segments in a binary image using the probabilistic Hough
transform.
|
static void |
HuMoments(Moments m,
Mat hu)
Calculates seven Hu invariants.
|
static void |
initUndistortRectifyMap(Mat cameraMatrix,
Mat distCoeffs,
Mat R,
Mat newCameraMatrix,
Size size,
int m1type,
Mat map1,
Mat map2)
Computes the undistortion and rectification transformation map.
|
static float |
initWideAngleProjMap(Mat cameraMatrix,
Mat distCoeffs,
Size imageSize,
int destImageWidth,
int m1type,
Mat map1,
Mat map2) |
static float |
initWideAngleProjMap(Mat cameraMatrix,
Mat distCoeffs,
Size imageSize,
int destImageWidth,
int m1type,
Mat map1,
Mat map2,
int projType,
double alpha) |
static void |
integral(Mat src,
Mat sum)
Calculates the integral of an image.
|
static void |
integral(Mat src,
Mat sum,
int sdepth)
Calculates the integral of an image.
|
static void |
integral2(Mat src,
Mat sum,
Mat sqsum)
Calculates the integral of an image.
|
static void |
integral2(Mat src,
Mat sum,
Mat sqsum,
int sdepth)
Calculates the integral of an image.
|
static void |
integral3(Mat src,
Mat sum,
Mat sqsum,
Mat tilted)
Calculates the integral of an image.
|
static void |
integral3(Mat src,
Mat sum,
Mat sqsum,
Mat tilted,
int sdepth)
Calculates the integral of an image.
|
static float |
intersectConvexConvex(Mat _p1,
Mat _p2,
Mat _p12) |
static float |
intersectConvexConvex(Mat _p1,
Mat _p2,
Mat _p12,
boolean handleNested) |
static void |
invertAffineTransform(Mat M,
Mat iM)
Inverts an affine transformation.
|
static boolean |
isContourConvex(MatOfPoint contour)
Tests a contour convexity.
|
static void |
Laplacian(Mat src,
Mat dst,
int ddepth)
Calculates the Laplacian of an image.
|
static void |
Laplacian(Mat src,
Mat dst,
int ddepth,
int ksize,
double scale,
double delta)
Calculates the Laplacian of an image.
|
static void |
Laplacian(Mat src,
Mat dst,
int ddepth,
int ksize,
double scale,
double delta,
int borderType)
Calculates the Laplacian of an image.
|
static double |
matchShapes(Mat contour1,
Mat contour2,
int method,
double parameter)
Compares two shapes.
|
static void |
matchTemplate(Mat image,
Mat templ,
Mat result,
int method)
Compares a template against overlapped image regions.
|
static void |
medianBlur(Mat src,
Mat dst,
int ksize)
Blurs an image using the median filter.
|
static RotatedRect |
minAreaRect(MatOfPoint2f points)
Finds a rotated rectangle of the minimum area enclosing the input 2D point
set.
|
static void |
minEnclosingCircle(MatOfPoint2f points,
Point center,
float[] radius)
Finds a circle of the minimum area enclosing a 2D point set.
|
static Moments |
moments(Mat array)
Calculates all of the moments up to the third order of a polygon or
rasterized shape.
|
static Moments |
moments(Mat array,
boolean binaryImage)
Calculates all of the moments up to the third order of a polygon or
rasterized shape.
|
static void |
morphologyEx(Mat src,
Mat dst,
int op,
Mat kernel)
Performs advanced morphological transformations.
|
static void |
morphologyEx(Mat src,
Mat dst,
int op,
Mat kernel,
Point anchor,
int iterations)
Performs advanced morphological transformations.
|
static void |
morphologyEx(Mat src,
Mat dst,
int op,
Mat kernel,
Point anchor,
int iterations,
int borderType,
Scalar borderValue)
Performs advanced morphological transformations.
|
static Point |
phaseCorrelate(Mat src1,
Mat src2)
The function is used to detect translational shifts that occur between two
images.
|
static Point |
phaseCorrelate(Mat src1,
Mat src2,
Mat window)
The function is used to detect translational shifts that occur between two
images.
|
static Point |
phaseCorrelateRes(Mat src1,
Mat src2,
Mat window) |
static Point |
phaseCorrelateRes(Mat src1,
Mat src2,
Mat window,
double[] response) |
static double |
pointPolygonTest(MatOfPoint2f contour,
Point pt,
boolean measureDist)
Performs a point-in-contour test.
|
static void |
preCornerDetect(Mat src,
Mat dst,
int ksize)
Calculates a feature map for corner detection.
|
static void |
preCornerDetect(Mat src,
Mat dst,
int ksize,
int borderType)
Calculates a feature map for corner detection.
|
static double |
PSNR(Mat src1,
Mat src2) |
static void |
pyrDown(Mat src,
Mat dst)
Blurs an image and downsamples it.
|
static void |
pyrDown(Mat src,
Mat dst,
Size dstsize)
Blurs an image and downsamples it.
|
static void |
pyrDown(Mat src,
Mat dst,
Size dstsize,
int borderType)
Blurs an image and downsamples it.
|
static void |
pyrMeanShiftFiltering(Mat src,
Mat dst,
double sp,
double sr)
Performs initial step of meanshift segmentation of an image.
|
static void |
pyrMeanShiftFiltering(Mat src,
Mat dst,
double sp,
double sr,
int maxLevel,
TermCriteria termcrit)
Performs initial step of meanshift segmentation of an image.
|
static void |
pyrUp(Mat src,
Mat dst)
Upsamples an image and then blurs it.
|
static void |
pyrUp(Mat src,
Mat dst,
Size dstsize)
Upsamples an image and then blurs it.
|
static void |
pyrUp(Mat src,
Mat dst,
Size dstsize,
int borderType)
Upsamples an image and then blurs it.
|
static void |
remap(Mat src,
Mat dst,
Mat map1,
Mat map2,
int interpolation)
Applies a generic geometrical transformation to an image.
|
static void |
remap(Mat src,
Mat dst,
Mat map1,
Mat map2,
int interpolation,
int borderMode,
Scalar borderValue)
Applies a generic geometrical transformation to an image.
|
static void |
resize(Mat src,
Mat dst,
Size dsize)
Resizes an image.
|
static void |
resize(Mat src,
Mat dst,
Size dsize,
double fx,
double fy,
int interpolation)
Resizes an image.
|
static void |
Scharr(Mat src,
Mat dst,
int ddepth,
int dx,
int dy)
Calculates the first x- or y- image derivative using Scharr operator.
|
static void |
Scharr(Mat src,
Mat dst,
int ddepth,
int dx,
int dy,
double scale,
double delta)
Calculates the first x- or y- image derivative using Scharr operator.
|
static void |
Scharr(Mat src,
Mat dst,
int ddepth,
int dx,
int dy,
double scale,
double delta,
int borderType)
Calculates the first x- or y- image derivative using Scharr operator.
|
static void |
sepFilter2D(Mat src,
Mat dst,
int ddepth,
Mat kernelX,
Mat kernelY)
Applies a separable linear filter to an image.
|
static void |
sepFilter2D(Mat src,
Mat dst,
int ddepth,
Mat kernelX,
Mat kernelY,
Point anchor,
double delta)
Applies a separable linear filter to an image.
|
static void |
sepFilter2D(Mat src,
Mat dst,
int ddepth,
Mat kernelX,
Mat kernelY,
Point anchor,
double delta,
int borderType)
Applies a separable linear filter to an image.
|
static void |
Sobel(Mat src,
Mat dst,
int ddepth,
int dx,
int dy)
Calculates the first, second, third, or mixed image derivatives using an
extended Sobel operator.
|
static void |
Sobel(Mat src,
Mat dst,
int ddepth,
int dx,
int dy,
int ksize,
double scale,
double delta)
Calculates the first, second, third, or mixed image derivatives using an
extended Sobel operator.
|
static void |
Sobel(Mat src,
Mat dst,
int ddepth,
int dx,
int dy,
int ksize,
double scale,
double delta,
int borderType)
Calculates the first, second, third, or mixed image derivatives using an
extended Sobel operator.
|
static double |
threshold(Mat src,
Mat dst,
double thresh,
double maxval,
int type)
Applies a fixed-level threshold to each array element.
|
static void |
undistort(Mat src,
Mat dst,
Mat cameraMatrix,
Mat distCoeffs)
Transforms an image to compensate for lens distortion.
|
static void |
undistort(Mat src,
Mat dst,
Mat cameraMatrix,
Mat distCoeffs,
Mat newCameraMatrix)
Transforms an image to compensate for lens distortion.
|
static void |
undistortPoints(MatOfPoint2f src,
MatOfPoint2f dst,
Mat cameraMatrix,
Mat distCoeffs)
Computes the ideal point coordinates from the observed point coordinates.
|
static void |
undistortPoints(MatOfPoint2f src,
MatOfPoint2f dst,
Mat cameraMatrix,
Mat distCoeffs,
Mat R,
Mat P)
Computes the ideal point coordinates from the observed point coordinates.
|
static void |
warpAffine(Mat src,
Mat dst,
Mat M,
Size dsize)
Applies an affine transformation to an image.
|
static void |
warpAffine(Mat src,
Mat dst,
Mat M,
Size dsize,
int flags)
Applies an affine transformation to an image.
|
static void |
warpAffine(Mat src,
Mat dst,
Mat M,
Size dsize,
int flags,
int borderMode,
Scalar borderValue)
Applies an affine transformation to an image.
|
static void |
warpPerspective(Mat src,
Mat dst,
Mat M,
Size dsize)
Applies a perspective transformation to an image.
|
static void |
warpPerspective(Mat src,
Mat dst,
Mat M,
Size dsize,
int flags)
Applies a perspective transformation to an image.
|
static void |
warpPerspective(Mat src,
Mat dst,
Mat M,
Size dsize,
int flags,
int borderMode,
Scalar borderValue)
Applies a perspective transformation to an image.
|
static void |
watershed(Mat image,
Mat markers)
Performs a marker-based image segmentation using the watershed algorithm.
|
public static final int ADAPTIVE_THRESH_GAUSSIAN_C
public static final int ADAPTIVE_THRESH_MEAN_C
public static final int BORDER_CONSTANT
public static final int BORDER_DEFAULT
public static final int BORDER_ISOLATED
public static final int BORDER_REFLECT
public static final int BORDER_REFLECT_101
public static final int BORDER_REFLECT101
public static final int BORDER_REPLICATE
public static final int BORDER_TRANSPARENT
public static final int BORDER_WRAP
public static final int CHAIN_APPROX_NONE
public static final int CHAIN_APPROX_SIMPLE
public static final int CHAIN_APPROX_TC89_KCOS
public static final int CHAIN_APPROX_TC89_L1
public static final int COLOR_BayerBG2BGR
public static final int COLOR_BayerBG2BGR_VNG
public static final int COLOR_BayerBG2GRAY
public static final int COLOR_BayerBG2RGB
public static final int COLOR_BayerBG2RGB_VNG
public static final int COLOR_BayerGB2BGR
public static final int COLOR_BayerGB2BGR_VNG
public static final int COLOR_BayerGB2GRAY
public static final int COLOR_BayerGB2RGB
public static final int COLOR_BayerGB2RGB_VNG
public static final int COLOR_BayerGR2BGR
public static final int COLOR_BayerGR2BGR_VNG
public static final int COLOR_BayerGR2GRAY
public static final int COLOR_BayerGR2RGB
public static final int COLOR_BayerGR2RGB_VNG
public static final int COLOR_BayerRG2BGR
public static final int COLOR_BayerRG2BGR_VNG
public static final int COLOR_BayerRG2GRAY
public static final int COLOR_BayerRG2RGB
public static final int COLOR_BayerRG2RGB_VNG
public static final int COLOR_BGR2BGR555
public static final int COLOR_BGR2BGR565
public static final int COLOR_BGR2BGRA
public static final int COLOR_BGR2GRAY
public static final int COLOR_BGR2HLS
public static final int COLOR_BGR2HLS_FULL
public static final int COLOR_BGR2HSV
public static final int COLOR_BGR2HSV_FULL
public static final int COLOR_BGR2Lab
public static final int COLOR_BGR2Luv
public static final int COLOR_BGR2RGB
public static final int COLOR_BGR2RGBA
public static final int COLOR_BGR2XYZ
public static final int COLOR_BGR2YCrCb
public static final int COLOR_BGR2YUV
public static final int COLOR_BGR2YUV_I420
public static final int COLOR_BGR2YUV_IYUV
public static final int COLOR_BGR2YUV_YV12
public static final int COLOR_BGR5552BGR
public static final int COLOR_BGR5552BGRA
public static final int COLOR_BGR5552GRAY
public static final int COLOR_BGR5552RGB
public static final int COLOR_BGR5552RGBA
public static final int COLOR_BGR5652BGR
public static final int COLOR_BGR5652BGRA
public static final int COLOR_BGR5652GRAY
public static final int COLOR_BGR5652RGB
public static final int COLOR_BGR5652RGBA
public static final int COLOR_BGRA2BGR
public static final int COLOR_BGRA2BGR555
public static final int COLOR_BGRA2BGR565
public static final int COLOR_BGRA2GRAY
public static final int COLOR_BGRA2RGB
public static final int COLOR_BGRA2RGBA
public static final int COLOR_BGRA2YUV_I420
public static final int COLOR_BGRA2YUV_IYUV
public static final int COLOR_BGRA2YUV_YV12
public static final int COLOR_COLORCVT_MAX
public static final int COLOR_GRAY2BGR
public static final int COLOR_GRAY2BGR555
public static final int COLOR_GRAY2BGR565
public static final int COLOR_GRAY2BGRA
public static final int COLOR_GRAY2RGB
public static final int COLOR_GRAY2RGBA
public static final int COLOR_HLS2BGR
public static final int COLOR_HLS2BGR_FULL
public static final int COLOR_HLS2RGB
public static final int COLOR_HLS2RGB_FULL
public static final int COLOR_HSV2BGR
public static final int COLOR_HSV2BGR_FULL
public static final int COLOR_HSV2RGB
public static final int COLOR_HSV2RGB_FULL
public static final int COLOR_Lab2BGR
public static final int COLOR_Lab2LBGR
public static final int COLOR_Lab2LRGB
public static final int COLOR_Lab2RGB
public static final int COLOR_LBGR2Lab
public static final int COLOR_LBGR2Luv
public static final int COLOR_LRGB2Lab
public static final int COLOR_LRGB2Luv
public static final int COLOR_Luv2BGR
public static final int COLOR_Luv2LBGR
public static final int COLOR_Luv2LRGB
public static final int COLOR_Luv2RGB
public static final int COLOR_mRGBA2RGBA
public static final int COLOR_RGB2BGR
public static final int COLOR_RGB2BGR555
public static final int COLOR_RGB2BGR565
public static final int COLOR_RGB2BGRA
public static final int COLOR_RGB2GRAY
public static final int COLOR_RGB2HLS
public static final int COLOR_RGB2HLS_FULL
public static final int COLOR_RGB2HSV
public static final int COLOR_RGB2HSV_FULL
public static final int COLOR_RGB2Lab
public static final int COLOR_RGB2Luv
public static final int COLOR_RGB2RGBA
public static final int COLOR_RGB2XYZ
public static final int COLOR_RGB2YCrCb
public static final int COLOR_RGB2YUV
public static final int COLOR_RGB2YUV_I420
public static final int COLOR_RGB2YUV_IYUV
public static final int COLOR_RGB2YUV_YV12
public static final int COLOR_RGBA2BGR
public static final int COLOR_RGBA2BGR555
public static final int COLOR_RGBA2BGR565
public static final int COLOR_RGBA2BGRA
public static final int COLOR_RGBA2GRAY
public static final int COLOR_RGBA2mRGBA
public static final int COLOR_RGBA2RGB
public static final int COLOR_RGBA2YUV_I420
public static final int COLOR_RGBA2YUV_IYUV
public static final int COLOR_RGBA2YUV_YV12
public static final int COLOR_XYZ2BGR
public static final int COLOR_XYZ2RGB
public static final int COLOR_YCrCb2BGR
public static final int COLOR_YCrCb2RGB
public static final int COLOR_YUV2BGR
public static final int COLOR_YUV2BGR_I420
public static final int COLOR_YUV2BGR_IYUV
public static final int COLOR_YUV2BGR_NV12
public static final int COLOR_YUV2BGR_NV21
public static final int COLOR_YUV2BGR_UYNV
public static final int COLOR_YUV2BGR_UYVY
public static final int COLOR_YUV2BGR_Y422
public static final int COLOR_YUV2BGR_YUNV
public static final int COLOR_YUV2BGR_YUY2
public static final int COLOR_YUV2BGR_YUYV
public static final int COLOR_YUV2BGR_YV12
public static final int COLOR_YUV2BGR_YVYU
public static final int COLOR_YUV2BGRA_I420
public static final int COLOR_YUV2BGRA_IYUV
public static final int COLOR_YUV2BGRA_NV12
public static final int COLOR_YUV2BGRA_NV21
public static final int COLOR_YUV2BGRA_UYNV
public static final int COLOR_YUV2BGRA_UYVY
public static final int COLOR_YUV2BGRA_Y422
public static final int COLOR_YUV2BGRA_YUNV
public static final int COLOR_YUV2BGRA_YUY2
public static final int COLOR_YUV2BGRA_YUYV
public static final int COLOR_YUV2BGRA_YV12
public static final int COLOR_YUV2BGRA_YVYU
public static final int COLOR_YUV2GRAY_420
public static final int COLOR_YUV2GRAY_I420
public static final int COLOR_YUV2GRAY_IYUV
public static final int COLOR_YUV2GRAY_NV12
public static final int COLOR_YUV2GRAY_NV21
public static final int COLOR_YUV2GRAY_UYNV
public static final int COLOR_YUV2GRAY_UYVY
public static final int COLOR_YUV2GRAY_Y422
public static final int COLOR_YUV2GRAY_YUNV
public static final int COLOR_YUV2GRAY_YUY2
public static final int COLOR_YUV2GRAY_YUYV
public static final int COLOR_YUV2GRAY_YV12
public static final int COLOR_YUV2GRAY_YVYU
public static final int COLOR_YUV2RGB
public static final int COLOR_YUV2RGB_I420
public static final int COLOR_YUV2RGB_IYUV
public static final int COLOR_YUV2RGB_NV12
public static final int COLOR_YUV2RGB_NV21
public static final int COLOR_YUV2RGB_UYNV
public static final int COLOR_YUV2RGB_UYVY
public static final int COLOR_YUV2RGB_Y422
public static final int COLOR_YUV2RGB_YUNV
public static final int COLOR_YUV2RGB_YUY2
public static final int COLOR_YUV2RGB_YUYV
public static final int COLOR_YUV2RGB_YV12
public static final int COLOR_YUV2RGB_YVYU
public static final int COLOR_YUV2RGBA_I420
public static final int COLOR_YUV2RGBA_IYUV
public static final int COLOR_YUV2RGBA_NV12
public static final int COLOR_YUV2RGBA_NV21
public static final int COLOR_YUV2RGBA_UYNV
public static final int COLOR_YUV2RGBA_UYVY
public static final int COLOR_YUV2RGBA_Y422
public static final int COLOR_YUV2RGBA_YUNV
public static final int COLOR_YUV2RGBA_YUY2
public static final int COLOR_YUV2RGBA_YUYV
public static final int COLOR_YUV2RGBA_YV12
public static final int COLOR_YUV2RGBA_YVYU
public static final int COLOR_YUV420p2BGR
public static final int COLOR_YUV420p2BGRA
public static final int COLOR_YUV420p2GRAY
public static final int COLOR_YUV420p2RGB
public static final int COLOR_YUV420p2RGBA
public static final int COLOR_YUV420sp2BGR
public static final int COLOR_YUV420sp2BGRA
public static final int COLOR_YUV420sp2GRAY
public static final int COLOR_YUV420sp2RGB
public static final int COLOR_YUV420sp2RGBA
public static final int CV_BILATERAL
public static final int CV_BLUR
public static final int CV_BLUR_NO_SCALE
public static final int CV_CANNY_L2_GRADIENT
public static final int CV_CHAIN_CODE
public static final int CV_CLOCKWISE
public static final int CV_COMP_BHATTACHARYYA
public static final int CV_COMP_CHISQR
public static final int CV_COMP_CORREL
public static final int CV_COMP_HELLINGER
public static final int CV_COMP_INTERSECT
public static final int CV_CONTOURS_MATCH_I1
public static final int CV_CONTOURS_MATCH_I2
public static final int CV_CONTOURS_MATCH_I3
public static final int CV_COUNTER_CLOCKWISE
public static final int CV_DIST_C
public static final int CV_DIST_FAIR
public static final int CV_DIST_HUBER
public static final int CV_DIST_L1
public static final int CV_DIST_L12
public static final int CV_DIST_L2
public static final int CV_DIST_LABEL_CCOMP
public static final int CV_DIST_LABEL_PIXEL
public static final int CV_DIST_MASK_3
public static final int CV_DIST_MASK_5
public static final int CV_DIST_MASK_PRECISE
public static final int CV_DIST_USER
public static final int CV_DIST_WELSCH
public static final int CV_GAUSSIAN
public static final int CV_GAUSSIAN_5x5
public static final int CV_HOUGH_GRADIENT
public static final int CV_HOUGH_MULTI_SCALE
public static final int CV_HOUGH_PROBABILISTIC
public static final int CV_HOUGH_STANDARD
public static final int CV_LINK_RUNS
public static final int CV_MAX_SOBEL_KSIZE
public static final int CV_MEDIAN
public static final int CV_mRGBA2RGBA
public static final int CV_POLY_APPROX_DP
public static final int CV_RGBA2mRGBA
public static final int CV_SCHARR
public static final int CV_SHAPE_CROSS
public static final int CV_SHAPE_CUSTOM
public static final int CV_SHAPE_ELLIPSE
public static final int CV_SHAPE_RECT
public static final int CV_WARP_FILL_OUTLIERS
public static final int CV_WARP_INVERSE_MAP
public static final int DIST_LABEL_CCOMP
public static final int DIST_LABEL_PIXEL
public static final int FLOODFILL_FIXED_RANGE
public static final int FLOODFILL_MASK_ONLY
public static final int GC_BGD
public static final int GC_EVAL
public static final int GC_FGD
public static final int GC_INIT_WITH_MASK
public static final int GC_INIT_WITH_RECT
public static final int GC_PR_BGD
public static final int GC_PR_FGD
public static final int GHT_POSITION
public static final int GHT_ROTATION
public static final int GHT_SCALE
public static final int INTER_AREA
public static final int INTER_BITS
public static final int INTER_BITS2
public static final int INTER_CUBIC
public static final int INTER_LANCZOS4
public static final int INTER_LINEAR
public static final int INTER_MAX
public static final int INTER_NEAREST
public static final int INTER_TAB_SIZE
public static final int INTER_TAB_SIZE2
public static final int KERNEL_ASYMMETRICAL
public static final int KERNEL_GENERAL
public static final int KERNEL_INTEGER
public static final int KERNEL_SMOOTH
public static final int KERNEL_SYMMETRICAL
public static final int MORPH_BLACKHAT
public static final int MORPH_CLOSE
public static final int MORPH_CROSS
public static final int MORPH_DILATE
public static final int MORPH_ELLIPSE
public static final int MORPH_ERODE
public static final int MORPH_GRADIENT
public static final int MORPH_HITMISS
public static final int MORPH_OPEN
public static final int MORPH_RECT
public static final int MORPH_TOPHAT
public static final int PROJ_SPHERICAL_EQRECT
public static final int PROJ_SPHERICAL_ORTHO
public static final int RETR_CCOMP
public static final int RETR_EXTERNAL
public static final int RETR_FLOODFILL
public static final int RETR_LIST
public static final int RETR_TREE
public static final int THRESH_BINARY
public static final int THRESH_BINARY_INV
public static final int THRESH_MASK
public static final int THRESH_OTSU
public static final int THRESH_TOZERO
public static final int THRESH_TOZERO_INV
public static final int THRESH_TRUNC
public static final int TM_CCOEFF
public static final int TM_CCOEFF_NORMED
public static final int TM_CCORR
public static final int TM_CCORR_NORMED
public static final int TM_SQDIFF
public static final int TM_SQDIFF_NORMED
public static final int WARP_INVERSE_MAP
public static void accumulate(Mat src, Mat dst)
Adds an image to the accumulator.
The function adds src
or some of its elements to
dst
:
dst(x,y) <- dst(x,y) + src(x,y) if mask(x,y) != 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.
src
- Input image as 1- or 3-channel, 8-bit or 32-bit floating point.dst
- Accumulator image with the same number of channels as input image,
32-bit or 64-bit floating-point.accumulateWeighted(org.opencv.core.Mat, org.opencv.core.Mat, double, org.opencv.core.Mat)
,
accumulateProduct(org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat)
,
accumulateSquare(org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat)
public static void accumulate(Mat src, Mat dst, Mat mask)
Adds an image to the accumulator.
The function adds src
or some of its elements to
dst
:
dst(x,y) <- dst(x,y) + src(x,y) if mask(x,y) != 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.
src
- Input image as 1- or 3-channel, 8-bit or 32-bit floating point.dst
- Accumulator image with the same number of channels as input image,
32-bit or 64-bit floating-point.mask
- Optional operation mask.accumulateWeighted(org.opencv.core.Mat, org.opencv.core.Mat, double, org.opencv.core.Mat)
,
accumulateProduct(org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat)
,
accumulateSquare(org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat)
public static void accumulateProduct(Mat src1, Mat src2, Mat dst)
Adds the per-element product of two input images to the accumulator.
The function adds the product of two images or their selected regions to the
accumulator dst
:
dst(x,y) <- dst(x,y) + src1(x,y) * src2(x,y) if mask(x,y) != 0
The function supports multi-channel images. Each channel is processed independently.
src1
- First input image, 1- or 3-channel, 8-bit or 32-bit floating
point.src2
- Second input image of the same type and the same size as
src1
.dst
- Accumulator with the same number of channels as input images,
32-bit or 64-bit floating-point.accumulate(org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat)
,
accumulateWeighted(org.opencv.core.Mat, org.opencv.core.Mat, double, org.opencv.core.Mat)
,
accumulateSquare(org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat)
public static void accumulateProduct(Mat src1, Mat src2, Mat dst, Mat mask)
Adds the per-element product of two input images to the accumulator.
The function adds the product of two images or their selected regions to the
accumulator dst
:
dst(x,y) <- dst(x,y) + src1(x,y) * src2(x,y) if mask(x,y) != 0
The function supports multi-channel images. Each channel is processed independently.
src1
- First input image, 1- or 3-channel, 8-bit or 32-bit floating
point.src2
- Second input image of the same type and the same size as
src1
.dst
- Accumulator with the same number of channels as input images,
32-bit or 64-bit floating-point.mask
- Optional operation mask.accumulate(org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat)
,
accumulateWeighted(org.opencv.core.Mat, org.opencv.core.Mat, double, org.opencv.core.Mat)
,
accumulateSquare(org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat)
public static void accumulateSquare(Mat src, Mat dst)
Adds the square of a source image to the accumulator.
The function adds the input image src
or its selected region,
raised to a power of 2, to the accumulator dst
:
dst(x,y) <- dst(x,y) + src(x,y)^2 if mask(x,y) != 0
The function supports multi-channel images. Each channel is processed independently.
src
- Input image as 1- or 3-channel, 8-bit or 32-bit floating point.dst
- Accumulator image with the same number of channels as input image,
32-bit or 64-bit floating-point.accumulateWeighted(org.opencv.core.Mat, org.opencv.core.Mat, double, org.opencv.core.Mat)
,
accumulateProduct(org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat)
,
accumulateSquare(org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat)
public static void accumulateSquare(Mat src, Mat dst, Mat mask)
Adds the square of a source image to the accumulator.
The function adds the input image src
or its selected region,
raised to a power of 2, to the accumulator dst
:
dst(x,y) <- dst(x,y) + src(x,y)^2 if mask(x,y) != 0
The function supports multi-channel images. Each channel is processed independently.
src
- Input image as 1- or 3-channel, 8-bit or 32-bit floating point.dst
- Accumulator image with the same number of channels as input image,
32-bit or 64-bit floating-point.mask
- Optional operation mask.accumulateWeighted(org.opencv.core.Mat, org.opencv.core.Mat, double, org.opencv.core.Mat)
,
accumulateProduct(org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat)
,
accumulateSquare(org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat)
public static void accumulateWeighted(Mat src, Mat dst, double alpha)
Updates a running average.
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:
dst(x,y) <- (1- alpha) * dst(x,y) + alpha * src(x,y) if mask(x,y) != 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.
src
- Input image as 1- or 3-channel, 8-bit or 32-bit floating point.dst
- Accumulator image with the same number of channels as input image,
32-bit or 64-bit floating-point.alpha
- Weight of the input image.accumulate(org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat)
,
accumulateProduct(org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat)
,
accumulateSquare(org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat)
public static void accumulateWeighted(Mat src, Mat dst, double alpha, Mat mask)
Updates a running average.
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:
dst(x,y) <- (1- alpha) * dst(x,y) + alpha * src(x,y) if mask(x,y) != 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.
src
- Input image as 1- or 3-channel, 8-bit or 32-bit floating point.dst
- Accumulator image with the same number of channels as input image,
32-bit or 64-bit floating-point.alpha
- Weight of the input image.mask
- Optional operation mask.accumulate(org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat)
,
accumulateProduct(org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat)
,
accumulateSquare(org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat)
public static void adaptiveBilateralFilter(Mat src, Mat dst, Size ksize, double sigmaSpace)
Applies the adaptive bilateral filter to an image.
A main part of our strategy will be to load each raw pixel once, and reuse it to calculate all pixels in the output (filtered) image that need this pixel value. The math of the filter is that of the usual bilateral filter, except that the sigma color is calculated in the neighborhood, and clamped by the optional input value.
src
- The source imagedst
- The destination image; will have the same size and the same type
as srcksize
- The kernel size. This is the neighborhood where the local
variance will be calculated, and where pixels will contribute (in a weighted
manner).sigmaSpace
- Filter sigma in the coordinate space. Larger value of the
parameter means that farther pixels will influence each other (as long as
their colors are close enough; see sigmaColor). Then d>0, it specifies the
neighborhood size regardless of sigmaSpace, otherwise d is proportional to
sigmaSpace.public static void adaptiveBilateralFilter(Mat src, Mat dst, Size ksize, double sigmaSpace, double maxSigmaColor, Point anchor)
Applies the adaptive bilateral filter to an image.
A main part of our strategy will be to load each raw pixel once, and reuse it to calculate all pixels in the output (filtered) image that need this pixel value. The math of the filter is that of the usual bilateral filter, except that the sigma color is calculated in the neighborhood, and clamped by the optional input value.
src
- The source imagedst
- The destination image; will have the same size and the same type
as srcksize
- The kernel size. This is the neighborhood where the local
variance will be calculated, and where pixels will contribute (in a weighted
manner).sigmaSpace
- Filter sigma in the coordinate space. Larger value of the
parameter means that farther pixels will influence each other (as long as
their colors are close enough; see sigmaColor). Then d>0, it specifies the
neighborhood size regardless of sigmaSpace, otherwise d is proportional to
sigmaSpace.maxSigmaColor
- Maximum allowed sigma color (will clamp the value
calculated in the ksize neighborhood. Larger value of the parameter means
that more dissimilar pixels will influence each other (as long as their
colors are close enough; see sigmaColor). Then d>0, it specifies the
neighborhood size regardless of sigmaSpace, otherwise d is proportional to
sigmaSpace.anchor
- a anchorpublic static void adaptiveBilateralFilter(Mat src, Mat dst, Size ksize, double sigmaSpace, double maxSigmaColor, Point anchor, int borderType)
Applies the adaptive bilateral filter to an image.
A main part of our strategy will be to load each raw pixel once, and reuse it to calculate all pixels in the output (filtered) image that need this pixel value. The math of the filter is that of the usual bilateral filter, except that the sigma color is calculated in the neighborhood, and clamped by the optional input value.
src
- The source imagedst
- The destination image; will have the same size and the same type
as srcksize
- The kernel size. This is the neighborhood where the local
variance will be calculated, and where pixels will contribute (in a weighted
manner).sigmaSpace
- Filter sigma in the coordinate space. Larger value of the
parameter means that farther pixels will influence each other (as long as
their colors are close enough; see sigmaColor). Then d>0, it specifies the
neighborhood size regardless of sigmaSpace, otherwise d is proportional to
sigmaSpace.maxSigmaColor
- Maximum allowed sigma color (will clamp the value
calculated in the ksize neighborhood. Larger value of the parameter means
that more dissimilar pixels will influence each other (as long as their
colors are close enough; see sigmaColor). Then d>0, it specifies the
neighborhood size regardless of sigmaSpace, otherwise d is proportional to
sigmaSpace.anchor
- a anchorborderType
- Pixel extrapolation method.public static void adaptiveThreshold(Mat src, Mat dst, double maxValue, int adaptiveMethod, int thresholdType, int blockSize, double C)
Applies an adaptive threshold to an array.
The function transforms a grayscale image to a binary image according to the formulae:
dst(x,y) = maxValue if src(x,y) > T(x,y); 0 otherwise
dst(x,y) = 0 if src(x,y) > T(x,y); maxValue otherwise
where T(x,y) is a threshold calculated individually for each pixel.
ADAPTIVE_THRESH_MEAN_C
, the threshold
value T(x,y) is a mean of the blockSize x blockSize
neighborhood of (x, y) minus C
.
ADAPTIVE_THRESH_GAUSSIAN_C
, the threshold
value T(x, y) is a weighted sum (cross-correlation with a Gaussian
window) of the blockSize x blockSize neighborhood of (x, y)
minus C
. The default sigma (standard deviation) is used for the
specified blockSize
. See "getGaussianKernel".
The function can process the image in-place.
src
- Source 8-bit single-channel image.dst
- Destination image of the same size and the same type as
src
.maxValue
- Non-zero value assigned to the pixels for which the condition
is satisfied. See the details below.adaptiveMethod
- Adaptive thresholding algorithm to use,
ADAPTIVE_THRESH_MEAN_C
or ADAPTIVE_THRESH_GAUSSIAN_C
.
See the details below.thresholdType
- Thresholding type that must be either THRESH_BINARY
or THRESH_BINARY_INV
.blockSize
- Size of a pixel neighborhood that is used to calculate a
threshold value for the pixel: 3, 5, 7, and so on.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.threshold(org.opencv.core.Mat, org.opencv.core.Mat, double, double, int)
,
GaussianBlur(org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Size, double, double, int)
,
blur(org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Size, org.opencv.core.Point, int)
public static void approxPolyDP(MatOfPoint2f curve, MatOfPoint2f approxCurve, double epsilon, boolean closed)
Approximates a polygonal curve(s) with the specified precision.
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/opencv/opencv/tree/master/samples/cpp/contours2.cpp for the function usage model.
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)
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.epsilon
- Parameter specifying the approximation accuracy. This is the
maximum distance between the original curve and its approximation.closed
- If true, the approximated curve is closed (its first and last
vertices are connected). Otherwise, it is not closed.public static double arcLength(MatOfPoint2f curve, boolean closed)
Calculates a contour perimeter or a curve length.
The function computes a curve length or a closed contour perimeter.
curve
- Input vector of 2D points, stored in std.vector
or
Mat
.closed
- Flag indicating whether the curve is closed or not.public static void bilateralFilter(Mat src, Mat dst, int d, double sigmaColor, double sigmaSpace)
Applies the bilateral filter to an image.
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.
This filter does not work inplace.
src
- Source 8-bit or floating-point, 1-channel or 3-channel image.dst
- Destination image of the same size and type as src
.d
- Diameter of each pixel neighborhood that is used during filtering.
If it is non-positive, it is computed from sigmaSpace
.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.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
.public static void bilateralFilter(Mat src, Mat dst, int d, double sigmaColor, double sigmaSpace, int borderType)
Applies the bilateral filter to an image.
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.
This filter does not work inplace.
src
- Source 8-bit or floating-point, 1-channel or 3-channel image.dst
- Destination image of the same size and type as src
.d
- Diameter of each pixel neighborhood that is used during filtering.
If it is non-positive, it is computed from sigmaSpace
.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.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
.borderType
- a borderTypepublic static void blur(Mat src, Mat dst, Size ksize)
Blurs an image using the normalized box filter.
The function smoothes an image using the kernel:
K = 1/(ksize.width*ksize.height) 1 1 1 *s 1 1 1 1 1 *s 1 1.................. 1 1 1 *s 1 1
The call blur(src, dst, ksize, anchor, borderType)
is equivalent
to boxFilter(src, dst, src.type(), anchor, true, borderType)
.
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
.dst
- output image of the same size and type as src
.ksize
- blurring kernel size.boxFilter(org.opencv.core.Mat, org.opencv.core.Mat, int, org.opencv.core.Size, org.opencv.core.Point, boolean, int)
,
GaussianBlur(org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Size, double, double, int)
,
bilateralFilter(org.opencv.core.Mat, org.opencv.core.Mat, int, double, double, int)
,
medianBlur(org.opencv.core.Mat, org.opencv.core.Mat, int)
public static void blur(Mat src, Mat dst, Size ksize, Point anchor)
Blurs an image using the normalized box filter.
The function smoothes an image using the kernel:
K = 1/(ksize.width*ksize.height) 1 1 1 *s 1 1 1 1 1 *s 1 1.................. 1 1 1 *s 1 1
The call blur(src, dst, ksize, anchor, borderType)
is equivalent
to boxFilter(src, dst, src.type(), anchor, true, borderType)
.
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
.dst
- output image of the same size and type as src
.ksize
- blurring kernel size.anchor
- anchor point; default value Point(-1,-1)
means
that the anchor is at the kernel center.boxFilter(org.opencv.core.Mat, org.opencv.core.Mat, int, org.opencv.core.Size, org.opencv.core.Point, boolean, int)
,
GaussianBlur(org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Size, double, double, int)
,
bilateralFilter(org.opencv.core.Mat, org.opencv.core.Mat, int, double, double, int)
,
medianBlur(org.opencv.core.Mat, org.opencv.core.Mat, int)
public static void blur(Mat src, Mat dst, Size ksize, Point anchor, int borderType)
Blurs an image using the normalized box filter.
The function smoothes an image using the kernel:
K = 1/(ksize.width*ksize.height) 1 1 1 *s 1 1 1 1 1 *s 1 1.................. 1 1 1 *s 1 1
The call blur(src, dst, ksize, anchor, borderType)
is equivalent
to boxFilter(src, dst, src.type(), anchor, true, borderType)
.
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
.dst
- output image of the same size and type as src
.ksize
- blurring kernel size.anchor
- anchor point; default value Point(-1,-1)
means
that the anchor is at the kernel center.borderType
- border mode used to extrapolate pixels outside of the
image.boxFilter(org.opencv.core.Mat, org.opencv.core.Mat, int, org.opencv.core.Size, org.opencv.core.Point, boolean, int)
,
GaussianBlur(org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Size, double, double, int)
,
bilateralFilter(org.opencv.core.Mat, org.opencv.core.Mat, int, double, double, int)
,
medianBlur(org.opencv.core.Mat, org.opencv.core.Mat, int)
public static int borderInterpolate(int p, int len, int borderType)
Computes the source location of an extrapolated pixel.
The function computes and returns the coordinate of a donor pixel
corresponding to the specified extrapolated pixel when using the specified
extrapolation border mode. For example, if you use BORDER_WRAP
mode in the horizontal direction, BORDER_REFLECT_101
in the
vertical direction and want to compute value of the "virtual" pixel
Point(-5, 100)
in a floating-point image img
, it
looks like:
// C++ code:
float val = img.at
borderInterpolate(-5, img.cols, BORDER_WRAP));
Normally, the function is not called directly. It is used inside
"FilterEngine" and "copyMakeBorder" to compute tables for quick extrapolation.
p
- 0-based coordinate of the extrapolated pixel along one of the axes,
likely <0 or >= len
.len
- Length of the array along the corresponding axis.borderType
- Border type, one of the BORDER_*
, except for
BORDER_TRANSPARENT
and BORDER_ISOLATED
. When
borderType==BORDER_CONSTANT
, the function always returns -1,
regardless of p
and len
.copyMakeBorder(org.opencv.core.Mat, org.opencv.core.Mat, int, int, int, int, int, org.opencv.core.Scalar)
public static Rect boundingRect(MatOfPoint points)
Calculates the up-right bounding rectangle of a point set.
The function calculates and returns the minimal up-right bounding rectangle for the specified point set.
points
- Input 2D point set, stored in std.vector
or
Mat
.public static void boxFilter(Mat src, Mat dst, int ddepth, Size ksize)
Blurs an image using the box filter.
The function smoothes an image using the kernel:
K = alpha 1 1 1 *s 1 1 1 1 1 *s 1 1.................. 1 1 1 *s 1 1
where
alpha = 1/(ksize.width*ksize.height) when 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 "integral".
src
- input image.dst
- output image of the same size and type as src
.ddepth
- the output image depth (-1 to use src.depth()
).ksize
- blurring kernel size.GaussianBlur(org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Size, double, double, int)
,
medianBlur(org.opencv.core.Mat, org.opencv.core.Mat, int)
,
integral(org.opencv.core.Mat, org.opencv.core.Mat, int)
,
bilateralFilter(org.opencv.core.Mat, org.opencv.core.Mat, int, double, double, int)
,
blur(org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Size, org.opencv.core.Point, int)
public static void boxFilter(Mat src, Mat dst, int ddepth, Size ksize, Point anchor, boolean normalize)
Blurs an image using the box filter.
The function smoothes an image using the kernel:
K = alpha 1 1 1 *s 1 1 1 1 1 *s 1 1.................. 1 1 1 *s 1 1
where
alpha = 1/(ksize.width*ksize.height) when 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 "integral".
src
- input image.dst
- output image of the same size and type as src
.ddepth
- the output image depth (-1 to use src.depth()
).ksize
- blurring kernel size.anchor
- anchor point; default value Point(-1,-1)
means
that the anchor is at the kernel center.normalize
- flag, specifying whether the kernel is normalized by its
area or not.GaussianBlur(org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Size, double, double, int)
,
medianBlur(org.opencv.core.Mat, org.opencv.core.Mat, int)
,
integral(org.opencv.core.Mat, org.opencv.core.Mat, int)
,
bilateralFilter(org.opencv.core.Mat, org.opencv.core.Mat, int, double, double, int)
,
blur(org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Size, org.opencv.core.Point, int)
public static void boxFilter(Mat src, Mat dst, int ddepth, Size ksize, Point anchor, boolean normalize, int borderType)
Blurs an image using the box filter.
The function smoothes an image using the kernel:
K = alpha 1 1 1 *s 1 1 1 1 1 *s 1 1.................. 1 1 1 *s 1 1
where
alpha = 1/(ksize.width*ksize.height) when 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 "integral".
src
- input image.dst
- output image of the same size and type as src
.ddepth
- the output image depth (-1 to use src.depth()
).ksize
- blurring kernel size.anchor
- anchor point; default value Point(-1,-1)
means
that the anchor is at the kernel center.normalize
- flag, specifying whether the kernel is normalized by its
area or not.borderType
- border mode used to extrapolate pixels outside of the
image.GaussianBlur(org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Size, double, double, int)
,
medianBlur(org.opencv.core.Mat, org.opencv.core.Mat, int)
,
integral(org.opencv.core.Mat, org.opencv.core.Mat, int)
,
bilateralFilter(org.opencv.core.Mat, org.opencv.core.Mat, int, double, double, int)
,
blur(org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Size, org.opencv.core.Point, int)
public static void calcBackProject(java.util.List<Mat> images, MatOfInt channels, Mat hist, Mat dst, MatOfFloat ranges, double scale)
Calculates the back projection of a histogram.
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:
This is an approximate algorithm of the "CamShift" color object tracker.
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.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.hist
- Input histogram that can be dense or sparse.dst
- a dstranges
- Array of arrays of the histogram bin boundaries in each
dimension. See "calcHist".scale
- Optional scale factor for the output back projection.calcHist(java.util.List<org.opencv.core.Mat>, org.opencv.core.MatOfInt, org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.MatOfInt, org.opencv.core.MatOfFloat, boolean)
public static void calcHist(java.util.List<Mat> images, MatOfInt channels, Mat mask, Mat hist, MatOfInt histSize, MatOfFloat ranges)
Calculates a histogram of a set of arrays.
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 correspondinginput arrays at the same location. The sample below
shows how to compute a 2D Hue-Saturation histogram for a color image.
// C++ code:
#include
#include
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, CV_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
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:
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.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.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.hist
- Output histogram, which is a dense or sparse dims
-dimensional array.histSize
- Array of histogram sizes in each dimension.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 L_0 of the 0-th histogram bin and the
upper (exclusive) boundary U_(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: L_0, U_0=L_1, U_1=L_2,...,
U_(histSize[i]-2)=L_(histSize[i]-1), U_(histSize[i]-1). The array
elements, that are not between L_0 and U_(histSize[i]-1),
are not counted in the histogram.public static void calcHist(java.util.List<Mat> images, MatOfInt channels, Mat mask, Mat hist, MatOfInt histSize, MatOfFloat ranges, boolean accumulate)
Calculates a histogram of a set of arrays.
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 correspondinginput arrays at the same location. The sample below
shows how to compute a 2D Hue-Saturation histogram for a color image.
// C++ code:
#include
#include
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, CV_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
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:
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.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.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.hist
- Output histogram, which is a dense or sparse dims
-dimensional array.histSize
- Array of histogram sizes in each dimension.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 L_0 of the 0-th histogram bin and the
upper (exclusive) boundary U_(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: L_0, U_0=L_1, U_1=L_2,...,
U_(histSize[i]-2)=L_(histSize[i]-1), U_(histSize[i]-1). The array
elements, that are not between L_0 and U_(histSize[i]-1),
are not counted in the histogram.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.public static void Canny(Mat image, Mat edges, double threshold1, double threshold2)
Finds edges in an image using the [Canny86] algorithm.
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:
image
- single-channel 8-bit input image.edges
- output edge map; it has the same size and type as
image
.threshold1
- first threshold for the hysteresis procedure.threshold2
- second threshold for the hysteresis procedure.public static void Canny(Mat image, Mat edges, double threshold1, double threshold2, int apertureSize, boolean L2gradient)
Finds edges in an image using the [Canny86] algorithm.
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:
image
- single-channel 8-bit input image.edges
- output edge map; it has the same size and type as
image
.threshold1
- first threshold for the hysteresis procedure.threshold2
- second threshold for the hysteresis procedure.apertureSize
- aperture size for the "Sobel" operator.L2gradient
- a flag, indicating whether a more accurate L_2
norm =sqrt((dI/dx)^2 + (dI/dy)^2) should be used to calculate the
image gradient magnitude (L2gradient=true
), or whether the
default L_1 norm =|dI/dx|+|dI/dy| is enough
(L2gradient=false
).public static double compareHist(Mat H1, Mat H2, int method)
Compares two histograms.
The functions compareHist
compare two dense or two sparse
histograms using the specified method:
method=CV_COMP_CORREL
)
d(H_1,H_2) = (sum_I(H_1(I) - H_1")(H_2(I) - H_2"))/(sqrt(sum_I(H_1(I) - H_1")^2 sum_I(H_2(I) - H_2")^2))
where
H_k" = 1/(N) sum _J H_k(J)
and N is a total number of histogram bins.
method=CV_COMP_CHISQR
)
d(H_1,H_2) = sum _I((H_1(I)-H_2(I))^2)/(H_1(I))
method=CV_COMP_INTERSECT
)
d(H_1,H_2) = sum _I min(H_1(I), H_2(I))
method=CV_COMP_BHATTACHARYYA
or
method=CV_COMP_HELLINGER
). In fact, OpenCV computes Hellinger
distance, which is related to Bhattacharyya coefficient.
d(H_1,H_2) = sqrt(1 - frac(1)(sqrt(H_1" H_2" N^2)) sum_I sqrt(H_1(I) * H_2(I)))
The function returns 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 "EMD" function.
H1
- First compared histogram.H2
- Second compared histogram of the same size as H1
.method
- Comparison method that could be one of the following:
CV_COMP_BHATTACHARYYA
public static double contourArea(Mat contour)
Calculates a contour area.
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:
// C++ code:
vector
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
approxPolyDP(contour, approx, 5, true);
double area1 = contourArea(approx);
cout << "area0 =" << area0 << endl <<
"area1 =" << area1 << endl <<
"approx poly vertices" << approx.size() << endl;
contour
- Input vector of 2D points (contour vertices), stored in
std.vector
or Mat
.public static double contourArea(Mat contour, boolean oriented)
Calculates a contour area.
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:
// C++ code:
vector
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
approxPolyDP(contour, approx, 5, true);
double area1 = contourArea(approx);
cout << "area0 =" << area0 << endl <<
"area1 =" << area1 << endl <<
"approx poly vertices" << approx.size() << endl;
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.public static void convertMaps(Mat map1, Mat map2, Mat dstmap1, Mat dstmap2, int dstmap1type)
Converts image transformation maps from one representation to another.
The function converts a pair of maps for "remap" from one representation to
another. The following options ((map1.type(), map2.type())
-> (dstmap1.type(), dstmap2.type())
) are supported:
nninterpolation=false
)
contains indices in the interpolation tables.
map1
- The first input map of type CV_16SC2
,
CV_32FC1
, or CV_32FC2
.map2
- The second input map of type CV_16UC1
,
CV_32FC1
, or none (empty matrix), respectively.dstmap1
- The first output map that has the type dstmap1type
and the same size as src
.dstmap2
- The second output map.dstmap1type
- Type of the first output map that should be
CV_16SC2
, CV_32FC1
, or CV_32FC2
.remap(org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat, int, int, org.opencv.core.Scalar)
,
initUndistortRectifyMap(org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Size, int, org.opencv.core.Mat, org.opencv.core.Mat)
,
undistort(org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat)
public static void convertMaps(Mat map1, Mat map2, Mat dstmap1, Mat dstmap2, int dstmap1type, boolean nninterpolation)
Converts image transformation maps from one representation to another.
The function converts a pair of maps for "remap" from one representation to
another. The following options ((map1.type(), map2.type())
-> (dstmap1.type(), dstmap2.type())
) are supported:
nninterpolation=false
)
contains indices in the interpolation tables.
map1
- The first input map of type CV_16SC2
,
CV_32FC1
, or CV_32FC2
.map2
- The second input map of type CV_16UC1
,
CV_32FC1
, or none (empty matrix), respectively.dstmap1
- The first output map that has the type dstmap1type
and the same size as src
.dstmap2
- The second output map.dstmap1type
- Type of the first output map that should be
CV_16SC2
, CV_32FC1
, or CV_32FC2
.nninterpolation
- Flag indicating whether the fixed-point maps are used
for the nearest-neighbor or for a more complex interpolation.remap(org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat, int, int, org.opencv.core.Scalar)
,
initUndistortRectifyMap(org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Size, int, org.opencv.core.Mat, org.opencv.core.Mat)
,
undistort(org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat)
public static void convexHull(MatOfPoint points, MatOfInt hull)
Finds the convex hull of a point set.
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:
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.public static void convexHull(MatOfPoint points, MatOfInt hull, boolean clockwise)
Finds the convex hull of a point set.
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:
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.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.public static void convexityDefects(MatOfPoint contour, MatOfInt convexhull, MatOfInt4 convexityDefects)
Finds the convexity defects of a contour.
The function finds all convexity defects of the input contour and returns a
sequence of the CvConvexityDefect
structures, where
CvConvexityDetect
is defined as:
// C++ code:
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:
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 CvConvexityDefect
structure - see below.public static void copyMakeBorder(Mat src, Mat dst, int top, int bottom, int left, int right, int borderType)
Forms a border around an image.
The function copies the source image into the middle of the destination
image. The areas to the left, to the right, above and below the copied source
image will be filled with extrapolated pixels. This is not what
"FilterEngine" or filtering functions based on it do (they extrapolate pixels
on-fly), but what other more complex functions, including your own, may do to
simplify image boundary handling.
The function supports the mode when src
is already in the middle
of dst
. In this case, the function does not copy
src
itself but simply constructs the border, for example:
// C++ code:
// let border be the same in all directions
int border=2;
// constructs a larger image to fit both the image and the border
Mat gray_buf(rgb.rows + border*2, rgb.cols + border*2, rgb.depth());
// select the middle part of it w/o copying data
Mat gray(gray_canvas, Rect(border, border, rgb.cols, rgb.rows));
// convert image from RGB to grayscale
cvtColor(rgb, gray, CV_RGB2GRAY);
// form a border in-place
copyMakeBorder(gray, gray_buf, border, border,
border, border, BORDER_REPLICATE);
// now do some custom filtering......
Note:
When the source image is a part (ROI) of a bigger image, the function will
try to use the pixels outside of the ROI to form a border. To disable this
feature and always do extrapolation, as if src
was not a ROI,
use borderType | BORDER_ISOLATED
.
src
- Source image.dst
- Destination image of the same type as src
and the
size Size(src.cols+left+right, src.rows+top+bottom)
.top
- a topbottom
- a bottomleft
- a leftright
- Parameter specifying how many pixels in each direction from the
source image rectangle to extrapolate. For example, top=1, bottom=1,
left=1, right=1
mean that 1 pixel-wide border needs to be built.borderType
- Border type. See "borderInterpolate" for details.borderInterpolate(int, int, int)
public static void copyMakeBorder(Mat src, Mat dst, int top, int bottom, int left, int right, int borderType, Scalar value)
Forms a border around an image.
The function copies the source image into the middle of the destination
image. The areas to the left, to the right, above and below the copied source
image will be filled with extrapolated pixels. This is not what
"FilterEngine" or filtering functions based on it do (they extrapolate pixels
on-fly), but what other more complex functions, including your own, may do to
simplify image boundary handling.
The function supports the mode when src
is already in the middle
of dst
. In this case, the function does not copy
src
itself but simply constructs the border, for example:
// C++ code:
// let border be the same in all directions
int border=2;
// constructs a larger image to fit both the image and the border
Mat gray_buf(rgb.rows + border*2, rgb.cols + border*2, rgb.depth());
// select the middle part of it w/o copying data
Mat gray(gray_canvas, Rect(border, border, rgb.cols, rgb.rows));
// convert image from RGB to grayscale
cvtColor(rgb, gray, CV_RGB2GRAY);
// form a border in-place
copyMakeBorder(gray, gray_buf, border, border,
border, border, BORDER_REPLICATE);
// now do some custom filtering......
Note:
When the source image is a part (ROI) of a bigger image, the function will
try to use the pixels outside of the ROI to form a border. To disable this
feature and always do extrapolation, as if src
was not a ROI,
use borderType | BORDER_ISOLATED
.
src
- Source image.dst
- Destination image of the same type as src
and the
size Size(src.cols+left+right, src.rows+top+bottom)
.top
- a topbottom
- a bottomleft
- a leftright
- Parameter specifying how many pixels in each direction from the
source image rectangle to extrapolate. For example, top=1, bottom=1,
left=1, right=1
mean that 1 pixel-wide border needs to be built.borderType
- Border type. See "borderInterpolate" for details.value
- Border value if borderType==BORDER_CONSTANT
.borderInterpolate(int, int, int)
public static void cornerEigenValsAndVecs(Mat src, Mat dst, int blockSize, int ksize)
Calculates eigenvalues and eigenvectors of image blocks for corner detection.
For every pixel p, the function cornerEigenValsAndVecs
considers a blockSize
x blockSize
neighborhood S(p). It calculates the covariation matrix of
derivatives over the neighborhood as:
M = sum(by: S(p))(dI/dx)^2 sum(by: S(p))(dI/dx dI/dy) sum(by: S(p))(dI/dx dI/dy) sum(by: S(p))(dI/dy)^2
where the derivatives are computed using the "Sobel" operator.
After that, it finds eigenvectors and eigenvalues of M and stores them in the destination image as (lambda_1, lambda_2, x_1, y_1, x_2, y_2) where
The output of the function can be used for robust edge or corner detection.
Note:
src
- Input single-channel 8-bit or floating-point image.dst
- Image to store the results. It has the same size as
src
and the type CV_32FC(6)
.blockSize
- Neighborhood size (see details below).ksize
- Aperture parameter for the "Sobel" operator.cornerHarris(org.opencv.core.Mat, org.opencv.core.Mat, int, int, double, int)
,
cornerMinEigenVal(org.opencv.core.Mat, org.opencv.core.Mat, int, int, int)
,
preCornerDetect(org.opencv.core.Mat, org.opencv.core.Mat, int, int)
public static void cornerEigenValsAndVecs(Mat src, Mat dst, int blockSize, int ksize, int borderType)
Calculates eigenvalues and eigenvectors of image blocks for corner detection.
For every pixel p, the function cornerEigenValsAndVecs
considers a blockSize
x blockSize
neighborhood S(p). It calculates the covariation matrix of
derivatives over the neighborhood as:
M = sum(by: S(p))(dI/dx)^2 sum(by: S(p))(dI/dx dI/dy) sum(by: S(p))(dI/dx dI/dy) sum(by: S(p))(dI/dy)^2
where the derivatives are computed using the "Sobel" operator.
After that, it finds eigenvectors and eigenvalues of M and stores them in the destination image as (lambda_1, lambda_2, x_1, y_1, x_2, y_2) where
The output of the function can be used for robust edge or corner detection.
Note:
src
- Input single-channel 8-bit or floating-point image.dst
- Image to store the results. It has the same size as
src
and the type CV_32FC(6)
.blockSize
- Neighborhood size (see details below).ksize
- Aperture parameter for the "Sobel" operator.borderType
- Pixel extrapolation method. See "borderInterpolate".cornerHarris(org.opencv.core.Mat, org.opencv.core.Mat, int, int, double, int)
,
cornerMinEigenVal(org.opencv.core.Mat, org.opencv.core.Mat, int, int, int)
,
preCornerDetect(org.opencv.core.Mat, org.opencv.core.Mat, int, int)
public static void cornerHarris(Mat src, Mat dst, int blockSize, int ksize, double k)
Harris edge detector.
The function runs the Harris edge detector on the image. Similarly to "cornerMinEigenVal" and "cornerEigenValsAndVecs", for each pixel (x, y) it calculates a 2x2 gradient covariance matrix M^((x,y)) over a blockSize x blockSize neighborhood. Then, it computes the following characteristic:
dst(x,y) = det M^((x,y)) - k * (tr M^((x,y)))^2
Corners in the image can be found as the local maxima of this response map.
src
- Input single-channel 8-bit or floating-point image.dst
- Image to store the Harris detector responses. It has the type
CV_32FC1
and the same size as src
.blockSize
- Neighborhood size (see the details on "cornerEigenValsAndVecs").ksize
- Aperture parameter for the "Sobel" operator.k
- Harris detector free parameter. See the formula below.public static void cornerHarris(Mat src, Mat dst, int blockSize, int ksize, double k, int borderType)
Harris edge detector.
The function runs the Harris edge detector on the image. Similarly to "cornerMinEigenVal" and "cornerEigenValsAndVecs", for each pixel (x, y) it calculates a 2x2 gradient covariance matrix M^((x,y)) over a blockSize x blockSize neighborhood. Then, it computes the following characteristic:
dst(x,y) = det M^((x,y)) - k * (tr M^((x,y)))^2
Corners in the image can be found as the local maxima of this response map.
src
- Input single-channel 8-bit or floating-point image.dst
- Image to store the Harris detector responses. It has the type
CV_32FC1
and the same size as src
.blockSize
- Neighborhood size (see the details on "cornerEigenValsAndVecs").ksize
- Aperture parameter for the "Sobel" operator.k
- Harris detector free parameter. See the formula below.borderType
- Pixel extrapolation method. See "borderInterpolate".public static void cornerMinEigenVal(Mat src, Mat dst, int blockSize)
Calculates the minimal eigenvalue of gradient matrices for corner detection.
The function is similar to "cornerEigenValsAndVecs" but it calculates and stores only the minimal eigenvalue of the covariance matrix of derivatives, that is, min(lambda_1, lambda_2) in terms of the formulae in the "cornerEigenValsAndVecs" description.
src
- Input single-channel 8-bit or floating-point image.dst
- Image to store the minimal eigenvalues. It has the type
CV_32FC1
and the same size as src
.blockSize
- Neighborhood size (see the details on "cornerEigenValsAndVecs").public static void cornerMinEigenVal(Mat src, Mat dst, int blockSize, int ksize)
Calculates the minimal eigenvalue of gradient matrices for corner detection.
The function is similar to "cornerEigenValsAndVecs" but it calculates and stores only the minimal eigenvalue of the covariance matrix of derivatives, that is, min(lambda_1, lambda_2) in terms of the formulae in the "cornerEigenValsAndVecs" description.
src
- Input single-channel 8-bit or floating-point image.dst
- Image to store the minimal eigenvalues. It has the type
CV_32FC1
and the same size as src
.blockSize
- Neighborhood size (see the details on "cornerEigenValsAndVecs").ksize
- Aperture parameter for the "Sobel" operator.public static void cornerMinEigenVal(Mat src, Mat dst, int blockSize, int ksize, int borderType)
Calculates the minimal eigenvalue of gradient matrices for corner detection.
The function is similar to "cornerEigenValsAndVecs" but it calculates and stores only the minimal eigenvalue of the covariance matrix of derivatives, that is, min(lambda_1, lambda_2) in terms of the formulae in the "cornerEigenValsAndVecs" description.
src
- Input single-channel 8-bit or floating-point image.dst
- Image to store the minimal eigenvalues. It has the type
CV_32FC1
and the same size as src
.blockSize
- Neighborhood size (see the details on "cornerEigenValsAndVecs").ksize
- Aperture parameter for the "Sobel" operator.borderType
- Pixel extrapolation method. See "borderInterpolate".public static void cornerSubPix(Mat image, MatOfPoint2f corners, Size winSize, Size zeroZone, TermCriteria criteria)
Refines the corner locations.
The function iterates to find the sub-pixel accurate location of corners or radial saddle points, as shown on the figure below.
Sub-pixel accurate corner locator is based on the observation that every vector from the center q to a point p located within a neighborhood of q is orthogonal to the image gradient at p subject to image and measurement noise. Consider the expression:
epsilon _i = (DI_(p_i))^T * (q - p_i)
where (DI_(p_i)) is an image gradient at one of the points p_i in a neighborhood of q. The value of q is to be found so that epsilon_i is minimized. A system of equations may be set up with epsilon_i set to zero:
sum _i(DI_(p_i) * (DI_(p_i))^T) - sum _i(DI_(p_i) * (DI_(p_i))^T * p_i)
where the gradients are summed within a neighborhood ("search window") of q. Calling the first gradient term G and the second gradient term b gives:
q = G^(-1) * b
The algorithm sets the center of the neighborhood window at this new center q and then iterates until the center stays within a set threshold.
image
- Input image.corners
- Initial coordinates of the input corners and refined
coordinates provided for output.winSize
- Half of the side length of the search window. For example, if
winSize=Size(5,5)
, then a 5*2+1 x 5*2+1 = 11 x 11
search window is used.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.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.public static void createHanningWindow(Mat dst, Size winSize, int type)
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.
An example is shown below:
// C++ code:
// create hanning window of size 100x100 and type CV_32F
Mat hann;
createHanningWindow(hann, Size(100, 100), CV_32F);
dst
- Destination array to place Hann coefficients inwinSize
- The window size specificationstype
- Created array typephaseCorrelate(org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat)
public static void cvtColor(Mat src, Mat dst, int code)
Converts an image from one color space to another.
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:
CV_8U
images
CV_16U
images
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-> 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:
// C++ code:
img *= 1./255;
cvtColor(img, img, CV_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:
CV_BGR2GRAY, CV_RGB2GRAY, CV_GRAY2BGR,
CV_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:
RGB[A] to Gray: Y <- 0.299 * R + 0.587 * G + 0.114 * B
and
Gray to RGB[A]: R <- Y, G <- Y, B <- Y, A <- max(ChannelRange)
The conversion from a RGB image to gray is done with:
// C++ code:
cvtColor(src, bwsrc, CV_RGB2GRAY);
More advanced channel reordering can also be done with "mixChannels".
CV_BGR2XYZ, CV_RGB2XYZ, CV_XYZ2BGR, CV_XYZ2RGB
):
X Z ltBR gt <- 0.412453 0.357580 0.180423 0.212671 0.715160 0.072169 0.019334 0.119193 0.950227 ltBR gt * R B ltBR gt
R B ltBR gt <- 3.240479 -1.53715 -0.498535 -0.969256 1.875991 0.041556 0.055648 -0.204043 1.057311 ltBR gt * X Z ltBR gt
X, Y and Z cover the whole value range (in case of floating-point images, Z may exceed 1).
CV_BGR2YCrCb,
CV_RGB2YCrCb, CV_YCrCb2BGR, CV_YCrCb2RGB
)
Y <- 0.299 * R + 0.587 * G + 0.114 * B
Cr <- (R-Y) * 0.713 + delta
Cb <- (B-Y) * 0.564 + delta
R <- Y + 1.403 * (Cr - delta)
G <- Y - 0.714 * (Cr - delta) - 0.344 * (Cb - delta)
B <- Y + 1.773 * (Cb - delta)
where
delta = <= ft (128 for 8-bit images 32768 for 16-bit images 0.5 for floating-point images right.
Y, Cr, and Cb cover the whole value range.
CV_BGR2HSV, CV_RGB2HSV, CV_HSV2BGR,
CV_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.
V <- max(R,G,B)
S <- (V-min(R,G,B))/(V) if V != 0; 0 otherwise
H <- (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 H<0 then H <- H+360. On output 0 <= V <= 1, 0 <= S <= 1, 0 <= H <= 360.
The values are then converted to the destination data type:
V <- 255 V, S <- 255 S, H <- H/2(to fit to 0 to 255)
V <- 65535 V, S <- 65535 S, H <- H
CV_BGR2HLS, CV_RGB2HLS, CV_HLS2BGR,
CV_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.
V_(max) <- (max)(R,G,B)
V_(min) <- (min)(R,G,B)
L <- (V_(max) + V_(min))/2
S <- fork ((V_(max) - V_(min))/(V_(max) + V_(min)))(if L < 0.5)<BR>((V_(max) - V_(min))/(2 - (V_(max) + V_(min))))(if L >= 0.5)
H <- forkthree ((60(G - B))/(S))(if V_(max)=R)<BR>((120+60(B - R))/(S))(if V_(max)=G)<BR>((240+60(R - G))/(S))(if V_(max)=B)
If H<0 then H <- H+360. On output 0 <= L <= 1, 0 <= S <= 1, 0 <= H <= 360.
The values are then converted to the destination data type:
V <- 255 * V, S <- 255 * S, H <- H/2(to fit to 0 to 255)
V <- 65535 * V, S <- 65535 * S, H <- H
CV_BGR2Lab, CV_RGB2Lab, CV_Lab2BGR,
CV_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.
[X Y Z] <- |0.412453 0.357580 0.180423| |0.212671 0.715160 0.072169| |0.019334 0.119193 0.950227|
X <- X/X_n, where X_n = 0.950456
Z <- Z/Z_n, where Z_n = 1.088754
L <- 116*Y^(1/3)-16 for Y>0.008856; 903.3*Y for Y <= 0.008856
a <- 500(f(X)-f(Y)) + delta
b <- 200(f(Y)-f(Z)) + delta
where
f(t)= t^(1/3) for t>0.008856; 7.787 t+16/116 for t <= 0.008856
and
delta = 128 for 8-bit images; 0 for floating-point images
This outputs 0 <= L <= 100, -127 <= a <= 127, -127 <= b <= 127. The values are then converted to the destination data type:
L <- L*255/100, a <- a + 128, b <- b + 128
CV_BGR2Luv, CV_RGB2Luv, CV_Luv2BGR,
CV_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.
[X Y Z] <- |0.412453 0.357580 0.180423| |0.212671 0.715160 0.072169| |0.019334 0.119193 0.950227|
L <- 116 Y^(1/3) for Y>0.008856; 903.3 Y for Y <= 0.008856
u' <- 4*X/(X + 15*Y + 3 Z)
v' <- 9*Y/(X + 15*Y + 3 Z)
u <- 13*L*(u' - u_n) where u_n=0.19793943
v <- 13*L*(v' - v_n) where v_n=0.46831096
This outputs 0 <= L <= 100, -134 <= u <= 220, -140 <= v <= 122.
The values are then converted to the destination data type:
L <- 255/100 L, u <- 255/354(u + 134), v <- 255/262(v + 140)
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
CV_BayerBG2BGR, CV_BayerGB2BGR,
CV_BayerRG2BGR, CV_BayerGR2BGR, CV_BayerBG2RGB, CV_BayerGB2RGB,
CV_BayerRG2RGB, CV_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: The output RGB components of a pixel are interpolated
from 1, 2, or
// C++ code:
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
C_1 and
C_2 in the conversion constants CV_Bayer
C_1
C_2 2BGR
and CV_Bayer
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.
src
- input image: 8-bit unsigned, 16-bit unsigned (CV_16UC...
),
or single-precision floating-point.dst
- output image of the same size and depth as src
.code
- color space conversion code (see the description below).public static void cvtColor(Mat src, Mat dst, int code, int dstCn)
Converts an image from one color space to another.
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:
CV_8U
images
CV_16U
images
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-> 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:
// C++ code:
img *= 1./255;
cvtColor(img, img, CV_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:
CV_BGR2GRAY, CV_RGB2GRAY, CV_GRAY2BGR,
CV_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:
RGB[A] to Gray: Y <- 0.299 * R + 0.587 * G + 0.114 * B
and
Gray to RGB[A]: R <- Y, G <- Y, B <- Y, A <- max(ChannelRange)
The conversion from a RGB image to gray is done with:
// C++ code:
cvtColor(src, bwsrc, CV_RGB2GRAY);
More advanced channel reordering can also be done with "mixChannels".
CV_BGR2XYZ, CV_RGB2XYZ, CV_XYZ2BGR, CV_XYZ2RGB
):
X Z ltBR gt <- 0.412453 0.357580 0.180423 0.212671 0.715160 0.072169 0.019334 0.119193 0.950227 ltBR gt * R B ltBR gt
R B ltBR gt <- 3.240479 -1.53715 -0.498535 -0.969256 1.875991 0.041556 0.055648 -0.204043 1.057311 ltBR gt * X Z ltBR gt
X, Y and Z cover the whole value range (in case of floating-point images, Z may exceed 1).
CV_BGR2YCrCb,
CV_RGB2YCrCb, CV_YCrCb2BGR, CV_YCrCb2RGB
)
Y <- 0.299 * R + 0.587 * G + 0.114 * B
Cr <- (R-Y) * 0.713 + delta
Cb <- (B-Y) * 0.564 + delta
R <- Y + 1.403 * (Cr - delta)
G <- Y - 0.714 * (Cr - delta) - 0.344 * (Cb - delta)
B <- Y + 1.773 * (Cb - delta)
where
delta = <= ft (128 for 8-bit images 32768 for 16-bit images 0.5 for floating-point images right.
Y, Cr, and Cb cover the whole value range.
CV_BGR2HSV, CV_RGB2HSV, CV_HSV2BGR,
CV_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.
V <- max(R,G,B)
S <- (V-min(R,G,B))/(V) if V != 0; 0 otherwise
H <- (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 H<0 then H <- H+360. On output 0 <= V <= 1, 0 <= S <= 1, 0 <= H <= 360.
The values are then converted to the destination data type:
V <- 255 V, S <- 255 S, H <- H/2(to fit to 0 to 255)
V <- 65535 V, S <- 65535 S, H <- H
CV_BGR2HLS, CV_RGB2HLS, CV_HLS2BGR,
CV_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.
V_(max) <- (max)(R,G,B)
V_(min) <- (min)(R,G,B)
L <- (V_(max) + V_(min))/2
S <- fork ((V_(max) - V_(min))/(V_(max) + V_(min)))(if L < 0.5)<BR>((V_(max) - V_(min))/(2 - (V_(max) + V_(min))))(if L >= 0.5)
H <- forkthree ((60(G - B))/(S))(if V_(max)=R)<BR>((120+60(B - R))/(S))(if V_(max)=G)<BR>((240+60(R - G))/(S))(if V_(max)=B)
If H<0 then H <- H+360. On output 0 <= L <= 1, 0 <= S <= 1, 0 <= H <= 360.
The values are then converted to the destination data type:
V <- 255 * V, S <- 255 * S, H <- H/2(to fit to 0 to 255)
V <- 65535 * V, S <- 65535 * S, H <- H
CV_BGR2Lab, CV_RGB2Lab, CV_Lab2BGR,
CV_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.
[X Y Z] <- |0.412453 0.357580 0.180423| |0.212671 0.715160 0.072169| |0.019334 0.119193 0.950227|
X <- X/X_n, where X_n = 0.950456
Z <- Z/Z_n, where Z_n = 1.088754
L <- 116*Y^(1/3)-16 for Y>0.008856; 903.3*Y for Y <= 0.008856
a <- 500(f(X)-f(Y)) + delta
b <- 200(f(Y)-f(Z)) + delta
where
f(t)= t^(1/3) for t>0.008856; 7.787 t+16/116 for t <= 0.008856
and
delta = 128 for 8-bit images; 0 for floating-point images
This outputs 0 <= L <= 100, -127 <= a <= 127, -127 <= b <= 127. The values are then converted to the destination data type:
L <- L*255/100, a <- a + 128, b <- b + 128
CV_BGR2Luv, CV_RGB2Luv, CV_Luv2BGR,
CV_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.
[X Y Z] <- |0.412453 0.357580 0.180423| |0.212671 0.715160 0.072169| |0.019334 0.119193 0.950227|
L <- 116 Y^(1/3) for Y>0.008856; 903.3 Y for Y <= 0.008856
u' <- 4*X/(X + 15*Y + 3 Z)
v' <- 9*Y/(X + 15*Y + 3 Z)
u <- 13*L*(u' - u_n) where u_n=0.19793943
v <- 13*L*(v' - v_n) where v_n=0.46831096
This outputs 0 <= L <= 100, -134 <= u <= 220, -140 <= v <= 122.
The values are then converted to the destination data type:
L <- 255/100 L, u <- 255/354(u + 134), v <- 255/262(v + 140)
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
CV_BayerBG2BGR, CV_BayerGB2BGR,
CV_BayerRG2BGR, CV_BayerGR2BGR, CV_BayerBG2RGB, CV_BayerGB2RGB,
CV_BayerRG2RGB, CV_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: The output RGB components of a pixel are interpolated
from 1, 2, or
// C++ code:
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
C_1 and
C_2 in the conversion constants CV_Bayer
C_1
C_2 2BGR
and CV_Bayer
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.
src
- input image: 8-bit unsigned, 16-bit unsigned (CV_16UC...
),
or single-precision floating-point.dst
- output image of the same size and depth as src
.code
- color space conversion code (see the description below).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
.public static void dilate(Mat src, Mat dst, Mat kernel)
Dilates an image by using a specific structuring element.
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:
dst(x,y) = max _((x',y'): element(x',y') != 0) 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.
Note:
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".dst
- output image of the same size and type as src
.kernel
- a kernelerode(org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Point, int, int, org.opencv.core.Scalar)
,
morphologyEx(org.opencv.core.Mat, org.opencv.core.Mat, int, org.opencv.core.Mat, org.opencv.core.Point, int, int, org.opencv.core.Scalar)
public static void dilate(Mat src, Mat dst, Mat kernel, Point anchor, int iterations)
Dilates an image by using a specific structuring element.
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:
dst(x,y) = max _((x',y'): element(x',y') != 0) 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.
Note:
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".dst
- output image of the same size and type as src
.kernel
- a kernelanchor
- position of the anchor within the element; default value
(-1, -1)
means that the anchor is at the element center.iterations
- number of times dilation is applied.erode(org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Point, int, int, org.opencv.core.Scalar)
,
morphologyEx(org.opencv.core.Mat, org.opencv.core.Mat, int, org.opencv.core.Mat, org.opencv.core.Point, int, int, org.opencv.core.Scalar)
public static void dilate(Mat src, Mat dst, Mat kernel, Point anchor, int iterations, int borderType, Scalar borderValue)
Dilates an image by using a specific structuring element.
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:
dst(x,y) = max _((x',y'): element(x',y') != 0) 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.
Note:
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".dst
- output image of the same size and type as src
.kernel
- a kernelanchor
- position of the anchor within the element; default value
(-1, -1)
means that the anchor is at the element center.iterations
- number of times dilation is applied.borderType
- pixel extrapolation method (see "borderInterpolate" for
details).borderValue
- border value in case of a constant border (see
"createMorphologyFilter" for details).erode(org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Mat, org.opencv.core.Point, int, int, org.opencv.core.Scalar)
,
morphologyEx(org.opencv.core.Mat, org.opencv.core.Mat, int, org.opencv.core.Mat, org.opencv.core.Point, int, int, org.opencv.core.Scalar)
public static void distanceTransform(Mat src, Mat dst, int distanceType, int maskSize)
Calculates the distance to the closest zero pixel for each pixel of the source image.
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 5x 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 5x 5 mask gives more
accurate results). For a
,b
, and c
,
OpenCV uses the values suggested in the original paper:
============== =================== ======================
CV_DIST_C
(3x 3) a = 1, b = 1 \
============== =================== ======================
CV_DIST_L1
(3x 3) a = 1, b = 2 \
CV_DIST_L2
(3x 3) a=0.955, b=1.3693 \
CV_DIST_L2
(5x 5) a=1, b=1.4, c=2.1969 \
============== =================== ======================
Typically, for a fast, coarse distance estimation CV_DIST_L2
, a
3x 3 mask is used. For a more accurate distance estimation
CV_DIST_L2
, a 5x 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 (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 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:
src
- 8-bit, single-channel (binary) source image.dst
- Output image with calculated distances. It is a 32-bit
floating-point, single-channel image of the same size as src
.distanceType
- Type of distance. It can be CV_DIST_L1,
CV_DIST_L2
, or CV_DIST_C
.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 3x 3 mask
gives the same result as 5x 5 or any larger aperture.public static void distanceTransformWithLabels(Mat src, Mat dst, Mat labels, int distanceType, int maskSize)
Calculates the distance to the closest zero pixel for each pixel of the source image.
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 5x 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 5x 5 mask gives more
accurate results). For a
,b
, and c
,
OpenCV uses the values suggested in the original paper:
============== =================== ======================
CV_DIST_C
(3x 3) a = 1, b = 1 \
============== =================== ======================
CV_DIST_L1
(3x 3) a = 1, b = 2 \
CV_DIST_L2
(3x 3) a=0.955, b=1.3693 \
CV_DIST_L2
(5x 5) a=1, b=1.4, c=2.1969 \
============== =================== ======================
Typically, for a fast, coarse distance estimation CV_DIST_L2
, a
3x 3 mask is used. For a more accurate distance estimation
CV_DIST_L2
, a 5x 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 (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 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:
src
- 8-bit, single-channel (binary) source image.dst
- Output image with calculated distances. It is a 32-bit
floating-point, single-channel image of the same size as src
.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.distanceType
- Type of distance. It can be CV_DIST_L1,
CV_DIST_L2
, or CV_DIST_C
.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 3x 3 mask
gives the same result as 5x 5 or any larger aperture.public static void distanceTransformWithLabels(Mat src, Mat dst, Mat labels, int distanceType, int maskSize, int labelType)
Calculates the distance to the closest zero pixel for each pixel of the source image.
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 5x 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 5x 5 mask gives more
accurate results). For a
,b
, and c
,
OpenCV uses the values suggested in the original paper:
============== =================== ======================
CV_DIST_C
(3x 3) a = 1, b = 1 \
============== =================== ======================
CV_DIST_L1
(3x 3) a = 1, b = 2 \
CV_DIST_L2
(3x 3) a=0.955, b=1.3693 \
CV_DIST_L2
(5x 5) a=1, b=1.4, c=2.1969 \
============== =================== ======================
Typically, for a fast, coarse distance estimation CV_DIST_L2
, a
3x 3 mask is used. For a more accurate distance estimation
CV_DIST_L2
, a 5x 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 (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 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:
src
- 8-bit, single-channel (binary) source image.dst
- Output image with calculated distances. It is a 32-bit
floating-point, single-channel image of the same size as src
.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.distanceType
- Type of distance. It can be CV_DIST_L1,
CV_DIST_L2
, or CV_DIST_C
.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 3x 3 mask
gives the same result as 5x 5 or any larger aperture.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.public static void drawContours(Mat image, java.util.List<MatOfPoint> contours, int contourIdx, Scalar color)
Draws contours outlines or filled contours.
The function draws contour outlines in the image if thickness >= 0
or fills the area bounded by the contours ifthickness<0. The
example below shows how to retrieve connected components from the binary
image and label them:
// C++ code:
#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
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:
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.public static void drawContours(Mat image, java.util.List<MatOfPoint> contours, int contourIdx, Scalar color, int thickness)
Draws contours outlines or filled contours.
The function draws contour outlines in the image if thickness >= 0
or fills the area bounded by the contours ifthickness<0. The
example below shows how to retrieve connected components from the binary
image and label them:
// C++ code:
#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
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:
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.public static void drawContours(Mat image, java.util.List<MatOfPoint> contours, int contourIdx, Scalar color, int thickness, int lineType, Mat hierarchy, int maxLevel, Point offset)
Draws contours outlines or filled contours.
The function draws contour outlines in the image if thickness >= 0
or fills the area bounded by the contours ifthickness<0. The
example below shows how to retrieve connected components from the binary
image and label them:
// C++ code:
#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
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:
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