本文整理汇总了C#中Image.CopyBlank方法的典型用法代码示例。如果您正苦于以下问题:C# Image.CopyBlank方法的具体用法?C# Image.CopyBlank怎么用?C# Image.CopyBlank使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Image
的用法示例。
在下文中一共展示了Image.CopyBlank方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Process
public DetectorResult Process(Image<Bgr, byte> rawFrame, Image<Gray, byte> grayFrame)
{
Image<Bgr, byte> contourImage = null;
if (rawFrame != null)
{
List<Point[]> polygon = new List<Point[]>(); // to draw the perimeter
Image<Gray, byte> gray = rawFrame.Convert<Gray, byte>(); // convert source to gray
Image<Gray, byte> thresh = gray.PyrDown().PyrUp(); // attempt to make edges more distinct?
using (Image<Gray, Byte> mask = new Image<Gray, byte>(thresh.Size))
using (Image<Gray, byte> cannyImg = thresh.Canny(new Gray(10), new Gray(50)))
using (Image<Gray, byte> dilateImg = cannyImg.Dilate(1))
using (MemStorage stor = new MemStorage())
{
mask.SetValue(255.0);
for (
Contour<Point> contours = dilateImg.FindContours(
Emgu.CV.CvEnum.CHAIN_APPROX_METHOD.CV_CHAIN_APPROX_SIMPLE,
Emgu.CV.CvEnum.RETR_TYPE.CV_RETR_EXTERNAL,
stor);
contours != null; contours = contours.HNext)
{
Rectangle rect = contours.BoundingRectangle;
int area = rect.Height * rect.Width;
if (area > 30000)
{
rect.X -= 1; rect.Y -= 1; rect.Width += 2; rect.Height += 2;
rect.Intersect(gray.ROI);
mask.Draw(rect, new Gray(0.0), -1);
polygon.Add(contours.ToArray());
}
}
thresh.SetValue(0, mask);
}
contourImage = new Image<Bgr, byte>(gray.Bitmap);
contourImage.CopyBlank();
foreach (Point[] points in polygon)
contourImage.DrawPolyline(points, true, new Bgr(Color.Red), 2);
}
var result = new DetectorResult()
{
Confidence = 100,
GrayImage = grayFrame,
ProcessedImage = contourImage,
RawImage = rawFrame
};
return result;
}
示例2: GetGradientMagnitude
//.........这里部分代码省略.........
Image<Gray, Byte> gray = photo5.Convert<Gray, byte>();
CircleF[] circles = gray.HoughCircles(
cannyThreshold,
circleAccumulatorThreshold,
5.0, //Resolution of the accumulator used to detect centers of the circles
10.0, //min distance
5, //min radius
0 //max radius
)[0]; //Get the circles from the first channel
Image<Gray, Byte> cannyEdges = gray.Canny(180, 120);
LineSegment2D[] lines = cannyEdges.HoughLinesBinary(
1, //Distance resolution in pixel-related units
Math.PI / 45.0, //Angle resolution measured in radians.
20, //threshold
30, //min Line width
10 //gap between lines
)[0]; //Get the lines from the first channel
#region Find triangles and rectangles
List<Triangle2DF> triangleList = new List<Triangle2DF>();
List<MCvBox2D> boxList = new List<MCvBox2D>();
//double largestarea = 0;
using (MemStorage storage = new MemStorage()) //allocate storage for contour approximation
for (Contour<Point> contours = cannyEdges.FindContours(); contours != null; contours = contours.HNext)
{
Contour<Point> currentContour = contours.ApproxPoly(contours.Perimeter * 0.05, storage);
double largestarea = contours.Area;
string p = largestarea.ToString(); // จะแสดงค่าขนาดพื้นที่ของรูปภาพแต่ทำไม่ได้
textBox1.Text = p;
//MessageBox.Show(largestarea);
if (contours.Area > 250) //only consider contours with area greater than 250
//MessageBox.Show(contours.Area);
{
if (currentContour.Total == 3) //The contour has 3 vertices, it is a triangle
{
Point[] pts = currentContour.ToArray();
triangleList.Add(new Triangle2DF(
pts[0],
pts[1],
pts[2]
));
// String text = _ocr.GetText(); หาขนาดแล้วไปแสดงใน text box
// ocrTextBox.Text = text;
}
else if (currentContour.Total == 4) //The contour has 4 vertices.
{
#region determine if all the angles in the contour are within the range of [80, 100] degree
bool isRectangle = true;
Point[] pts = currentContour.ToArray();
LineSegment2D[] edges = PointCollection.PolyLine(pts, true);
for (int i = 0; i < edges.Length; i++)
{
double angle = Math.Abs(
edges[(i + 1) % edges.Length].GetExteriorAngleDegree(edges[i]));
if (angle < 80 || angle > 100)
{
isRectangle = false;
break;
}
}
#endregion
if (isRectangle) boxList.Add(currentContour.GetMinAreaRect());
}
}
}
#endregion
//pictureBox6.Image = photo5.ToBitmap();
pictureBox6.Image = cannyEdges.ToBitmap();
#region draw triangles and rectangles
Image<Bgr, Byte> triangleRectangleImage = photo5.CopyBlank();
foreach (Triangle2DF triangle in triangleList)
triangleRectangleImage.Draw(triangle, new Bgr(Color.DarkBlue), 2);
foreach (MCvBox2D box in boxList)
triangleRectangleImage.Draw(box, new Bgr(Color.DarkOrange), 2);
pictureBox7.Image = triangleRectangleImage.ToBitmap();
#endregion
#region draw circles
Image<Bgr, Byte> circleImage = photo5.CopyBlank();
foreach (CircleF circle in circles)
circleImage.Draw(circle, new Bgr(Color.Brown), 2);
// circleImageBox.Image = circleImage;
pictureBox8.Image = circleImage.ToBitmap();
#endregion
/*
#region draw lines
Image<Bgr, Byte> lineImage = img.CopyBlank();
foreach (LineSegment2D line in lines)
lineImage.Draw(line, new Bgr(Color.Green), 2);
lineImageBox.Image = lineImage;
#endregion
*/
}
示例3: button1_Click
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog Openfile = new OpenFileDialog();
if (Openfile.ShowDialog() == DialogResult.OK)
{
//Load the Image
Image<Bgr, Byte> My_Image = new Image<Bgr, byte>(Openfile.FileName);
//Convert the image to grayscale and filter out the noise
Image<Gray, Byte> gray = My_Image.Convert<Gray, Byte>().PyrDown().PyrUp();
Gray cannyThreshold = new Gray(180);
Gray cannyThresholdLinking = new Gray(120);
Gray circleAccumulatorThreshold = new Gray(120);
CircleF[] circles = gray.HoughCircles(
cannyThreshold,
circleAccumulatorThreshold,
5.0, //Resolution of the accumulator used to detect centers of the circles
10.0, //min distance
5, //min radius
0 //max radius
)[0]; //Get the circles from the first channel
Image<Gray, Byte> cannyEdges = gray.Canny(cannyThreshold, cannyThresholdLinking);
LineSegment2D[] lines = cannyEdges.HoughLinesBinary(
1, //Distance resolution in pixel-related units
Math.PI / 45.0, //Angle resolution measured in radians.
20, //threshold
30, //min Line width
10 //gap between lines
)[0]; //Get the lines from the first channel
#region Find triangles and rectangles
List<Triangle2DF> triangleList = new List<Triangle2DF>();
List<MCvBox2D> boxList = new List<MCvBox2D>();
using (MemStorage storage = new MemStorage()) //allocate storage for contour approximation
for (Contour<Point> contours = cannyEdges.FindContours(); contours != null; contours = contours.HNext)
{
Contour<Point> currentContour = contours.ApproxPoly(contours.Perimeter * 0.05, storage);
if (contours.Area > 250) //only consider contours with area greater than 250
{
if (currentContour.Total == 3) //The contour has 3 vertices, it is a triangle
{
Point[] pts = currentContour.ToArray();
triangleList.Add(new Triangle2DF(
pts[0],
pts[1],
pts[2]
));
}
else if (currentContour.Total == 4) //The contour has 4 vertices.
{
#region determine if all the angles in the contour are within the range of [80, 100] degree
bool isRectangle = true;
Point[] pts = currentContour.ToArray();
LineSegment2D[] edges = PointCollection.PolyLine(pts, true);
for (int i = 0; i < edges.Length; i++)
{
double angle = Math.Abs(
edges[(i + 1) % edges.Length].GetExteriorAngleDegree(edges[i]));
if (angle < 80 || angle > 100)
{
isRectangle = false;
break;
}
}
#endregion
if (isRectangle) boxList.Add(currentContour.GetMinAreaRect());
}
}
}
#endregion
originalImageBox.Image = My_Image.ToBitmap();
#region draw triangles and rectangles
Image<Bgr, Byte> triangleRectangleImage = My_Image.CopyBlank();
foreach (Triangle2DF triangle in triangleList)
triangleRectangleImage.Draw(triangle, new Bgr(Color.DarkBlue), 2);
foreach (MCvBox2D box in boxList)
triangleRectangleImage.Draw(box, new Bgr(Color.DarkOrange), 2);
triangleRectangleImageBox.Image = triangleRectangleImage.ToBitmap();
#endregion
#region draw circles
Image<Bgr, Byte> circleImage = My_Image.CopyBlank();
foreach (CircleF circle in circles)
circleImage.Draw(circle, new Bgr(Color.Brown), 2);
circleImageBox.Image = circleImage.ToBitmap();
#endregion
#region draw lines
Image<Bgr, Byte> lineImage = My_Image.CopyBlank();
foreach (LineSegment2D line in lines)
lineImage.Draw(line, new Bgr(Color.Green), 2);
lineImageBox.Image = lineImage.ToBitmap();
//.........这里部分代码省略.........
示例4: ImageGrabbed
//.........这里部分代码省略.........
}
//draw the results
_img.Draw(new CircleF(_corners[0], 3), new Bgr(Color.Yellow), 1);
for (int i = 1; i < _corners.Length; i++)
{
_img.Draw(new LineSegment2DF(_corners[i - 1], _corners[i]), _lineColourArray[i], 2);
_img.Draw(new CircleF(_corners[i], 3), new Bgr(Color.Yellow), 1);
}
//calibrate the delay bassed on size of buffer
//if buffer small you want a big delay if big small delay
Thread.Sleep(100);//allow the user to move the board to a different position
}
_corners = null;
}
if (_camera.Calibration.CurrentMode == CameraCalibrationMode.CalculatingIntrinsics)
{
//we can do this in the loop above to increase speed
for (int k = 0; k < _frameArrayBuffer.Length; k++)
{
_cornersPointsList[k] = CameraCalibration.FindChessboardCorners(_frameArrayBuffer[k], _patternSize, CALIB_CB_TYPE.ADAPTIVE_THRESH);
//for accuracy
_grayFrame.FindCornerSubPix(_cornersPointsList, new Size(11, 11), new Size(-1, -1), new MCvTermCriteria(30, 0.1));
//Fill our objects list with the real world mesurments for the intrinsic calculations
List<MCvPoint3D32f> objectList = new List<MCvPoint3D32f>();
for (int i = 0; i < Height; i++)
{
for (int j = 0; j < Width; j++)
{
objectList.Add(new MCvPoint3D32f(j * 20.0F, i * 20.0F, 0.0F));
}
}
_cornersObjectList[k] = objectList.ToArray();
}
ExtrinsicCameraParameters[] ex;
//our error should be as close to 0 as possible
_camera.Calibration.Error = CameraCalibration.CalibrateCamera(
_cornersObjectList,
_cornersPointsList,
_grayFrame.Size,
_camera.Calibration.IntrinsicParameters,
CALIB_TYPE.CV_CALIB_RATIONAL_MODEL,
new MCvTermCriteria(30, 0.1),
out ex);
//_camera.Calibration.ExtrinsicParameters = ex;
//set up to allow another calculation
//SetButtonState(true);
_camera.Calibration.StartFlag = false;
//If Emgu.CV.CvEnum.CALIB_TYPE == CV_CALIB_USE_INTRINSIC_GUESS and/or CV_CALIB_FIX_ASPECT_RATIO are specified, some or all of fx, fy, cx, cy must be initialized before calling the function
//if you use FIX_ASPECT_RATIO and FIX_FOCAL_LEGNTH options, these values needs to be set in the intrinsic parameters before the CalibrateCamera function is called. Otherwise 0 values are used as default.
Console.WriteLine("Intrinsic Calculation Error: " + _camera.Calibration.Error); //display the results to the user
_camera.Calibration.CurrentMode = CameraCalibrationMode.Calibrated;
}
if (_camera.Calibration.CurrentMode == CameraCalibrationMode.Calibrated)
{
_corners = CameraCalibration.FindChessboardCorners(_grayFrame, _patternSize, CALIB_CB_TYPE.ADAPTIVE_THRESH);
//we use this loop so we can show a colour image rather than a gray:
//CameraCalibration.DrawChessboardCorners(Gray_Frame, patternSize, corners);
if (_corners != null) //chess board found
{
//make mesurments more accurate by using FindCornerSubPixel
_grayFrame.FindCornerSubPix(new PointF[1][] { _corners }, new Size(11, 11), new Size(-1, -1), new MCvTermCriteria(30, 0.1));
//draw the results
_img.Draw(new CircleF(_corners[0], 3), new Bgr(Color.Yellow), 1);
for (int i = 1; i < _corners.Length; i++)
{
_img.Draw(new LineSegment2DF(_corners[i - 1], _corners[i]), _lineColourArray[i], 2);
_img.Draw(new CircleF(_corners[i], 3), new Bgr(Color.Yellow), 1);
}
//calibrate the delay bassed on size of buffer
//if buffer small you want a big delay if big small delay
Thread.Sleep(100);//allow the user to move the board to a different position
}
//display the original image
//Sub_PicturBox.Image = img.ToBitmap();
//calculate the camera intrinsics
Matrix<float> map1, map2;
_camera.Calibration.IntrinsicParameters.InitUndistortMap(_img.Width, _img.Height, out map1, out map2);
//remap the image to the particular intrinsics
//In the current version of EMGU any pixel that is not corrected is set to transparent allowing the original image to be displayed if the same
//image is mapped backed, in the future this should be controllable through the flag '0'
Image<Bgr, Byte> temp = _img.CopyBlank();
CvInvoke.cvRemap(_img, temp, map1, map2, 0, new MCvScalar(0));
_img = temp.Copy();
}
if(!_ctsCameraCalibration.Token.IsCancellationRequested)
{
BitmapSource bitmapSource = BitmapHelper.ToBitmapSource(_img);
bitmapSource.Freeze();
_camera.ImageSource = bitmapSource;
}
}
示例5: _Capture_ImageGrabbed
/// <summary>
/// main function processing of the image data
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void _Capture_ImageGrabbed(object sender, EventArgs e)
{
//lets get a frame from our capture device
img = _Capture.RetrieveBgrFrame();
Gray_Frame = img.Convert<Gray, Byte>();
//apply chess board detection
if (currentMode == Mode.SavingFrames)
{
corners = CameraCalibration.FindChessboardCorners(Gray_Frame, patternSize, Emgu.CV.CvEnum.CALIB_CB_TYPE.ADAPTIVE_THRESH);
//we use this loop so we can show a colour image rather than a gray: //CameraCalibration.DrawChessboardCorners(Gray_Frame, patternSize, corners);
if (corners != null) //chess board found
{
//make mesurments more accurate by using FindCornerSubPixel
Gray_Frame.FindCornerSubPix(new PointF[1][] { corners }, new System.Drawing.Size(11, 11), new System.Drawing.Size(-1, -1), new MCvTermCriteria(30, 0.1));
//if go button has been pressed start aquiring frames else we will just display the points
if (start_Flag)
{
Frame_array_buffer[frame_buffer_savepoint] = Gray_Frame.Copy(); //store the image
frame_buffer_savepoint++;//increase buffer positon
//check the state of buffer
if (frame_buffer_savepoint == Frame_array_buffer.Length) currentMode = Mode.Caluculating_Intrinsics; //buffer full
}
//dram the results
img.Draw(new CircleF(corners[0], 3), new Bgr(System.Drawing.Color.Yellow), 1);
for (int i = 1; i < corners.Length; i++)
{
img.Draw(new LineSegment2DF(corners[i - 1], corners[i]), line_colour_array[i], 2);
img.Draw(new CircleF(corners[i], 3), new Bgr(System.Drawing.Color.Yellow), 1);
}
//calibrate the delay bassed on size of buffer
//if buffer small you want a big delay if big small delay
Thread.Sleep(100);//allow the user to move the board to a different position
}
corners = null;
}
if (currentMode == Mode.Caluculating_Intrinsics)
{
//we can do this in the loop above to increase speed
for (int k = 0; k < Frame_array_buffer.Length; k++)
{
corners_points_list[k] = CameraCalibration.FindChessboardCorners(Frame_array_buffer[k], patternSize, Emgu.CV.CvEnum.CALIB_CB_TYPE.ADAPTIVE_THRESH);
//for accuracy
Gray_Frame.FindCornerSubPix(corners_points_list, new System.Drawing.Size(11, 11), new System.Drawing.Size(-1, -1), new MCvTermCriteria(30, 0.1));
//Fill our objects list with the real world mesurments for the intrinsic calculations
List<MCvPoint3D32f> object_list = new List<MCvPoint3D32f>();
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
object_list.Add(new MCvPoint3D32f(j * 20.0F, i * 20.0F, 0.0F));
}
}
corners_object_list[k] = object_list.ToArray();
}
//our error should be as close to 0 as possible
double error = CameraCalibration.CalibrateCamera(corners_object_list, corners_points_list, Gray_Frame.Size, IC, Emgu.CV.CvEnum.CALIB_TYPE.CV_CALIB_RATIONAL_MODEL, new MCvTermCriteria(30, 0.1), out EX_Param);
//If Emgu.CV.CvEnum.CALIB_TYPE == CV_CALIB_USE_INTRINSIC_GUESS and/or CV_CALIB_FIX_ASPECT_RATIO are specified, some or all of fx, fy, cx, cy must be initialized before calling the function
//if you use FIX_ASPECT_RATIO and FIX_FOCAL_LEGNTH options, these values needs to be set in the intrinsic parameters before the CalibrateCamera function is called. Otherwise 0 values are used as default.
System.Windows.Forms.MessageBox.Show("Intrinsic Calculation Error: " + error.ToString(), "Results", MessageBoxButtons.OK, MessageBoxIcon.Information); //display the results to the user
currentMode = Mode.Calibrated;
this.Dispatcher.Invoke((Action)(() =>
{
Write_BTN.IsEnabled = true;
}));
}
if (currentMode == Mode.Calibrated)
{
//calculate the camera intrinsics
Matrix<float> Map1, Map2;
IC.InitUndistortMap(img.Width, img.Height, out Map1, out Map2);
//remap the image to the particular intrinsics
//In the current version of EMGU any pixel that is not corrected is set to transparent allowing the original image to be displayed if the same
//image is mapped backed, in the future this should be controllable through the flag '0'
Image<Bgr, Byte> temp = img.CopyBlank();
CvInvoke.cvRemap(img, temp, Map1, Map2, 0, new MCvScalar(0));
img = temp.Copy();
//set up to allow another calculation
SetButtonState(true);
start_Flag = false;
}
Image<Bgr, byte> mainImage = img.Resize(((double)Main_Picturebox.Width / (double)img.Width), Emgu.CV.CvEnum.INTER.CV_INTER_LINEAR);
Main_Picturebox.Image = mainImage;
}
示例6: _Capture_ImageGrabbed
//.........这里部分代码省略.........
}
//our error should be as close to 0 as possible
double error = CameraCalibration.CalibrateCamera(corners_object_list, corners_points_list, Gray_Frame.Size, IC, Emgu.CV.CvEnum.CALIB_TYPE.CV_CALIB_RATIONAL_MODEL, out EX_Param);
//If Emgu.CV.CvEnum.CALIB_TYPE == CV_CALIB_USE_INTRINSIC_GUESS and/or CV_CALIB_FIX_ASPECT_RATIO are specified, some or all of fx, fy, cx, cy must be initialized before calling the function
//if you use FIX_ASPECT_RATIO and FIX_FOCAL_LEGNTH options, these values needs to be set in the intrinsic parameters before the CalibrateCamera function is called. Otherwise 0 values are used as default.
MessageBox.Show("Intrinsic Calculation Error: " + error.ToString(), "Results", MessageBoxButtons.OK, MessageBoxIcon.Information); //display the results to the user
currentMode = Mode.Calibrated;
for (int i1 = 0; i1 < 8; i1++)
{
Console.Write(IC.DistortionCoeffs[i1,0].ToString()+"\n");
}
for (int i1 = 0; i1 < 3; i1++)
{
for (int j1 = 0; j1 < 3;j1++ )
Console.Write(IC.IntrinsicMatrix[i1, j1].ToString()+"\t");
Console.Write("\n");
}
}
if (currentMode == Mode.Calibrated)
{
//display the original image
Sub_PicturBox.Image = img.ToBitmap();
//calculate the camera intrinsics
Matrix<float> Map1, Map2;
IC.InitUndistortMap(img.Width, img.Height, out Map1, out Map2);
//remap the image to the particular intrinsics
//In the current version of EMGU any pixel that is not corrected is set to transparent allowing the original image to be displayed if the same
//image is mapped backed, in the future this should be controllable through the flag '0'
Image<Bgr, Byte> temp = img.CopyBlank();
CvInvoke.cvRemap(img, temp, Map1, Map2, 0, new MCvScalar(0));
//added for corner drawing
Gray_Frame = temp.Convert<Gray, Byte>();
corners = CameraCalibration.FindChessboardCorners(Gray_Frame, patternSize, Emgu.CV.CvEnum.CALIB_CB_TYPE.ADAPTIVE_THRESH);
//we use this loop so we can show a colour image rather than a gray: //CameraCalibration.DrawChessboardCorners(Gray_Frame, patternSize, corners);
if (corners != null) //chess board found
{
//make mesurments more accurate by using FindCornerSubPixel
Gray_Frame.FindCornerSubPix(new PointF[1][] { corners }, new Size(11, 11), new Size(-1, -1), new MCvTermCriteria(30, 0.1));
//dram the results
temp.Draw(new CircleF(corners[0], 3), new Bgr(Color.Yellow), 1);
//CSV Writing before your loop
var csv = new StringBuilder();
string dirSave = Directory.GetCurrentDirectory() + "/Resources/dirSave";
string filePath = dirSave + "/dataChessBoardCalibrated.csv";
var newLine = ""; var newItem = "";
newLine = string.Format("{0}", Environment.NewLine);
if (!File.Exists(filePath))
{
for (int i = 1; i < corners.Length; i++)
{
newItem = i.ToString() + ", ";
csv.Append(newItem);
}
csv.Append(newLine);
File.WriteAllText(filePath, csv.ToString());
示例7: GetFFT_InverseAmpAndPhase
/// <summary>
/// Calculate Inverse FFT
/// </summary>
/// <param name="fft_Amp1"></param>
/// <param name="fft_Phase2"></param>
/// <returns></returns>
internal static Image<Gray, byte> GetFFT_InverseAmpAndPhase(Image<Gray, float> fft_Amp, Image<Gray, float> fft_Phase)
{
//rearange the fft output
fft_Amp = FFT2shift(fft_Amp,true);
fft_Phase = FFT2shift(fft_Phase,true);
// Get amplitude and Phase Channels
Image<Gray, float> imgFFT_Re = fft_Amp.CopyBlank();
Image<Gray, float> imgFFT_Im = fft_Amp.CopyBlank();
CvInvoke.cvPolarToCart(fft_Amp, fft_Phase, imgFFT_Re, imgFFT_Im, false);
return GetFFT_InverseReAndIm(imgFFT_Re, imgFFT_Im);
}
示例8: detectHardHat
//faceDetection ends
//Detect Hard Hat in the image
private Image<Bgr, Byte> detectHardHat(Image<Bgr,Byte> image)
{
Console.Out.WriteLine("Detecting Hard Hat...");
try
{
MCvAvgComp[] faces = faceDetection(image);
Image<Bgr, Byte> newImage = image.CopyBlank();
foreach (MCvAvgComp face in faces)
{
//Counter for the cirles in the processed image
int counter = 0;
//Object to store the region of the head above face for analysis
var headRegion = face;
headRegion.rect.Height = (face.rect.Height) ;
headRegion.rect.Y = face.rect.Y - (face.rect.Height * 8) / 10;
headRegion.rect.Width = face.rect.Width + face.rect.Width;
headRegion.rect.X = face.rect.X - (face.rect.Width * 2) / 4;
//Set the region of the image to headRegion for analysis
image.ROI = headRegion.rect;
//Object to store the region of the hard hat for display
var hardHat = face;
hardHat.rect.Height = face.rect.Height;
hardHat.rect.Y = face.rect.Y - (face.rect.Height * 8) / 10;
hardHat.rect.Width = face.rect.Width;
hardHat.rect.X = face.rect.X;
//Convert Image to HSV format for filtering
Image<Hsv, Byte> hsv = image.Convert<Hsv, Byte>();
//Apply the red color filter in the HSV model
grayScale_Image = hsv.InRange(new Hsv(0, 80, 80), new Hsv(20, 200, 200));
//List to store the contour region
List<Contour<Point>> list = new List<Contour<Point>>();
//Find the canny of the filtered image
grayScale_Image = cannyEdgeDetect(grayScale_Image.Convert<Bgr, Byte>(), 100, 50);
Console.Out.WriteLine("Head>" + headRegion.rect.Height + ":::" + headRegion.rect.Width);
//return grayScale_Image.Convert<Bgr, Byte>();
//Find the contours
Contour<Point> ctrs = grayScale_Image.FindContours();
while (ctrs != null)
{
Contour<Point> ctr = ctrs.ApproxPoly(2);
if (ctr.Area > 1) { list.Add(ctr); }
ctrs = ctrs.HNext;
}
foreach (Contour<Point> lis in list)
{
newImage.Draw(lis, new Bgr(Color.White), 1);
}
//newImage.ROI = headRegion.rect;
CircleF[] circles = grayScale_Image.HoughCircles(new Gray(220), new Gray(160), 5, 40, (headRegion.rect.Height *7)/20, headRegion.rect.Height/2)[0];
foreach (CircleF circle in circles)
{
counter++;
//image.Draw(circle, new Bgr(0, 255, 0), 2);
}
//return newImage.Convert<Bgr, Byte>();
//Reset the region of image back to whole image
image.ROI = Rectangle.Empty;
//Draw rectangle for each face detected
image.Draw(face.rect, new Bgr(0, 0, 0), 1);
if (counter > 0)
{
image.Draw(hardHat.rect, new Bgr(255, 0, 0), 2);
}
}
return image;
}
catch(Exception ex){
Console.Out.WriteLine("Error in detectHardHar(): " + ex.Message);
}
return myImage;
}
示例9: GetWhiteBlackImage
private Image<Bgr, Byte> GetWhiteBlackImage(Image<Bgr, byte> img, ushort threshold )
{
Image<Bgr, Byte> whiteBlackImg = img.CopyBlank();
for (int y = 0; y < img.Width; y++)
{
for (int x = 0; x < img.Height; x++)
{
Bgr color = img[x, y];
if (((int)GetDistanceToWhite(color)) < threshold)
{
whiteBlackImg[x, y] = new Bgr(Color.Black);
}
else
{
whiteBlackImg[x, y] = new Bgr(Color.White);
}
}
}
return whiteBlackImg;
}
示例10: PerformShapeDetection
public void PerformShapeDetection()
{
if (fileNameTextBox.Text != String.Empty)
{
//Load the image from file and resize it for display
Image<Bgr, Byte> img =
new Image<Bgr, byte>(fileNameTextBox.Text)
.Resize(400, 400, Emgu.CV.CvEnum.INTER.CV_INTER_LINEAR, true);
//Convert the image to grayscale and filter out the noise
Image<Gray, Byte> gray = img.Convert<Gray, Byte>().PyrDown().PyrUp();
Gray cannyThreshold = new Gray(180);
Gray cannyThresholdLinking = new Gray(120);
Gray circleAccumulatorThreshold = new Gray(500);
CircleF[] circles = gray.HoughCircles(
cannyThreshold,
circleAccumulatorThreshold,
4.0, //Resolution of the accumulator used to detect centers of the circles
15.0, //min distance
5, //min radius
0 //max radius
)[0]; //Get the circles from the first channel
Image<Gray, Byte> cannyEdges = gray.Canny(cannyThreshold, cannyThresholdLinking);
LineSegment2D[] lines = cannyEdges.HoughLinesBinary(
1, //Distance resolution in pixel-related units
Math.PI / 45.0, //Angle resolution measured in radians.
20, //threshold
30, //min Line width
10 //gap between lines
)[0]; //Get the lines from the first channel
#region Find triangles and rectangles
List<Triangle2DF> triangleList = new List<Triangle2DF>();
List<MCvBox2D> boxList = new List<MCvBox2D>(); //a box is a rotated rectangle
using (MemStorage storage = new MemStorage()) //allocate storage for contour approximation
for (
Contour<Point> contours = cannyEdges.FindContours(
Emgu.CV.CvEnum.CHAIN_APPROX_METHOD.CV_CHAIN_APPROX_SIMPLE,
Emgu.CV.CvEnum.RETR_TYPE.CV_RETR_LIST,
storage);
contours != null;
contours = contours.HNext)
{
Contour<Point> currentContour = contours.ApproxPoly(contours.Perimeter * 0.05, storage);
if (currentContour.Area > 250) //only consider contours with area greater than 250
{
if (currentContour.Total == 3) //The contour has 3 vertices, it is a triangle
{
Point[] pts = currentContour.ToArray();
triangleList.Add(new Triangle2DF(
pts[0],
pts[1],
pts[2]
));
}
else if (currentContour.Total == 4) //The contour has 4 vertices.
{
#region determine if all the angles in the contour are within [80, 100] degree
bool isRectangle = true;
Point[] pts = currentContour.ToArray();
LineSegment2D[] edges = PointCollection.PolyLine(pts, true);
for (int i = 0; i < edges.Length; i++)
{
double angle = Math.Abs(
edges[(i + 1) % edges.Length].GetExteriorAngleDegree(edges[i]));
if (angle < 80 || angle > 100)
{
isRectangle = false;
break;
}
}
#endregion
if (isRectangle) boxList.Add(currentContour.GetMinAreaRect());
}
}
}
#endregion
originalImageBox.Image = img;
#region draw triangles and rectangles
Image<Bgr, Byte> triangleRectangleImage = img.CopyBlank();
foreach (Triangle2DF triangle in triangleList)
triangleRectangleImage.Draw(triangle, new Bgr(Color.DarkBlue), 2);
foreach (MCvBox2D box in boxList)
triangleRectangleImage.Draw(box, new Bgr(Color.DarkOrange), 2);
triangleRectangleImageBox.Image = triangleRectangleImage;
#endregion
#region draw circles
Image<Bgr, Byte> circleImage = img.CopyBlank();
foreach (CircleF circle in circles)
circleImage.Draw(circle, new Bgr(Color.Brown), 2);
//.........这里部分代码省略.........
示例11: FindCirclesAndLinesWithHough
public static Bitmap FindCirclesAndLinesWithHough(Image<Bgr, byte> source)
{
frameBgr = source;
frameGray = frameBgr[0]
.PyrDown()
.Dilate(2)
.Erode(2)
.ThresholdBinary(VideoParameters.Default.GrayFrameThresholdLow, VideoParameters.Default.GrayFrameThresholdHigh)
.PyrUp();
frameCanny = HoughTransform.GetCanny(frameGray);
var blackGray = new Gray(0);
var blackBgr = new Bgr(Color.Black);
frameCanny.SetValue(blackGray, RobotMask);
var lines = HoughTransform.GetLines(frameCanny);
Lines = lines;
var height = VisionData.FrameSize.Height;
foreach (var line in lines)
{
if (line.Length < 10 /*&& IsLineWhite(frameBgr, line)*/)
continue;
var polygon = new[]
{
new Point(line.P1.X, line.P1.Y + 5),
new Point(line.P1.X, 0),
new Point(line.P2.X, 0),
new Point(line.P2.X, line.P2.Y + 5)
};
/*
var newLine = GetEdgeLine(line.P1, line.P2);
var polygon = new[]
{
new Point(newLine.P1.X, newLine.P1.Y),
new Point(newLine.P1.X, newLine.P1.Y - height),
new Point(newLine.P2.X, newLine.P2.Y - height),
new Point(newLine.P2.X, newLine.P2.Y)
};
*/
frameCanny.FillConvexPoly(polygon, blackGray);
frameBgr.FillConvexPoly(polygon, blackBgr);
//frameCanny.Draw(line, new Gray(0), 5);
}
//Lines = HoughTransform.FilterLines(lines);
Circles = HoughTransform.GetCircles(frameCanny.Bitmap);
//var points = EdgeFinder.GetTopArea(blue, lines);
//canny.FillConvexPoly(points.ToArray(), new Gray(155));
//var contours = EdgeFinder.GetContours(canny);
//foreach (var contour in contours)
// canny.FillConvexPoly(contour.ToArray(), new Gray(150));
// HACK: Testing))
switch (channel)
{
default:
case 1:
return frameBgr.Bitmap;
case 2:
return frameGray.Convert<Bgr, byte>().Bitmap;
case 3:
return frameCanny.Convert<Bgr, byte>().Bitmap;
case 4:
return new Image<Bgr, byte>(HoughTransform.CircleTransformation.ToBitmap()).Bitmap;
case 5:
return frameBgr.CopyBlank().Bitmap;
case 6:
var frame = frameBgr.InRange(
new Bgr(0, 0, 50),
new Bgr(VideoParameters.Default.RedThresholdBlue, VideoParameters.Default.RedThresholdGreen, VideoParameters.Default.RedThresholdRed));
return frame
.Dilate(3).Erode(6).Dilate(3)
.Convert<Bgr, byte>().Bitmap;
case 7:
var frame2 = frameBgr.InRange(
new Bgr(50, 0, 0),
new Bgr(VideoParameters.Default.BlueThresholdBlue, VideoParameters.Default.BlueThresholdGreen, VideoParameters.Default.BlueThresholdRed));
return frame2
.Dilate(3).Erode(6).Dilate(3)
.Convert<Bgr, byte>().Bitmap;
case 8:
var rectanglesRed = FindRedGoalRectangles();
var i = 1;
foreach (var rectangle in rectanglesRed.OrderBy(x => x.Size.Width))
{
frameBgr.Draw(rectangle, new Bgr(Color.Red), 3);
frameBgr.Draw(i.ToString(), ref Font, rectangle.Location + new Size(10, 10), new Bgr(Color.DarkRed));
}
var rectanglesBlue = FindBlueGoalRectangles();
i = 1;
foreach (var rectangle in rectanglesBlue.OrderBy(x => x.Size.Width))
{
//.........这里部分代码省略.........
示例12: process
/// <summary>
/// Find the wheels and run the rest of code.
/// </summary>
/// <param name="imgToPro"></param>
/// <param name="imgToDrawOn"></param>
/// <param name="isRealTime"></param>
/// <returns></returns>
public Image<Gray, Byte> process(Image<Gray, Byte> imgToPro, Image<Bgr,Byte> imgToDrawOn,bool isRealTime, String repairSubject)
{
// Detects the circles using the HoughCircles algorithm.
// The important parameters are
// Circle accumulator threshold
double cannyThreshold = 200;
double circleAccumulatorThreshold =300;
double resolutionOfAccumulator = 2.0;
double minDist = 500;//300;
int minRadius = 150;
int maxRadius = 300;
timer1--;
if (isRealTime)
{
minRadius = 50;
}
imgToPro.SmoothGaussian(333);
// Take 2 smaller pieces of the picture and test that on them
Rectangle rect = new Rectangle(0, 0+(this.Height/3), this.Width, this.Height - this.Height/3 );
imgToPro.ROI = rect;
imgToDrawOn.ROI = rect;
// Type avg = imgToPro.GetAverage(imgToPro);
// The following is done for the sake of speed.
// Since the wheels should be on the bottom part of the image,
// then 1/4 of the picture height should be the maximum radius.
maxRadius = rect.Height / 2;
// minRadius = rect.Width/ 10;
double[] valuesToTest = new double[] { 1,1.25,1.5,1.75, 2,2.5, 3, 4, 5, 6,7,8,9,10 };
// The minimum radius is
List<CircleF[]> circles = new List<CircleF[]>();
List<PointF> centers = new List<PointF>();
foreach (int i in valuesToTest)
{
circleAccumulatorThreshold = rect.Width / i +1;
circles.Add(imgToPro.HoughCircles(new Gray(cannyThreshold), new Gray(circleAccumulatorThreshold), resolutionOfAccumulator, minDist, minRadius, maxRadius)[0]);
//Console.WriteLine(circles);
}
List<CircleF> circlesList = new List<CircleF>();
int radInt = 0;
// Draws point on the circles where the rays are
// We are working in a two dimensional array [][].
Image<Gray, Byte> circleImage = imgToPro.CopyBlank();
Point centerOfWheel = new Point();
for (int i = 0; i < circles.Count; i++)
{
for(int z = 0; z < circles[i].Length; z++)
{
circlesList.Add(circles[i][z]);
//CircleF
PointF cpoint = circles[i][z].Center;
centers.Add(cpoint);
float rad = circles[i][z].Radius;
radInt = Convert.ToInt32(rad);
if (centers.Count > 2) break;
// Console.WriteLine(circles[i][z]);
}
}
// Distance between the wheels
double length = 0;
// Connect the two points
if (centers.Count > 2)
{
float startX = centers[0].X;
float startY = centers[0].Y;
float endX = centers[1].X;
float endY = centers[1].Y;
Point start = new Point((int)startX, (int)startY);
Point end = new Point((int)endX, (int)endY);
length = new LineSegment2DF(start, end).Length;
}
if (isRealTime)
{
// if the bike is found
if (timer1 > 0)
{
// draw the last bike
if (this.centers != null)
{
circleImage = drawEverything(this.centers, imgToPro, this.centerofwheel, imgToDrawOn, this.circleslist, this.length, radInt);
}
}
else
{
// draw the new found bike
if (isBikeFound(length, imgToPro))
//.........这里部分代码省略.........
示例13: TestContour
public void TestContour()
{
Image<Gray, Byte> img = new Image<Gray, byte>("stuff.jpg");
img.SmoothGaussian(3);
img = img.Canny(new Gray(80), new Gray(50));
Image<Gray, Byte> res = img.CopyBlank();
res.SetValue(255);
Contour<Point> contour = img.FindContours();
while (contour != null)
{
Contour<Point> approx = contour.ApproxPoly(contour.Perimeter * 0.05);
if (approx.Convex && approx.Area > 20.0)
{
Point[] vertices = approx.ToArray();
LineSegment2D[] edges = PointCollection.PolyLine(vertices, true);
res.DrawPolyline(vertices, true, new Gray(200), 1);
}
contour = contour.HNext;
}
}