public static GameResult DetermineGameResult(Bitmap screenshot) { ExhaustiveTemplateMatching tm = new ExhaustiveTemplateMatching(0); if (screenshot.PixelFormat != PixelFormat.Format24bppRgb) { screenshot = screenshot.To24Bpp(); } var win = tm.ProcessImage(screenshot, Image.FromFile("assets/victory_template.png"), new Rectangle(60, 50, 315, 80))[0].Similarity; if (win > 0.92f) { return(GameResult.Victory); } var defeat = tm.ProcessImage(screenshot, Image.FromFile("assets/defeat_template.png"), new Rectangle(60, 50, 265, 80))[0].Similarity; if (defeat > 0.92f) { return(GameResult.Defeat); } var draw = tm.ProcessImage(screenshot, Image.FromFile("assets/draw_template.png"), new Rectangle(60, 50, 265, 80))[0].Similarity; if (draw > 0.92f) { return(GameResult.Draw); } return(GameResult.Uncertain); }
private void btnMatch_Click(object sender, EventArgs e) { //Converting Template into GrayScale Image Bitmap templateImage = new Bitmap(textBox2.Text); Grayscale gg = new GrayscaleBT709(); Bitmap grayTemplate = gg.Apply(templateImage); // create template matching algorithm's instance ExhaustiveTemplateMatching tm = new ExhaustiveTemplateMatching(0); // find all matchings with specified above similarity Bitmap sourceImage = new Bitmap(textBox1.Text); Bitmap graySource = gg.Apply(sourceImage); TemplateMatch[] matchings = tm.ProcessImage(graySource, grayTemplate); Graphics g = Graphics.FromImage(sourceImage); if (matchings[0].Similarity > 0.8f) { int X = matchings[0].Rectangle.X; int Y = matchings[0].Rectangle.Y; g.DrawRectangle(new Pen(Color.HotPink, 20), X, Y, matchings[0].Rectangle.Width, matchings[0].Rectangle.Height); PicTemplate.Image = sourceImage; MessageBox.Show("Match found..."); } else { MessageBox.Show("Match Not Found..."); } }
public void test_template_matching() { try { using (var sourceImage = ((Bitmap)Bitmap.FromFile(@"C:\IMAGES\PB\PB742007.jpg")).ToGrayScale()) using (var template = ((Bitmap)Bitmap.FromFile(@"C:\IMAGES\PB\PB742007_cover2.jpg")).ToGrayScale()) { // create template matching algorithm's instance // (set similarity threshold to 92.5%) ExhaustiveTemplateMatching tm = new ExhaustiveTemplateMatching(0.80f); // find all matchings with specified above similarity TemplateMatch[] matchings = tm.ProcessImage(sourceImage, template); // highlight found matchings BitmapData data = sourceImage.LockBits(new System.Drawing.Rectangle(0, 0, sourceImage.Width, sourceImage.Height), ImageLockMode.ReadWrite, sourceImage.PixelFormat); foreach (TemplateMatch m in matchings) { Drawing.Rectangle(data, m.Rectangle, Color.Red); Debug.WriteLine(m.Rectangle.Location.ToString()); } sourceImage.UnlockBits(data); } } catch (Exception ex) { Debug.WriteLine(ex); } }
private bool verifyImage(Bitmap sourceImage, Bitmap template) { // create template matching algorithm's instance // (set similarity threshold to 92.1%) ExhaustiveTemplateMatching tm = new ExhaustiveTemplateMatching(0.921f); // find all matchings with specified above similarity TemplateMatch[] matchings = tm.ProcessImage(sourceImage, template); // highlight found matchings if (matchings.Length == 0) { return(false); } BitmapData data = sourceImage.LockBits( new Rectangle(0, 0, sourceImage.Width, sourceImage.Height), ImageLockMode.ReadWrite, sourceImage.PixelFormat); foreach (TemplateMatch m in matchings) { Drawing.Rectangle(data, m.Rectangle, System.Drawing.Color.White); x = m.Rectangle.Location.X; y = m.Rectangle.Location.Y; } // do something else with matching sourceImage.UnlockBits(data); return(true); }
public void findzoom() { //use this for cam stuff System.Drawing.Bitmap sourceImage = (Bitmap)Bitmap.FromFile(@"C:\Users\psang\Downloads\zoompos1.jpg"); System.Drawing.Bitmap temp = (Bitmap)Bitmap.FromFile(@"C:\Users\psang\Downloads\zoomjoin.jpg"); // create template matching algorithm's instance // (set similarity threshold to 92.1%) ExhaustiveTemplateMatching tm = new ExhaustiveTemplateMatching(0.921f); // find all matchings with specified above similarity TemplateMatch[] matchings = tm.ProcessImage(sourceImage, temp); // highlight found matchings BitmapData data = sourceImage.LockBits( new Rectangle(0, 0, sourceImage.Width, sourceImage.Height), ImageLockMode.ReadWrite, sourceImage.PixelFormat); foreach (TemplateMatch m in matchings) { Drawing.Rectangle(data, m.Rectangle, Color.White); MessageBox.Show(m.Rectangle.Location.ToString()); // do something else with matching } sourceImage.UnlockBits(data); }
public float sensitivity = 0.99f; //somewhere between 0.98 - 0.99 is perfect void Contains(Bitmap template, Bitmap bmp) { const Int32 divisor = 4; const Int32 epsilon = 10; ExhaustiveTemplateMatching etm = new ExhaustiveTemplateMatching(sensitivity); TemplateMatch[] tm = etm.ProcessImage( new ResizeNearestNeighbor(template.Width / divisor, template.Height / divisor).Apply(template), new ResizeNearestNeighbor(bmp.Width / divisor, bmp.Height / divisor).Apply(bmp) ); label5.Text = tm.Length.ToString(); if (tm.Length >= 1) { Rectangle tempRect = tm[0].Rectangle; imageX = tempRect.Location.X * divisor; imageY = tempRect.Location.Y * divisor; SetText(imageXY, "X:" + (imageX).ToString() + " Y:" + (imageY).ToString()); if (Math.Abs(bmp.Width / divisor - tempRect.Width) < epsilon && Math.Abs(bmp.Height / divisor - tempRect.Height) < epsilon) { SetText(findImage, "Got Fish!"); } Loot(imageX, imageY); } else { SetText(findImage, "Waiting for splash..."); SetText(imageXY, ""); } }
void Contains(Bitmap template, Bitmap bmp) { const Int32 divisor = 4; const Int32 epsilon = 10; ExhaustiveTemplateMatching etm = new ExhaustiveTemplateMatching(0.925f); //98% threshold TemplateMatch[] tm = etm.ProcessImage( new ResizeNearestNeighbor(template.Width / divisor, template.Height / divisor).Apply(template), new ResizeNearestNeighbor(bmp.Width / divisor, bmp.Height / divisor).Apply(bmp) ); label5.Text = tm.Length.ToString(); if (tm.Length == 1) { Rectangle tempRect = tm[0].Rectangle; imageX = tempRect.Location.X * divisor; imageY = tempRect.Location.Y * divisor; SetText(imageXY, "X:" + (imageX).ToString() + " Y:" + (imageY).ToString()); if (Math.Abs(bmp.Width / divisor - tempRect.Width) < epsilon && Math.Abs(bmp.Height / divisor - tempRect.Height) < epsilon) { SetText(findImage, "True"); } } else { SetText(findImage, "False"); SetText(imageXY, ""); } }
// private const Int32 Divider = 4; // Compare to images at x4 time smaller then real resolution for speed public static TemplateMatch[] Contains(this Bitmap Template, Bitmap bmp, float Precision = 0.9f, Int32 Dividier = 4) { var ETM = new ExhaustiveTemplateMatching(Precision); try { var Matches = ETM.ProcessImage( new ResizeNearestNeighbor(Template.Width / Dividier, Template.Height / Dividier).Apply(Template), new ResizeNearestNeighbor(bmp.Width / Dividier, bmp.Height / Dividier).Apply(bmp) ); if (Matches.Any()) { return(Matches); } else { return(null); } } catch (Exception Ex) { Console.WriteLine(Ex); return(null); } }
public void matchTemplate() { try { pictureBox3.InitialImage = null; Bitmap _templateimage = new Bitmap(pictureBox1.ClientSize.Width, pictureBox1.ClientSize.Height, PixelFormat.Format24bppRgb); Bitmap _srcimage = new Bitmap(pictureBox2.ClientSize.Width, pictureBox2.ClientSize.Height, PixelFormat.Format24bppRgb); Bitmap _dsimage = (Bitmap)_srcimage.Clone(); ExhaustiveTemplateMatching _tm = new ExhaustiveTemplateMatching(0.9f); TemplateMatch[] _mts = _tm.ProcessImage(_dsimage, _templateimage); /*if (_mts.Length > 0) * { * MessageBox.Show(_mts.Length.ToString()); * }*/ BitmapData _bmpdata = _dsimage.LockBits(new Rectangle(0, 0, _dsimage.Width, _dsimage.Height), ImageLockMode.ReadWrite, _dsimage.PixelFormat); foreach (var _match in _mts) { Drawing.Rectangle(_bmpdata, _match.Rectangle, Color.Red); } _dsimage.UnlockBits(_bmpdata); pictureBox3.Image = _dsimage; stop = true; } catch (Exception ex) { Console.WriteLine(ex.Message); } }
/// <summary> /// Constructs a new <see cref="MatchingTracker"/> object tracker. /// </summary> /// public MatchingTracker() { matcher = new ExhaustiveTemplateMatching(0); crop = new Crop(Rectangle.Empty); trackingObject = new TrackingObject(); RegistrationThreshold = 0.99; }
public static double GetSimilarity(string image, Bitmap targetImage, string filepath) { // Load images into bitmaps var imageOne = new Bitmap(image); var imageTwo = targetImage; var overlayImage = ChangePixelFormat(new Bitmap(imageOne)); var template = ChangePixelFormat(new Bitmap(imageOne)); var templFile = ChangePixelFormat(new Bitmap(imageTwo)); var df = new ThresholdedDifference(90) { OverlayImage = overlayImage }; var savedTemplate = SaveBitmapToFile(df.Apply(template), filepath, image, BitMapExtension); var savedTempFile = SaveBitmapToFile( df.Apply(templFile), filepath, Path.Combine(filepath, "temp.bmp"), BitMapExtension); // Setup the AForge library var tm = new ExhaustiveTemplateMatching(0); // Process the images var results = tm.ProcessImage(savedTemplate, savedTempFile); // Compare the results, 0 indicates no match so return false return(results.Length <= 0 ? 0 : results[0].Similarity); }
public static List <Point> GetSubPositionsAForge(Bitmap main, Bitmap sub, float similarityThreshold) { List <Point> possiblepos = new List <Point>(); System.Drawing.Bitmap sourceImage = ConvertToFormat(main, PixelFormat.Format24bppRgb); System.Drawing.Bitmap template = ConvertToFormat(sub, PixelFormat.Format24bppRgb); // create template matching algorithm's instance // (set similarity threshold to 92.1%) ExhaustiveTemplateMatching tm = new ExhaustiveTemplateMatching(0.941f); // find all matchings with specified above similarity TemplateMatch[] matchings = tm.ProcessImage(sourceImage, template); // highlight found matchings BitmapData data = sourceImage.LockBits( new Rectangle(0, 0, sourceImage.Width, sourceImage.Height), ImageLockMode.ReadWrite, sourceImage.PixelFormat); foreach (TemplateMatch m in matchings) { Point picPoint = m.Rectangle.Location; picPoint.X = picPoint.X * 4; picPoint.Y = picPoint.Y * 4; possiblepos.Add(picPoint); //sourceImage.UnlockBits(data); //return possiblepos; //1 result is enough } sourceImage.UnlockBits(data); return(possiblepos); }
private int CompareInventoryToSupply(Supply supply) { int numberOfMatches = 0; try { Bitmap image = new Bitmap("supplies/" + supply.fileName); Bitmap coverted = image.Clone(new Rectangle(0, 0, image.Width, image.Height), PixelFormat.Format24bppRgb); ExhaustiveTemplateMatching tm = new ExhaustiveTemplateMatching(0); TemplateMatch[] matchings = tm.ProcessImage(Data.Boxes[boxNo].Image, coverted); CleanupDebugFolders(); foreach (TemplateMatch m in matchings) { DebugMatches(m, Data.Boxes[boxNo]); if (m.Similarity > supply.matchValue) { numberOfMatches++; } } } catch (Exception ex) { MessageBox.Show(ex.Message); } return(numberOfMatches); }
public static MedalType DetermineMedalOnCard(Bitmap card) { ExhaustiveTemplateMatching tm = new ExhaustiveTemplateMatching(0); var goldSimilarity = tm.ProcessImage(card, Image.FromFile("TemplateImages/gold_medal.png"), new Rectangle(80, 40, 200, 200))[0].Similarity; if (goldSimilarity > 0.95f) { return(MedalType.Gold); } var silverSimilarity = tm.ProcessImage(card, Image.FromFile("TemplateImages/silver_medal.png"), new Rectangle(80, 40, 200, 200))[0].Similarity; if (silverSimilarity > 0.95f) { return(MedalType.Silver); } var bronzeSimilarity = tm.ProcessImage(card, Image.FromFile("TemplateImages/bronze_medal.png"), new Rectangle(80, 40, 200, 200))[0].Similarity; if (bronzeSimilarity > 0.95f) { return(MedalType.Bronze); } var noMedalSimilarity = tm.ProcessImage(card, Image.FromFile("TemplateImages/no_medal.png"), new Rectangle(80, 40, 200, 200))[0].Similarity; if (noMedalSimilarity > 0.95f) { return(MedalType.None); } return(MedalType.Uncertain); }
public double Matching1(Bitmap sourceImage, string template) { try { UseWaitCursor = true; Bitmap _sourceImage = (Bitmap)AForge.Imaging.Image.Clone(sourceImage, PixelFormat.Format24bppRgb); Bitmap _template = (Bitmap)AForge.Imaging.Image.FromFile(template); pictureBoxSource.Image = _sourceImage; pictureBoxTemplate.Image = _template; // create template matching algorithm's instance ExhaustiveTemplateMatching tm = new ExhaustiveTemplateMatching(0.9f); // find all matchings with specified above similarity TemplateMatch[] matchings = tm.ProcessImage(_sourceImage, _template); // highlight found matchings BitmapData data = _sourceImage.LockBits(new Rectangle(0, 0, _sourceImage.Width, _sourceImage.Height), ImageLockMode.ReadWrite, _sourceImage.PixelFormat); _sourceImage.UnlockBits(data); UseWaitCursor = false; return(double.Parse(matchings[0].Similarity.ToString())); } catch (Exception ex) { MessageBox.Show(ex.Message); return(0); } }
/* Assume the two images are in the correct format * 1 = perfectly equal * 0 = totally different */ private double TemplateMatchingSimilarity(Bitmap image, Bitmap template) { ExhaustiveTemplateMatching tm = new ExhaustiveTemplateMatching(0); TemplateMatch[] matchings = tm.ProcessImage(image, template); return((double)matchings[0].Similarity); }
private void FindSubmitButton(Process proc) { // https://stackoverflow.com/questions/2472467/how-to-find-one-image-inside-of-another try { Bitmap sourceImage = (Bitmap)Bitmap.FromFile(Application.StartupPath + "\\capture.jpg"); Bitmap baseImage = (Bitmap)Bitmap.FromFile(Application.StartupPath + "\\submit.jpg"); ExhaustiveTemplateMatching tm = new ExhaustiveTemplateMatching(0.921f); // find all matchings with specified above similarity TemplateMatch[] matchings = tm.ProcessImage(sourceImage, baseImage); // highlight found matchings BitmapData data = sourceImage.LockBits(new Rectangle(0, 0, sourceImage.Width, sourceImage.Height), ImageLockMode.ReadOnly, sourceImage.PixelFormat); sourceImage.UnlockBits(data); sourceImage.Dispose(); baseImage.Dispose(); var r = matchings[0].Rectangle; SendMessage(proc.MainWindowHandle, 0x201, 0x00000001, Coordinate(r.X, r.Y)); Thread.Sleep(100); SendMessage(proc.MainWindowHandle, 0x202, 0x00000001, Coordinate(r.X, r.Y)); CreateTextFile("submit1.txt", string.Format("{0}:{1}", r.X.ToString(), r.Y.ToString())); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }
/// <summary> /// 模板匹配 /// </summary> /// <param name="bitmaps"></param> /// <param name="templatepath"></param> /// <returns></returns> public static string GetTextFromTemplate(List <Bitmap> bitmaps, string templatepath) { var files = Directory.GetFiles(templatepath); var listnames = new List <string>(); var templateList = files.Select(i => { var stream = File.OpenRead(i); var file = new FileInfo(i); listnames.Add(file.Name.Replace(".jpg", "")); return((Bitmap)System.Drawing.Image.FromStream(stream)); }).ToList(); var sb = new StringBuilder(); ExhaustiveTemplateMatching templateMatching = new ExhaustiveTemplateMatching(0.9f); //这里面有四张图片,进行四张图的模板匹配 for (int i = 0; i < bitmaps.Count; i++) { float max = 0; int index = 0; for (int j = 0; j < templateList.Count; j++) { var compare = templateMatching.ProcessImage(bitmaps[i], templateList[j]); if (compare.Length > 0 && compare[0].Similarity > max) { //记录下最相似的 max = compare[0].Similarity; index = j; } } sb.Append(listnames[index]); } return(sb.ToString()); }
/// <summary> /// 匹配 /// </summary> /// <returns></returns> private string Match(Bitmap bitmap) { Dictionary <string, float> dm = new Dictionary <string, float>(); foreach (KeyValuePair <String, List <Bitmap> > dic in _bits) { foreach (Bitmap b in dic.Value) { ExhaustiveTemplateMatching tm = new ExhaustiveTemplateMatching(0); // compare two images TemplateMatch[] matchings = tm.ProcessImage(bitmap, b); if (matchings.Length > 0) { if (matchings[0].Similarity < 9.0f) { dm.Add(dic.Key, matchings[0].Similarity); } else { return(dic.Key); } } } } return(dm.Count > 0 ? dm.OrderByDescending(m => m.Value).FirstOrDefault().Key : "#"); }
/// <summary> /// Compares the images. /// </summary> /// <param name="image">The image.</param> /// <param name="targetImage">The target image.</param> /// <param name="compareLevel">The compare level.</param> /// <param name="filepath">The filepath.</param> /// <param name="similarityThreshold">The similarity threshold.</param> /// <returns>Boolean result</returns> public static bool CompareImages(Bitmap image, string targetImage, double compareLevel, float similarityThreshold, string filepath) { // Load images into bitmaps var imageOne = image; var imageTwo = new Bitmap(targetImage); var newBitmap1 = ChangePixelFormat(new Bitmap(imageOne), PixelFormat.Format24bppRgb); var newBitmap2 = ChangePixelFormat(new Bitmap(imageTwo), PixelFormat.Format24bppRgb); //newBitmap1 = SaveBitmapToFile(newBitmap1, filepath, image, ".bmp"); //newBitmap2 = SaveBitmapToFile(newBitmap2, filepath, targetImage, ".bmp"); // Setup the AForge library var tm = new ExhaustiveTemplateMatching(similarityThreshold); // Process the images var results = tm.ProcessImage(newBitmap1, newBitmap2); // Compare the results, 0 indicates no match so return false if (results.Length <= 0) { return(false); } // Return true if similarity score is equal or greater than the comparison level var match = results[0].Similarity >= compareLevel; return(match); }
/* Class regroupant les fonctions permettant de chercher une image dans un Stream Image par comparaison de pixel */ public Boolean checkImagePresentInStreamImage(MemoryStream screen_check, string img_check) { int i = 0; bool trouve = false; System.Drawing.Bitmap sourceImage = (Bitmap)Bitmap.FromStream(new MemoryStream(screen_check.ToArray())); System.Drawing.Bitmap template = (Bitmap)Bitmap.FromFile(img_check); // System.Drawing.Bitmap template = (Bitmap)Properties.Resources.r_egide; // avec les images en resources(not working) // create template matching algorithm's instance (hreshold ~ 92.5%) ExhaustiveTemplateMatching tm = new ExhaustiveTemplateMatching(0.921f); // find all matchings with specified above similarity TemplateMatch[] matchings = tm.ProcessImage(sourceImage, template); // highlight found matchings System.Drawing.Imaging.BitmapData data = sourceImage.LockBits(new Rectangle(0, 0, sourceImage.Width, sourceImage.Height), ImageLockMode.ReadWrite, sourceImage.PixelFormat); foreach (TemplateMatch m in matchings) { // on compte le nombre de tour dans le foreach(1 tour = image trouvée, 0 = image non trouvée) i++; AForge.Imaging.Drawing.Rectangle(data, m.Rectangle, System.Drawing.Color.White); //affiche la localisation de l'image trouvée //MessageBox.Show("position= " + m.Rectangle.Location.ToString()); } // à revoir pour faire chaque perso de chaque groupe if (i != 0) { trouve = true; } sourceImage.UnlockBits(data); return(trouve); }
public static List <System.Drawing.Point> TranslateImageToCoordinates(System.Drawing.Image image) { //List<PixelPoint> pixelPoints = new List<PixelPoint>(); List <Rectangle> results = new List <Rectangle>(); List <System.Drawing.Point> points = new List <System.Drawing.Point>(); Bitmap followImage = ConvertToFormat(Properties.Resources.followImage, PixelFormat.Format24bppRgb); Bitmap bitmap = ConvertToFormat(image, PixelFormat.Format24bppRgb); int multiplier = 3; followImage = ConvertToFormat(new Bitmap(followImage, new Size(followImage.Width / multiplier, followImage.Height / multiplier)), PixelFormat.Format24bppRgb); bitmap = ConvertToFormat(new Bitmap(bitmap, new Size(bitmap.Width / multiplier, bitmap.Height / multiplier)), PixelFormat.Format24bppRgb); ExhaustiveTemplateMatching tm = new ExhaustiveTemplateMatching(0.951f); TemplateMatch[] matchings = tm.ProcessImage(bitmap, followImage); BitmapData data = bitmap.LockBits( new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, image.PixelFormat); foreach (TemplateMatch m in matchings) { results.Add(m.Rectangle); } bitmap.UnlockBits(data); foreach (var item in results) { int centerX = item.X + 10; int centerY = item.Y + 5; points.Add(new System.Drawing.Point(centerX * multiplier, centerY * multiplier)); } return(points); }
private static bool CompareImages(string base1, string base2, double compareLevel, float similarityThreshold) { var imageOne = Base64StringToBitmap(base1); var imageTwo = Base64StringToBitmap(base2); imageOne = ScaleImage(imageOne, 60, 60); imageTwo = ScaleImage(imageTwo, 60, 60); var newBitmap1 = ChangePixelFormat(imageOne, System.Drawing.Imaging.PixelFormat.Format24bppRgb); var newBitmap2 = ChangePixelFormat(imageTwo, System.Drawing.Imaging.PixelFormat.Format24bppRgb); // Setup the AForge library var tm = new ExhaustiveTemplateMatching(similarityThreshold); // Process the images var results = tm.ProcessImage(newBitmap2, newBitmap1); // Compare the results, 0 indicates no match so return false if (results.Length <= 0) { return(false); } // Return true if similarity score is equal or greater than the comparison level var match = results[0].Similarity >= compareLevel; return(match); }
private void znajdzToolStripMenuItem_Click(object sender, EventArgs e) { System.Drawing.Bitmap sourceImage = (Bitmap)pictureBox2.Image; System.Drawing.Bitmap template = (Bitmap)pictureBox3.Image; // create template matching algorithm's instance // (set similarity threshold to 92.1%) ExhaustiveTemplateMatching tm = new ExhaustiveTemplateMatching(0.921f); // find all matchings with specified above similarity TemplateMatch[] matchings = tm.ProcessImage(sourceImage, template); // highlight found matchings BitmapData data = sourceImage.LockBits( new Rectangle(0, 0, sourceImage.Width, sourceImage.Height), ImageLockMode.ReadWrite, sourceImage.PixelFormat); foreach (TemplateMatch m in matchings) { Drawing.Rectangle(data, m.Rectangle, Color.White); //MessageBox.Show(m.Rectangle.Location.ToString()); richTextBox1.Text += "Obrazek znaleziony: m.Rectangle.Location.ToString() /n"; lokalizacja = m.Rectangle.Location; // do something else with matching } sourceImage.UnlockBits(data); }
public static double FindComparisonRatioBetweenImages(System.Drawing.Image one, System.Drawing.Image template) { Bitmap Bone = new Bitmap(one); Bitmap Btemplate = new Bitmap(template); Bitmap cloneTemplate = new Bitmap(Btemplate.Width, Btemplate.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb); using (Graphics gr = Graphics.FromImage(cloneTemplate)) { gr.DrawImage(Btemplate, new Rectangle(0, 0, cloneTemplate.Width, cloneTemplate.Height)); } Bitmap clone = new Bitmap(Btemplate.Width, Btemplate.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb); using (Graphics gr = Graphics.FromImage(clone)) { gr.DrawImage(Bone, new Rectangle(0, 0, cloneTemplate.Width, cloneTemplate.Height)); } ExhaustiveTemplateMatching tm = new ExhaustiveTemplateMatching(0); // compare two images' TemplateMatch[] matchings = null; matchings = tm.ProcessImage(clone, cloneTemplate); // check similarity level return(matchings[0].Similarity); }
/// <summary> /// See if bmp is contained in template with a small margin of error. /// </summary> /// <param name="template">The Bitmap that might contain.</param> /// <param name="bmp">The Bitmap that might be contained in.</param> /// <returns>You guess!</returns> public static bool Contains(this Bitmap template, Bitmap bmp) { const Int32 divisor = 4; const Int32 epsilon = 10; ExhaustiveTemplateMatching etm = new ExhaustiveTemplateMatching(0.9f); TemplateMatch[] tm = etm.ProcessImage( new ResizeNearestNeighbor(template.Width / divisor, template.Height / divisor).Apply(template), new ResizeNearestNeighbor(bmp.Width / divisor, bmp.Height / divisor).Apply(bmp) ); if (tm.Length == 1) { Rectangle tempRect = tm[0].Rectangle; if (Math.Abs(bmp.Width / divisor - tempRect.Width) < epsilon && Math.Abs(bmp.Height / divisor - tempRect.Height) < epsilon) { return(true); } } return(false); }
/* Function: CAM_CompareImage() * Parameters: * Input string Actual_Image * Input string Captured_Image * Description: compares Actual_Image and Captured_Image and returns the similarity rate in % value * 0 - none similar image * 100 - accurately similar image */ public Double CAM_CompareImage(string Actual_Image, string Captured_Image) { double dSimilarityResult = 0; Bitmap myactual = new Bitmap(Actual_Image); Bitmap mycapture = new Bitmap(Captured_Image); ExhaustiveTemplateMatching tm = new ExhaustiveTemplateMatching(0); TemplateMatch[] matchings = tm.ProcessImage(myactual, mycapture); // check similarity level myactual.Dispose(); mycapture.Dispose(); if (matchings.Length > 0) { dSimilarityResult = matchings[0].Similarity; } else if (matchings.Length <= 0) { dSimilarityResult = 0; } double rounded = Math.Round(dSimilarityResult, 2) * 100; return(rounded); }
public static Point ImageMatching(Bitmap big, Bitmap small, Point cropPoint = new Point(), int width = 0, int height = 0) { // create template matching algorithm's instance // (set similarity threshold to 92.5%) small = Imaging.ConvertFormat(small, PixelFormat.Format24bppRgb); big = width == 0 && height == 0 ? Imaging.ConvertFormat(big, PixelFormat.Format24bppRgb) : Imaging.ConvertFormat(CropImage(big, cropPoint, width, height), PixelFormat.Format24bppRgb); //big = Stopwatch sw = new Stopwatch(); sw.Start(); ExhaustiveTemplateMatching tm = new ExhaustiveTemplateMatching(0.95f); // find all matchings with specified above similarity TemplateMatch[] matchings = tm.ProcessImage(big, small); // highlight found matchings big.Save("C:\\test2.png"); BitmapData data = big.LockBits( new Rectangle(0, 0, big.Width, big.Height), ImageLockMode.ReadWrite, big.PixelFormat); big.UnlockBits(data); sw.Stop(); Console.WriteLine(sw.Elapsed); return(matchings.Length > 0 ? matchings[0].Rectangle.Location : new Point()); }
/// <summary> /// 查找图片,不能镂空 /// </summary> /// <param name="subPic"></param> /// <param name="parPic"></param> /// <param name="searchRect">如果为empty,则默认查找整个图像</param> /// <param name="errorRange">容错,单个色值范围内视为正确0~255</param> /// <param name="matchRate">图片匹配度,默认90%</param> /// <param name="isFindAll">是否查找所有相似的图片</param> /// <returns>返回查找到的图片的中心点坐标</returns> public System.Drawing.Point FindPicture(string subPic, float matchRate, bool isFindAll = false) { System.Drawing.Point Rst = new System.Drawing.Point(); System.Drawing.Bitmap sourceImage = getScreen(); System.Drawing.Bitmap template = (Bitmap)Bitmap.FromFile(subPic); // create template matching algorithm's instance // (set similarity threshold to 92.1%) ExhaustiveTemplateMatching tm = new ExhaustiveTemplateMatching(matchRate); // find all matchings with specified above similarity TemplateMatch[] matchings = tm.ProcessImage(sourceImage, template); // highlight found matchings BitmapData data = sourceImage.LockBits( new Rectangle(0, 0, sourceImage.Width, sourceImage.Height), ImageLockMode.ReadWrite, sourceImage.PixelFormat); foreach (TemplateMatch m in matchings) { Drawing.Rectangle(data, m.Rectangle, Color.White); Rst = m.Rectangle.Location; //MessageBox.Show(m.Rectangle.Location.ToString()); // do something else with matching } sourceImage.UnlockBits(data); return(Rst); }
public float IsMatch(Bitmap source, Bitmap template, float threshold = 0.80f) { var tm = new ExhaustiveTemplateMatching(threshold); var matchings = tm.ProcessImage(source, template); return(matchings.Length > 0 ? matchings[0].Similarity : -1); }
public float IsMatch(Bitmap source, Bitmap template, float threshold = 0.80f) { var tm = new ExhaustiveTemplateMatching(threshold); var matchings = tm.ProcessImage(source, template); return matchings.Length > 0 ? matchings[0].Similarity : -1; }