本文整理汇总了C#中Mat.Type方法的典型用法代码示例。如果您正苦于以下问题:C# Mat.Type方法的具体用法?C# Mat.Type怎么用?C# Mat.Type使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Mat
的用法示例。
在下文中一共展示了Mat.Type方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Niblack
/// <summary>
/// Niblackの手法による二値化処理を行う。
/// </summary>
/// <param name="imgSrc">入力画像</param>
/// <param name="imgDst">出力画像</param>
/// <param name="kernelSize">局所領域のサイズ</param>
/// <param name="k">係数</param>
#else
/// <summary>
/// Binarizes by Niblack's method
/// </summary>
/// <param name="src">Input image</param>
/// <param name="dst">Output image</param>
/// <param name="kernelSize">Window size</param>
/// <param name="k">Adequate coefficient</param>
#endif
public static void Niblack(Mat src, Mat dst, int kernelSize, double k)
{
if (src == null)
throw new ArgumentNullException("src");
if (dst == null)
throw new ArgumentNullException("dst");
// グレースケールのみ
if (src.Type() != MatType.CV_8UC1)
throw new ArgumentException("src must be gray scale image");
if (dst.Type() != MatType.CV_8UC1)
throw new ArgumentException("dst must be gray scale image");
// サイズのチェック
if (kernelSize < 3)
throw new ArgumentOutOfRangeException("kernelSize", "size must be 3 and above");
if (kernelSize % 2 == 0)
throw new ArgumentOutOfRangeException("kernelSize", "size must be odd number");
int width = src.Width;
int height = src.Height;
dst.Create(src.Size(), src.Type());
using (var tSrcMat = new MatOfByte(src))
using (var tDstMat = new MatOfByte(dst))
{
var tSrc = tSrcMat.GetIndexer();
var tDst = tDstMat.GetIndexer();
//for (int y = 0; y < gray.Height; y++)
MyParallel.For(0, height, delegate(int y)
{
for (int x = 0; x < width; x++)
{
double m, s;
MeanStddev(src, x, y, kernelSize, out m, out s);
double threshold = m + k * s;
if (tSrc[y, x] < threshold)
tDst[y, x] = 0;
else
tDst[y, x] = 255;
}
}
);
}
}
示例2: Run
public void Run()
{
// Load left&right images
using (var imgLeft = new IplImage(FilePath.Image.TsukubaLeft, LoadMode.GrayScale))
using (var imgRight = new IplImage(FilePath.Image.TsukubaRight, LoadMode.GrayScale))
{
// output image buffers
using (var dispBM = new IplImage(imgLeft.Size, BitDepth.S16, 1))
using (var dispLeft = new IplImage(imgLeft.Size, BitDepth.S16, 1))
using (var dispRight = new IplImage(imgLeft.Size, BitDepth.S16, 1))
using (var dstBM = new IplImage(imgLeft.Size, BitDepth.U8, 1))
using (var dstGC = new IplImage(imgLeft.Size, BitDepth.U8, 1))
using (var dstAux = new IplImage(imgLeft.Size, BitDepth.U8, 1))
using (var dstSGBM = new Mat())
{
// measures distance and scales
const int sad = 3;
using (var stateBM = new CvStereoBMState(StereoBMPreset.Basic, 16))
using (var stateGC = new CvStereoGCState(16, 2))
using (var sgbm = new StereoSGBM() // C++
{
MinDisparity = 0,
NumberOfDisparities = 32,
PreFilterCap = 63,
SADWindowSize = sad,
P1 = 8 * imgLeft.NChannels * sad * sad,
P2 = 32 * imgLeft.NChannels * sad * sad,
UniquenessRatio = 10,
SpeckleWindowSize = 100,
SpeckleRange = 32,
Disp12MaxDiff = 1,
FullDP = false,
})
{
Cv.FindStereoCorrespondenceBM(imgLeft, imgRight, dispBM, stateBM);
Cv.FindStereoCorrespondenceGC(imgLeft, imgRight, dispLeft, dispRight, stateGC, false);
Cv.FindStereoCorrespondence(imgLeft, imgRight, DisparityMode.Birchfield, dstAux, 50, 25, 5, 12, 15, 25); // cvaux
sgbm.Compute(new Mat(imgLeft), new Mat(imgRight), dstSGBM);
Cv.ConvertScale(dispBM, dstBM, 1);
Cv.ConvertScale(dispLeft, dstGC, -16);
Cv.ConvertScale(dstAux, dstAux, 16);
dstSGBM.ConvertTo(dstSGBM, dstSGBM.Type(), 32, 0);
using (new CvWindow("Stereo Correspondence (BM)", dstBM))
using (new CvWindow("Stereo Correspondence (GC)", dstGC))
using (new CvWindow("Stereo Correspondence (cvaux)", dstAux))
using (new CvWindow("Stereo Correspondence (SGBM)", dstSGBM.ToIplImage()))
{
Cv.WaitKey();
}
}
}
}
}
示例3: Main
public static void Main(string[] args)
{
Mat src = new Mat("TestImages/2013-12-27-09G37_TRB.jpg", LoadMode.Color);
src = src.Resize (new Size (420, 625));
Mat srcGrey = src.CvtColor(ColorConversion.BgrToGray);
Mat dst = new Mat ();
Point[][] contours;
Mat invertColour = new Mat (src.Rows, src.Cols, src.Type(), new Scalar(255, 255, 255) );
HiearchyIndex[] hierarchy;
Mat contoursLines = new Mat(src.Rows, src.Cols, src.Type());
// InputArray element = Cv2.GetStructuringElement (StructuringElementShape.Ellipse, new Size (16, 16));
// Mat thresh = srcGrey.Threshold (230, 255, ThresholdType.Binary).Dilate(element);
Mat thresh = srcGrey.Threshold (230, 255, ThresholdType.Binary);
Cv2.FindContours (thresh, out contours, out hierarchy, ContourRetrieval.Tree, ContourChain.ApproxSimple);
// Find center of mass in contour
Moments center = Cv2.Moments (contours [0]);
// Convert moment matrix to X/Y coords
int x = (int) (center.M10 / center.M00);
int y = (int) (center.M01 / center.M00);
src.Circle (new Point (x, y), 5, CvColor.CornflowerBlue, 2);
src.DrawContours (contours, 1, CvColor.Green, 2);
bool intersect = IsIntersecting (selector[0], selector[1], contours[1][0], contours[1][1]);
using (var orig = new Window ("src image", src))
{
orig.OnMouseCallback += new CvMouseCallback(MouseMove);
Cv2.WaitKey();
}
}
示例4: Update
// Update is called once per frame
void Update () {
if (isVid) {
cap.Read (frame);
}
if (!frame.Empty()){
bkrnd_win = frame.Clone(bkrnd_rect);
//calc the hsv histogram inside that window
Rangef[] ranges = { new Rangef (0, 180), new Rangef (0, 256) };
bkrnd_win = bkrnd_win.CvtColor(ColorConversionCodes.BGR2HSV);
frame_hsv = frame.CvtColor (ColorConversionCodes.BGR2HSV);
Cv2.CalcHist (new Mat[]{ bkrnd_win }, new int[]{ 0, 1 }, null, hist, 2, new int[]{ 180, 256 }, ranges);
hist = hist.Normalize (0, 255, NormTypes.MinMax);
Point min_loc, max_loc;
Cv2.MinMaxLoc (hist, out min_loc, out max_loc);
Debug.Log (max_loc.X.ToString ());
//double[] lowerb = {0,0,0};
//double[] upperb = {180,255,255};
//Mat M = new Mat(1, 3, frame_hsv.Type(), Scalar (0, 0, 0));
Mat lowerb = new Mat (new Size (1, 3), frame_hsv.Type (), Scalar.All(100));
Mat upperb = new Mat(new Size(1,3), frame_hsv.Type(),Scalar.All(255));
//Debug.Log(frame_hsv.Type().ToString());
Cv2.InRange (frame_hsv, lowerb, upperb, frame_backproj);
//Cv2.CalcBackProject (new Mat[]{ frame_hsv }, new int[]{ 0, 1 }, hist, frame_backproj, ranges);
Mat kernel = Cv2.GetStructuringElement (MorphShapes.Ellipse, new Size (5, 5));
Cv2.Filter2D (frame_backproj, mask, mask.Type (), kernel);
//thresh = Cv2.Threshold (mask, mask, 0.0, 255.0, ThresholdTypes.Otsu);
//mask = 255 - mask;
kernel = Cv2.GetStructuringElement (MorphShapes.Rect, new Size (3, 3));
Cv2.MorphologyEx (mask, mask, MorphTypes.ERODE, kernel,null,2);
kernel = Cv2.GetStructuringElement (MorphShapes.Rect, new Size (15, 15));
Cv2.MorphologyEx (mask, mask, MorphTypes.Close, kernel,null,5);
Cv2.Merge(new Mat[]{mask,mask,mask},mask);
Cv2.BitwiseAnd (mask, frame, mask);
Cv2.Merge(new Mat[]{frame_backproj,frame_backproj,frame_backproj},frame_backproj);
tex.LoadImage (frame_backproj.ToBytes (".png", new int[]{ 0 }));
}
}
示例5: Perform
/// <summary>
///
/// </summary>
/// <param name="img"></param>
/// <param name="blobs"></param>
/// <returns></returns>
public static int Perform(Mat img, CvBlobs blobs)
{
if (img == null)
throw new ArgumentNullException(nameof(img));
if (blobs == null)
throw new ArgumentNullException(nameof(blobs));
if (img.Type() != MatType.CV_8UC1)
throw new ArgumentException("'img' must be a 1-channel U8 image.");
LabelData labels = blobs.Labels;
if (labels == null)
throw new ArgumentException("");
//if(labels.GetLength(0) != h || labels.GetLength(1) != w)
if (labels.Rows != img.Height || labels.Cols != img.Width)
throw new ArgumentException("img.Size != labels' size");
int numPixels = 0;
blobs.Clear();
int w = img.Cols;
int h = img.Rows;
int step = (int)img.Step();
byte[] imgIn;
unsafe
{
byte* imgInPtr = (byte*)img.Data;
if ((long) h * step > Int32.MaxValue)
throw new ArgumentException("Too big image (image data > 2^31)");
int length = h * step;
imgIn = new byte[length];
Marshal.Copy(new IntPtr(imgInPtr), imgIn, 0, imgIn.Length);
}
int label = 0;
int lastLabel = 0;
CvBlob lastBlob = null;
for (int y = 0; y < h; y++)
{
for (int x = 0; x < w; x++)
{
if (imgIn[x + y * step] == 0)
continue;
bool labeled = labels[y, x] != 0;
if (!labeled && ((y == 0) || (imgIn[x + (y - 1) * step] == 0)))
{
labeled = true;
// Label contour.
label++;
if (label == MarkerValue)
throw new Exception();
labels[y, x] = label;
numPixels++;
// XXX This is not necessary at all. I only do this for consistency.
if (y > 0)
labels[y - 1, x] = MarkerValue;
CvBlob blob = new CvBlob(label, x, y);
blobs.Add(label, blob);
lastLabel = label;
lastBlob = blob;
blob.Contour.StartingPoint = new Point(x, y);
int direction = 1;
int xx = x;
int yy = y;
bool contourEnd = false;
do
{
for (int numAttempts = 0; numAttempts < 3; numAttempts++)
{
bool found = false;
for (int i = 0; i < 3; i++)
{
int nx = xx + MovesE[direction, i, 0];
int ny = yy + MovesE[direction, i, 1];
if ((nx < w) && (nx >= 0) && (ny < h) && (ny >= 0))
{
if (imgIn[nx + ny * step] != 0)
{
found = true;
blob.Contour.ChainCode.Add((CvChainCode)MovesE[direction, i, 3]);
xx = nx;
yy = ny;
direction = MovesE[direction, i, 2];
break;
}
labels[ny, nx] = MarkerValue;
}
//.........这里部分代码省略.........
示例6: PerformOne
/// <summary>
///
/// </summary>
/// <param name="labels"></param>
/// <param name="blob"></param>
/// <param name="imgSrc"></param>
/// <param name="imgDst"></param>
/// <param name="mode"></param>
/// <param name="color"></param>
/// <param name="alpha"></param>
public static unsafe void PerformOne(LabelData labels, CvBlob blob, Mat imgSrc, Mat imgDst,
RenderBlobsMode mode, Scalar color, double alpha)
{
if (labels == null)
throw new ArgumentNullException("labels");
if (blob == null)
throw new ArgumentNullException("blob");
if (imgSrc == null)
throw new ArgumentNullException("imgSrc");
if (imgDst == null)
throw new ArgumentNullException("imgDst");
if (imgDst.Type() != MatType.CV_8UC3)
throw new ArgumentException("'img' must be a 3-channel U8 image.");
if ((mode & RenderBlobsMode.Color) == RenderBlobsMode.Color)
{
var pSrc = imgSrc.GetGenericIndexer<Vec3b>();
var pDst = imgDst.GetGenericIndexer<Vec3b>();
for (int r = blob.MinY; r < blob.MaxY; r++)
{
for (int c = blob.MinX; c < blob.MaxX; c++)
{
if (labels[r, c] == blob.Label)
{
byte v0 = (byte) ((1.0 - alpha)*pSrc[r, c].Item0 + alpha*color.Val0);
byte v1 = (byte) ((1.0 - alpha)*pSrc[r, c].Item1 + alpha*color.Val1);
byte v2 = (byte) ((1.0 - alpha)*pSrc[r, c].Item2 + alpha*color.Val2);
pDst[r, c] = new Vec3b(v0, v1, v2);
}
}
}
}
if (mode != RenderBlobsMode.None)
{
if ((mode & RenderBlobsMode.BoundingBox) == RenderBlobsMode.BoundingBox)
{
Cv2.Rectangle(
imgDst,
new Point(blob.MinX, blob.MinY),
new Point(blob.MaxX - 1, blob.MaxY - 1),
new Scalar(255, 0, 0));
}
if ((mode & RenderBlobsMode.Angle) == RenderBlobsMode.Angle)
{
double angle = blob.Angle();
double lengthLine = Math.Max(blob.MaxX - blob.MinX, blob.MaxY - blob.MinY) / 2.0;
double x1 = blob.Centroid.X - lengthLine * Math.Cos(angle);
double y1 = blob.Centroid.Y - lengthLine * Math.Sin(angle);
double x2 = blob.Centroid.X + lengthLine * Math.Cos(angle);
double y2 = blob.Centroid.Y + lengthLine * Math.Sin(angle);
Cv2.Line(imgDst, new Point((int)x1, (int)y1), new Point((int)x2, (int)y2),
new Scalar(0, 255, 0));
}
if ((mode & RenderBlobsMode.Centroid) == RenderBlobsMode.Centroid)
{
Cv2.Line(imgDst,
new Point((int)blob.Centroid.X - 3, (int)blob.Centroid.Y),
new Point((int)blob.Centroid.X + 3, (int)blob.Centroid.Y),
new Scalar(255, 0, 0));
Cv2.Line(imgDst,
new Point((int)blob.Centroid.X, (int)blob.Centroid.Y - 3),
new Point((int)blob.Centroid.X, (int)blob.Centroid.Y + 3),
new Scalar(255, 0, 0));
}
}
}
示例7: PerformMany
/// <summary>
///
/// </summary>
/// <param name="blobs"></param>
/// <param name="imgSrc"></param>
/// <param name="imgDst"></param>
/// <param name="mode"></param>
/// <param name="alpha"></param>
public static void PerformMany(CvBlobs blobs, Mat imgSrc, Mat imgDst, RenderBlobsMode mode, double alpha)
{
if (blobs == null)
throw new ArgumentNullException("blobs");
if (imgSrc == null)
throw new ArgumentNullException("imgSrc");
if (imgDst == null)
throw new ArgumentNullException("imgDst");
if (imgDst.Type() != MatType.CV_8UC3)
throw new ArgumentException("'img' must be a 3-channel U8 image.");
var palette = new Dictionary<int, Scalar>();
if ((mode & RenderBlobsMode.Color) == RenderBlobsMode.Color)
{
int colorCount = 0;
foreach (var kv in blobs)
{
double r, g, b;
Hsv2Rgb((colorCount*77) % 360, 0.5, 1.0, out r, out g, out b);
colorCount++;
palette[kv.Key] = new Scalar(b, g, r);
}
}
foreach (var kv in blobs)
{
PerformOne(blobs.Labels, kv.Value, imgSrc, imgDst, mode, palette[kv.Key], alpha);
}
}
示例8: NiblackFast
/// <summary>
/// Niblackの手法による二値化処理を行う(高速だが、メモリを多く消費するバージョン)。
/// </summary>
/// <param name="imgSrc">入力画像</param>
/// <param name="imgDst">出力画像</param>
/// <param name="kernelSize">局所領域のサイズ</param>
/// <param name="k">係数</param>
#else
/// <summary>
/// Binarizes by Niblack's method (This is faster but memory-hogging)
/// </summary>
/// <param name="src">Input image</param>
/// <param name="dst">Output image</param>
/// <param name="kernelSize">Window size</param>
/// <param name="k">Adequate coefficient</param>
#endif
public static void NiblackFast(Mat src, Mat dst, int kernelSize, double k)
{
if (src == null)
throw new ArgumentNullException("src");
if (dst == null)
throw new ArgumentNullException("dst");
// グレースケールのみ
if (src.Type() != MatType.CV_8UC1)
throw new ArgumentException("src must be gray scale image");
if (dst.Type() != MatType.CV_8UC1)
throw new ArgumentException("dst must be gray scale image");
// サイズのチェック
if (kernelSize < 3)
throw new ArgumentOutOfRangeException("kernelSize", "size must be 3 and above");
if (kernelSize % 2 == 0)
throw new ArgumentOutOfRangeException("kernelSize", "size must be odd number");
int borderSize = kernelSize / 2;
int width = src.Width;
int height = src.Height;
dst.Create(src.Size(), src.Type());
using (var tempMat = new Mat(height + (borderSize * 2), width + (borderSize * 2), src.Type()))
using (var sumMat = new Mat(tempMat.Height + 1, tempMat.Width + 1, MatType.CV_64FC1, 1))
using (var sqSumMat = new Mat(tempMat.Height + 1, tempMat.Width + 1, MatType.CV_64FC1, 1))
{
Cv2.CopyMakeBorder(src, tempMat, borderSize, borderSize, borderSize, borderSize, BorderTypes.Replicate, Scalar.All(0));
Cv2.Integral(tempMat, sumMat, sqSumMat);
using (var tSrcMat = new MatOfByte(src))
using (var tDstMat = new MatOfByte(dst))
using (var tSumMat = new MatOfDouble(sumMat))
using (var tSqSumMat = new MatOfDouble(sqSumMat))
{
var tSrc = tSrcMat.GetIndexer();
var tDst = tDstMat.GetIndexer();
var tSum = tSumMat.GetIndexer();
var tSqSum = tSqSumMat.GetIndexer();
int ylim = height + borderSize;
int xlim = width + borderSize;
int kernelPixels = kernelSize * kernelSize;
for (int y = borderSize; y < ylim; y++)
{
for (int x = borderSize; x < xlim; x++)
{
int x1 = x - borderSize;
int y1 = y - borderSize;
int x2 = x + borderSize + 1;
int y2 = y + borderSize + 1;
double sum = tSum[y2, x2] - tSum[y2, x1] - tSum[y1, x2] + tSum[y1, x1];
double sqsum = tSqSum[y2, x2] - tSqSum[y2, x1] - tSqSum[y1, x2] + tSqSum[y1, x1];
double mean = sum / kernelPixels;
double var = (sqsum / kernelPixels) - (mean * mean);
if (var < 0.0) var = 0.0;
double stddev = Math.Sqrt(var);
double threshold = mean + k * stddev;
if (tSrc[y - borderSize, x - borderSize] < threshold)
tDst[y - borderSize, x - borderSize] = 0;
else
tDst[y - borderSize, x - borderSize] = 255;
}
}
}
}
}
示例9: Bernsen
/// <summary>
/// Bernsenの手法による二値化処理を行う。
/// </summary>
/// <param name="imgSrc">入力画像</param>
/// <param name="imgDst">出力画像</param>
/// <param name="kernelSize">局所領域のサイズ</param>
/// <param name="constrastMin">この数値以下のコントラストの領域は背景領域とみなす</param>
/// <param name="bgThreshold">背景領域と見なされた領域に適用する閾値(背景領域以外では、適応的に閾値を求める)</param>
#else
/// <summary>
/// Binarizes by Bernsen's method
/// </summary>
/// <param name="src">Input image</param>
/// <param name="dst">Output image</param>
/// <param name="kernelSize">Window size</param>
/// <param name="constrastMin">Adequate coefficient</param>
/// <param name="bgThreshold">Adequate coefficient</param>
#endif
public static void Bernsen(Mat src, Mat dst, int kernelSize, byte constrastMin, byte bgThreshold)
{
if (src == null)
throw new ArgumentNullException("src");
if (dst == null)
throw new ArgumentNullException("dst");
// グレースケールのみ
if (src.Type() != MatType.CV_8UC1)
throw new ArgumentException("src must be gray scale image");
if (dst.Type() != MatType.CV_8UC1)
throw new ArgumentException("dst must be gray scale image");
// サイズのチェック
if (kernelSize < 3)
throw new ArgumentOutOfRangeException("kernelSize", "size must be 3 and above");
if (kernelSize % 2 == 0)
throw new ArgumentOutOfRangeException("kernelSize", "size must be odd number");
int width = src.Width;
int height = src.Height;
dst.Create(src.Size(), src.Type());
using (var tSrcMat = new MatOfByte(src))
using (var tDstMat = new MatOfByte(dst))
{
var tSrc = tSrcMat.GetIndexer();
var tDst = tDstMat.GetIndexer();
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
byte min, max;
MinMax(src, x, y, kernelSize, out min, out max);
int contrast = max - min;
byte threshold;
if (contrast < constrastMin)
threshold = bgThreshold;
else
threshold = (byte)((max + min) / 2);
if (tSrc[y, x] <= threshold)
tDst[y, x] = 0;
else
tDst[y, x] = 255;
}
}
}
}
示例10: example02
private static void example02()
{
var src = new Mat(@"..\..\Images\fruits.jpg", LoadMode.AnyDepth | LoadMode.AnyColor);
Cv2.ImShow("Source", src);
Cv2.WaitKey(1); // do events
Cv2.Blur(src, src, new Size(15, 15));
Cv2.ImShow("Blurred Image", src);
Cv2.WaitKey(1); // do events
// Converts the MxNx3 image into a Kx3 matrix where K=MxN and
// each row is now a vector in the 3-D space of RGB.
// change to a Mx3 column vector (M is number of pixels in image)
var columnVector = src.Reshape(cn: 3, rows: src.Rows * src.Cols);
// convert to floating point, it is a requirement of the k-means method of OpenCV.
var samples = new Mat();
columnVector.ConvertTo(samples, MatType.CV_32FC3);
for (var clustersCount = 2; clustersCount <= 8; clustersCount += 2)
{
var bestLabels = new Mat();
var centers = new Mat();
Cv2.Kmeans(
data: samples,
k: clustersCount,
bestLabels: bestLabels,
criteria:
new TermCriteria(type: CriteriaType.Epsilon | CriteriaType.Iteration, maxCount: 10, epsilon: 1.0),
attempts: 3,
flags: KMeansFlag.PpCenters,
centers: centers);
var clusteredImage = new Mat(src.Rows, src.Cols, src.Type());
for (var size = 0; size < src.Cols * src.Rows; size++)
{
var clusterIndex = bestLabels.At<int>(0, size);
var newPixel = new Vec3b
{
Item0 = (byte)(centers.At<float>(clusterIndex, 0)), // B
Item1 = (byte)(centers.At<float>(clusterIndex, 1)), // G
Item2 = (byte)(centers.At<float>(clusterIndex, 2)) // R
};
clusteredImage.Set(size / src.Cols, size % src.Cols, newPixel);
}
Cv2.ImShow(string.Format("Clustered Image [k:{0}]", clustersCount), clusteredImage);
Cv2.WaitKey(1); // do events
}
Cv2.WaitKey();
Cv2.DestroyAllWindows();
}
示例11: example01
/// <summary>
/// https://github.com/Itseez/opencv_extra/blob/master/learning_opencv_v2/ch13_ex13_1.cpp
/// </summary>
private static void example01()
{
using (var window = new Window("Clusters", flags: WindowMode.AutoSize | WindowMode.FreeRatio))
{
const int maxClusters = 5;
var rng = new RNG(state: (ulong)DateTime.Now.Ticks);
for (; ; )
{
var clustersCount = rng.Uniform(a: 2, b: maxClusters + 1);
var samplesCount = rng.Uniform(a: 1, b: 1001);
var points = new Mat(rows: samplesCount, cols: 1, type: MatType.CV_32FC2);
clustersCount = Math.Min(clustersCount, samplesCount);
var img = new Mat(rows: 500, cols: 500, type: MatType.CV_8UC3, s: Scalar.All(0));
// generate random sample from multi-gaussian distribution
for (var k = 0; k < clustersCount; k++)
{
var pointChunk = points.RowRange(
startRow: k * samplesCount / clustersCount,
endRow: (k == clustersCount - 1)
? samplesCount
: (k + 1) * samplesCount / clustersCount);
var center = new Point
{
X = rng.Uniform(a: 0, b: img.Cols),
Y = rng.Uniform(a: 0, b: img.Rows)
};
rng.Fill(
mat: pointChunk,
distType: DistributionType.Normal,
a: new Scalar(center.X, center.Y),
b: new Scalar(img.Cols * 0.05f, img.Rows * 0.05f));
}
Cv2.RandShuffle(dst: points, iterFactor: 1, rng: rng);
var labels = new Mat();
var centers = new Mat(rows: clustersCount, cols: 1, type: points.Type());
Cv2.Kmeans(
data: points,
k: clustersCount,
bestLabels: labels,
criteria: new TermCriteria(CriteriaType.Epsilon | CriteriaType.Iteration, 10, 1.0),
attempts: 3,
flags: KMeansFlag.PpCenters,
centers: centers);
Scalar[] colors =
{
new Scalar(0, 0, 255),
new Scalar(0, 255, 0),
new Scalar(255, 100, 100),
new Scalar(255, 0, 255),
new Scalar(0, 255, 255)
};
for (var i = 0; i < samplesCount; i++)
{
var clusterIdx = labels.At<int>(i);
Point ipt = points.At<Point2f>(i);
Cv2.Circle(
img: img,
center: ipt,
radius: 2,
color: colors[clusterIdx],
lineType: LineType.AntiAlias,
thickness: Cv.FILLED);
}
window.Image = img;
var key = (char)Cv2.WaitKey();
if (key == 27 || key == 'q' || key == 'Q') // 'ESC'
{
break;
}
}
}
}
示例12: Render
/// <summary>
/// Draw a contour.
/// </summary>
/// <param name="img">Image to draw on.</param>
/// <param name="color">Color to draw (default, white).</param>
public void Render(Mat img, Scalar color)
{
if (img == null)
throw new ArgumentNullException(nameof(img));
if (img.Type() != MatType.CV_8UC3)
throw new ArgumentException("Invalid img format (U8 3-channels)");
var indexer = img.GetGenericIndexer<Vec3b>();
int x = StartingPoint.X;
int y = StartingPoint.Y;
foreach (CvChainCode cc in ChainCode)
{
indexer[y, x] = new Vec3b((byte) color.Val0, (byte) color.Val1, (byte) color.Val2);
x += CvBlobConst.ChainCodeMoves[(int) cc][0];
y += CvBlobConst.ChainCodeMoves[(int) cc][1];
}
}
示例13: watershedExample
/// <summary>
/// https://github.com/Itseez/opencv_extra/blob/master/learning_opencv_v2/ch9_watershed.cpp
/// </summary>
private static void watershedExample()
{
var src = new Mat(@"..\..\Images\corridor.jpg", LoadMode.AnyDepth | LoadMode.AnyColor);
var srcCopy = new Mat();
src.CopyTo(srcCopy);
var markerMask = new Mat();
Cv2.CvtColor(srcCopy, markerMask, ColorConversion.BgrToGray);
var imgGray = new Mat();
Cv2.CvtColor(markerMask, imgGray, ColorConversion.GrayToBgr);
markerMask = new Mat(markerMask.Size(), markerMask.Type(), s: Scalar.All(0));
var sourceWindow = new Window("Source (Select areas by mouse and then press space)")
{
Image = srcCopy
};
var previousPoint = new Point(-1, -1);
sourceWindow.OnMouseCallback += (@event, x, y, flags) =>
{
if (x < 0 || x >= srcCopy.Cols || y < 0 || y >= srcCopy.Rows)
{
return;
}
if (@event == MouseEvent.LButtonUp || !flags.HasFlag(MouseEvent.FlagLButton))
{
previousPoint = new Point(-1, -1);
}
else if (@event == MouseEvent.LButtonDown)
{
previousPoint = new Point(x, y);
}
else if (@event == MouseEvent.MouseMove && flags.HasFlag(MouseEvent.FlagLButton))
{
var pt = new Point(x, y);
if (previousPoint.X < 0)
{
previousPoint = pt;
}
Cv2.Line(img: markerMask, pt1: previousPoint, pt2: pt, color: Scalar.All(255), thickness: 5);
Cv2.Line(img: srcCopy, pt1: previousPoint, pt2: pt, color: Scalar.All(255), thickness: 5);
previousPoint = pt;
sourceWindow.Image = srcCopy;
}
};
var rnd = new Random();
for (; ; )
{
var key = Cv2.WaitKey(0);
if ((char)key == 27) // ESC
{
break;
}
if ((char)key == 'r') // Reset
{
markerMask = new Mat(markerMask.Size(), markerMask.Type(), s: Scalar.All(0));
src.CopyTo(srcCopy);
sourceWindow.Image = srcCopy;
}
if ((char)key == 'w' || (char)key == ' ') // Apply watershed
{
Point[][] contours; //vector<vector<Point>> contours;
HiearchyIndex[] hierarchyIndexes; //vector<Vec4i> hierarchy;
Cv2.FindContours(
markerMask,
out contours,
out hierarchyIndexes,
mode: ContourRetrieval.CComp,
method: ContourChain.ApproxSimple);
if (contours.Length == 0)
{
continue;
}
var markers = new Mat(markerMask.Size(), MatType.CV_32S, s: Scalar.All(0));
var componentCount = 0;
var contourIndex = 0;
while ((contourIndex >= 0))
{
Cv2.DrawContours(
markers,
contours,
contourIndex,
color: Scalar.All(componentCount+1),
thickness: -1,
lineType: LineType.Link8,
hierarchy: hierarchyIndexes,
//.........这里部分代码省略.........