elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado:


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  [C#] detectar imagen y obtener coordenadas
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: [C#] detectar imagen y obtener coordenadas  (Leído 12,631 veces)
nevachana

Desconectado Desconectado

Mensajes: 61


Ver Perfil
[C#] detectar imagen y obtener coordenadas
« en: 1 Febrero 2015, 19:47 pm »

Hola ^^ me gustaría hacer un programa que detecte una imagen en la pantalla y obtener las coordenadas x e y pero no sé como compararlas y obtener las coordenadas.
Una ayudita? xD


« Última modificación: 1 Febrero 2015, 20:07 pm por Eleкtro » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.810



Ver Perfil
Re: [C#] ¿Cómo podría hacer esto?
« Respuesta #1 en: 1 Febrero 2015, 20:06 pm »

Buenas

1) El título de un tema debe describir el problema.
Porfavor, lee las normas del subforo de programación.



Una ayudita? xD

¿Donde está el código que demuestra tus progresos?, en este lugar no hacemos trabajos, ayudamos a resolver dudas específicas o aportamos orientación.

Hay varias librerías, algunas gratis y otras de pago, que ofrecen algoritmos profesionales de técnicas ImageSearch o PixelSearch, como por ejemplo AForge.Net
http://www.aforgenet.com/framework/downloads.html

Si quieres desarrollar tu propio algoritmo de forma tradicional no te lo recomiendo, por el simple hecho de que jamás podrás optimizarlo hasta tal punto, pero de todas formas puedes ver un ejemplo escrito en VB.Net en la class PixelUtil que desarrollé:
Librería de Snippets !! (Compartan aquí sus snippets)

Este ejemplo utilizando Aforge, es una función de uso genérico que busca una imagen en otra imagen, y devuelve un objeto con las coordenadas y otra información relevante:

VB.Net:
Código
  1.    ' Find Image
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    '
  6.    'Private Sub Test() Handles MyBase.Shown
  7.    '
  8.    '    ' A Desktop Screenshot, in 1920x1080 px. resolution.
  9.    '    Dim desktopScreenshoot As New Bitmap("C:\Desktop.png")
  10.    '
  11.    '    ' A cutted piece of the screenshot, in 50x50 px. resolution.
  12.    '    Dim partOfDesktopToFind As New Bitmap("C:\PartOfDesktop.png")
  13.    '
  14.    '    ' Find the part of the image in the desktop, with the specified similarity.
  15.    '    For Each matching As AForge.Imaging.TemplateMatch In
  16.    '
  17.    '        FindImage(baseImage:=desktopScreenshoot, imageToFind:=partOfDesktopToFind, similarity:=80.5R) ' 80,5% similarity.
  18.    '
  19.    '        Dim sb As New System.Text.StringBuilder
  20.    '
  21.    '        sb.AppendFormat("Top-Left Corner Coordinates: {0}", matching.Rectangle.Location.ToString())
  22.    '        sb.AppendLine()
  23.    '        sb.AppendFormat("similarity Image Percentage: {0}%", (matching.similarity * 100.0F).ToString("00.00"))
  24.    '
  25.    '        MessageBox.Show(sb.ToString)
  26.    '
  27.    '    Next matching
  28.    '
  29.    'End Sub
  30.    '
  31.    ''' <summary>
  32.    ''' Finds a part of an image inside other image and returns the top-left corner coordinates and it's similarity percent.
  33.    ''' </summary>
  34.    ''' <param name="baseImage">
  35.    ''' Indicates the base image.
  36.    ''' </param>
  37.    ''' <param name="imageToFind">
  38.    ''' Indicates the image to find in the base image.
  39.    ''' </param>
  40.    ''' <param name="similarity">
  41.    ''' Indicates the similarity percentage to compare the images.
  42.    ''' A value of '100' means identical image.
  43.    ''' Note: High percentage values with big images could take several minutes to finish.
  44.    ''' </param>
  45.    ''' <returns>AForge.Imaging.TemplateMatch().</returns>
  46.    Private Function FindImage(ByVal baseImage As Bitmap,
  47.                               ByVal imageToFind As Bitmap,
  48.                               ByVal similarity As Double) As AForge.Imaging.TemplateMatch()
  49.  
  50.        Dim currentSimilarity As Single
  51.  
  52.        ' Translate the readable similarity percent value to Single value.
  53.        Select Case similarity
  54.  
  55.            Case Is < 0.1R, Is > 100.0R ' Value is out of range.
  56.                Throw New Exception(String.Format("similarity value of '{0}' is out of range, range is from '0.1' to '100.0'",
  57.                                                  CStr(similarity)))
  58.  
  59.            Case Is = 100.0R ' Identical image comparission.
  60.                currentSimilarity = 1.0F
  61.  
  62.            Case Else ' Image comparission with specific similarity.
  63.                currentSimilarity = Convert.ToSingle(similarity) / 100.0F
  64.  
  65.        End Select
  66.  
  67.        ' Set the similarity threshold to find all matching images with specified similarity.
  68.        Dim tm As New AForge.Imaging.ExhaustiveTemplateMatching(currentSimilarity)
  69.  
  70.        ' Return all the found matching images,
  71.        ' it contains the top-left corner coordinates of each one
  72.        ' and matchings are sortered by it's similarity percent.
  73.        Return tm.ProcessImage(baseImage, imageToFind)
  74.  
  75.    End Function
  76.  

C#:
EDITO: El Snippet está traducido incorrectamente.

Código
  1. // Find Image
  2. // ( By Elektro )
  3.  
  4. /// <summary>
  5. /// Finds a part of an image inside other image and returns the top-left corner coordinates and it's similarity percent.
  6. /// </summary>
  7. /// <param name="baseImage">
  8. /// Indicates the base image.
  9. /// </param>
  10. /// <param name="imageToFind">
  11. /// Indicates the image to find in the base image.
  12. /// </param>
  13. /// <param name="similarity">
  14. /// Indicates the similarity percentage to compare the images.
  15. /// A value of '100' means identical image.
  16. /// Note: High percentage values with big images could take several minutes to finish.
  17. /// </param>
  18. /// <returns>AForge.Imaging.TemplateMatch().</returns>
  19. private AForge.Imaging.TemplateMatch[] FindImage(Bitmap baseImage, Bitmap imageToFind, double similarity)
  20. {
  21.  
  22. float currentSimilarity = 0;
  23.  
  24. // Translate the readable similarity percent value to Single value.
  25. switch (similarity) {
  26.  
  27. case 100.0: // Identical image comparission.
  28. currentSimilarity = 1f;
  29. break;
  30.  
  31. default: // Image comparission with specific similarity.
  32. currentSimilarity = Convert.ToSingle(similarity) / 100f;
  33. break;
  34. }
  35.  
  36. // Set the similarity threshold to find all matching images with specified similarity.
  37. AForge.Imaging.ExhaustiveTemplateMatching tm = new AForge.Imaging.ExhaustiveTemplateMatching(currentSimilarity);
  38.  
  39. // Return all the found matching images,
  40. // it contains the top-left corner coordinates of each one
  41. // and matchings are sortered by it's similarity percent.
  42. return tm.ProcessImage(baseImage, imageToFind);
  43.  
  44. }
  45.  
  46. //=======================================================
  47. //Service provided by Telerik (www.telerik.com)
  48. //=======================================================

Saludos.


« Última modificación: 1 Febrero 2015, 20:22 pm por Eleкtro » En línea

nevachana

Desconectado Desconectado

Mensajes: 61


Ver Perfil
Re: [C#] ¿Cómo podría hacer esto?
« Respuesta #2 en: 2 Febrero 2015, 20:14 pm »

Buenas

1) El título de un tema debe describir el problema.
Porfavor, lee las normas del subforo de programación.



¿Donde está el código que demuestra tus progresos?, en este lugar no hacemos trabajos, ayudamos a resolver dudas específicas o aportamos orientación.

Hay varias librerías, algunas gratis y otras de pago, que ofrecen algoritmos profesionales de técnicas ImageSearch o PixelSearch, como por ejemplo AForge.Net
http://www.aforgenet.com/framework/downloads.html

Si quieres desarrollar tu propio algoritmo de forma tradicional no te lo recomiendo, por el simple hecho de que jamás podrás optimizarlo hasta tal punto, pero de todas formas puedes ver un ejemplo escrito en VB.Net en la class PixelUtil que desarrollé:
Librería de Snippets !! (Compartan aquí sus snippets)

Este ejemplo utilizando Aforge, es una función de uso genérico que busca una imagen en otra imagen, y devuelve un objeto con las coordenadas y otra información relevante:

VB.Net:
Código
  1.    ' Find Image
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    '
  6.    'Private Sub Test() Handles MyBase.Shown
  7.    '
  8.    '    ' A Desktop Screenshot, in 1920x1080 px. resolution.
  9.    '    Dim desktopScreenshoot As New Bitmap("C:\Desktop.png")
  10.    '
  11.    '    ' A cutted piece of the screenshot, in 50x50 px. resolution.
  12.    '    Dim partOfDesktopToFind As New Bitmap("C:\PartOfDesktop.png")
  13.    '
  14.    '    ' Find the part of the image in the desktop, with the specified similarity.
  15.    '    For Each matching As AForge.Imaging.TemplateMatch In
  16.    '
  17.    '        FindImage(baseImage:=desktopScreenshoot, imageToFind:=partOfDesktopToFind, similarity:=80.5R) ' 80,5% similarity.
  18.    '
  19.    '        Dim sb As New System.Text.StringBuilder
  20.    '
  21.    '        sb.AppendFormat("Top-Left Corner Coordinates: {0}", matching.Rectangle.Location.ToString())
  22.    '        sb.AppendLine()
  23.    '        sb.AppendFormat("similarity Image Percentage: {0}%", (matching.similarity * 100.0F).ToString("00.00"))
  24.    '
  25.    '        MessageBox.Show(sb.ToString)
  26.    '
  27.    '    Next matching
  28.    '
  29.    'End Sub
  30.    '
  31.    ''' <summary>
  32.    ''' Finds a part of an image inside other image and returns the top-left corner coordinates and it's similarity percent.
  33.    ''' </summary>
  34.    ''' <param name="baseImage">
  35.    ''' Indicates the base image.
  36.    ''' </param>
  37.    ''' <param name="imageToFind">
  38.    ''' Indicates the image to find in the base image.
  39.    ''' </param>
  40.    ''' <param name="similarity">
  41.    ''' Indicates the similarity percentage to compare the images.
  42.    ''' A value of '100' means identical image.
  43.    ''' Note: High percentage values with big images could take several minutes to finish.
  44.    ''' </param>
  45.    ''' <returns>AForge.Imaging.TemplateMatch().</returns>
  46.    Private Function FindImage(ByVal baseImage As Bitmap,
  47.                               ByVal imageToFind As Bitmap,
  48.                               ByVal similarity As Double) As AForge.Imaging.TemplateMatch()
  49.  
  50.        Dim currentSimilarity As Single
  51.  
  52.        ' Translate the readable similarity percent value to Single value.
  53.        Select Case similarity
  54.  
  55.            Case Is < 0.1R, Is > 100.0R ' Value is out of range.
  56.                Throw New Exception(String.Format("similarity value of '{0}' is out of range, range is from '0.1' to '100.0'",
  57.                                                  CStr(similarity)))
  58.  
  59.            Case Is = 100.0R ' Identical image comparission.
  60.                currentSimilarity = 1.0F
  61.  
  62.            Case Else ' Image comparission with specific similarity.
  63.                currentSimilarity = Convert.ToSingle(similarity) / 100.0F
  64.  
  65.        End Select
  66.  
  67.        ' Set the similarity threshold to find all matching images with specified similarity.
  68.        Dim tm As New AForge.Imaging.ExhaustiveTemplateMatching(currentSimilarity)
  69.  
  70.        ' Return all the found matching images,
  71.        ' it contains the top-left corner coordinates of each one
  72.        ' and matchings are sortered by it's similarity percent.
  73.        Return tm.ProcessImage(baseImage, imageToFind)
  74.  
  75.    End Function
  76.  

C#:
EDITO: El Snippet está traducido incorrectamente.

Código
  1. // Find Image
  2. // ( By Elektro )
  3.  
  4. /// <summary>
  5. /// Finds a part of an image inside other image and returns the top-left corner coordinates and it's similarity percent.
  6. /// </summary>
  7. /// <param name="baseImage">
  8. /// Indicates the base image.
  9. /// </param>
  10. /// <param name="imageToFind">
  11. /// Indicates the image to find in the base image.
  12. /// </param>
  13. /// <param name="similarity">
  14. /// Indicates the similarity percentage to compare the images.
  15. /// A value of '100' means identical image.
  16. /// Note: High percentage values with big images could take several minutes to finish.
  17. /// </param>
  18. /// <returns>AForge.Imaging.TemplateMatch().</returns>
  19. private AForge.Imaging.TemplateMatch[] FindImage(Bitmap baseImage, Bitmap imageToFind, double similarity)
  20. {
  21.  
  22. float currentSimilarity = 0;
  23.  
  24. // Translate the readable similarity percent value to Single value.
  25. switch (similarity) {
  26.  
  27. case 100.0: // Identical image comparission.
  28. currentSimilarity = 1f;
  29. break;
  30.  
  31. default: // Image comparission with specific similarity.
  32. currentSimilarity = Convert.ToSingle(similarity) / 100f;
  33. break;
  34. }
  35.  
  36. // Set the similarity threshold to find all matching images with specified similarity.
  37. AForge.Imaging.ExhaustiveTemplateMatching tm = new AForge.Imaging.ExhaustiveTemplateMatching(currentSimilarity);
  38.  
  39. // Return all the found matching images,
  40. // it contains the top-left corner coordinates of each one
  41. // and matchings are sortered by it's similarity percent.
  42. return tm.ProcessImage(baseImage, imageToFind);
  43.  
  44. }
  45.  
  46. //=======================================================
  47. //Service provided by Telerik (www.telerik.com)
  48. //=======================================================

Saludos.
La prueba:
Código
  1.    public static void Start()
  2.        {
  3.            while (true)
  4.            {
  5.                for (int i = 0; i < totalCoords; i++)
  6.                {
  7.                    a.MouseClick("Left", X[i], Y[i], 1, 1);
  8.                    Thread.Sleep(seconds * 1000);
  9.                    a.MouseClick("Left", CloseX, CloseY, 1, 1);
  10.                    Thread.Sleep(1900);
  11.                    if (i == totalCoords - 1)
  12.                        i = 0;
  13.                }
  14.            }
  15.        }
  16.  
  17.        private void Form1_Load(object sender, EventArgs e)
  18.        {
  19.            this.KeyPreview = true;          
  20.        }
  21.  
  22.        private void button2_Click(object sender, EventArgs e)
  23.        {
  24.            this.KeyDown += new KeyEventHandler(Form1_KeyDown);
  25.            textBox4.Text = "";
  26.        }
  27.        void Form1_KeyDown(object sender, KeyEventArgs e)
  28.        {
  29.            if (e.KeyCode.ToString() == "F3")
  30.            {
  31.                textBox4.Text = textBox4.Text + Cursor.Position.X.ToString()+"@"+Cursor.Position.Y + "\r\n";
  32.            }
  33.        }
  34.        void cerrar(object sender, KeyEventArgs e)
  35.        {
  36.            if (e.KeyCode.ToString() == "F1")
  37.            {
  38.                textBox1.Text = Cursor.Position.X.ToString();
  39.                textBox2.Text = Cursor.Position.Y.ToString();
  40.            }
  41.        }
  42.  
  43.        private void button3_Click(object sender, EventArgs e)
  44.        {
  45.            this.KeyDown += new KeyEventHandler(cerrar);
  46.        }
  47.    }
  48. }
  49.  
Ya sé que no es limpio es mi primera aplicación en autoit,pero la idea que me has dado serviría para buscarlo por toda la pantalla?
« Última modificación: 2 Febrero 2015, 20:28 pm por Eleкtro » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.810



Ver Perfil
Re: [C#] ¿Cómo podría hacer esto?
« Respuesta #3 en: 2 Febrero 2015, 20:36 pm »

Ya sé que no es limpio es mi primera aplicación en autoit
No te preocupes, aquí nadie es mejor que nadie y todos vienen a aprender.

pero la idea que me has dado serviría para buscarlo por toda la pantalla?
Hombre, por supuesto, solo debes obtener la imagen de la zona donde quieras buscar (puede ser una captura de la pantalla completa, claro), y si la imagen es demasiado grande redimensionar la imagen a unas dimensiones que te permitan realizar la búsqueda y comparación de imagen de una forma eficiente, rápida, pero sin aumentar el margen de falsos positivos, buscando esa relación (ej: 100x100 píxeles quizás, depende).

EDITO:
No me ha quedado claro que camino vas a tomar para llevarlo a cabo, pero bueno vuelvo a aconsejarte utilizar la librería de AForge.Net, aunque he visto algoritmos de pago mucho más rápidos que obtienen los mismos o mejores resultados, pero AForge es excelente para ser gratis.

Realizar un algoritmo de ese estilo es relativamente fácil, de forma básica, pero es un tema muy delicado ya que procesar/comparar una imagen, una imagen que sea grande, es una operación muy lenta (y si usas metodologías anticuadas lo es aun mucho más), si no optimizas tu propio algoritmo hasta el punto que puede llegar a optimizarlo un grupo de desarrolladores profesionales en el tema que están vendiendo un producto de ese estilo entonces te puede quedar un algoritmo muy lento o incompetente en otros sentidos, y yo no soy ningún gurú en la optimización de este tema, pero llegué a implementar funcionalidades GPU para aumentar la velocidad de procesamiento de imagen y aun así no me convenció mucho el resultado que obtuve, sigo prefiriendo la estabilidad de AForge.

Saludos
« Última modificación: 2 Febrero 2015, 20:46 pm por Eleкtro » En línea

nevachana

Desconectado Desconectado

Mensajes: 61


Ver Perfil
Re: [C#] ¿Cómo podría hacer esto?
« Respuesta #4 en: 5 Febrero 2015, 18:54 pm »

No te preocupes, aquí nadie es mejor que nadie y todos vienen a aprender.
Hombre, por supuesto, solo debes obtener la imagen de la zona donde quieras buscar (puede ser una captura de la pantalla completa, claro), y si la imagen es demasiado grande redimensionar la imagen a unas dimensiones que te permitan realizar la búsqueda y comparación de imagen de una forma eficiente, rápida, pero sin aumentar el margen de falsos positivos, buscando esa relación (ej: 100x100 píxeles quizás, depende).

EDITO:
No me ha quedado claro que camino vas a tomar para llevarlo a cabo, pero bueno vuelvo a aconsejarte utilizar la librería de AForge.Net, aunque he visto algoritmos de pago mucho más rápidos que obtienen los mismos o mejores resultados, pero AForge es excelente para ser gratis.

Realizar un algoritmo de ese estilo es relativamente fácil, de forma básica, pero es un tema muy delicado ya que procesar/comparar una imagen, una imagen que sea grande, es una operación muy lenta (y si usas metodologías anticuadas lo es aun mucho más), si no optimizas tu propio algoritmo hasta el punto que puede llegar a optimizarlo un grupo de desarrolladores profesionales en el tema que están vendiendo un producto de ese estilo entonces te puede quedar un algoritmo muy lento o incompetente en otros sentidos, y yo no soy ningún gurú en la optimización de este tema, pero llegué a implementar funcionalidades GPU para aumentar la velocidad de procesamiento de imagen y aun así no me convenció mucho el resultado que obtuve, sigo prefiriendo la estabilidad de AForge.

Saludos
ahora le hecho un vistazo ^^,y bueno no te dije lo que quería cambiar,a sí que te lo dejo ahora :P , estoy usando una lista de coordenadas.
a.MouseClick("Left", X, Y, 1, 1);
y bueno,resulta que donde quiero pulsar aparece de forma aleatoria en la pantalla,por lo que rara vez clicaba,y por eso necesitaba lo de las imágenes ^^
En línea

nevachana

Desconectado Desconectado

Mensajes: 61


Ver Perfil
Re: [C#] detectar imagen y obtener coordenadas
« Respuesta #5 en: 6 Febrero 2015, 16:59 pm »

Hola ^^ sabrías qué falla aquí?
Código
  1.    Bitmap bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
  2.                Graphics gfxScreenshot = Graphics.FromImage(bmpScreenshot);
  3.                gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);
  4.                System.Drawing.Bitmap sourceImage = new Bitmap (@"C:\Users\PC\Documents\Visual Studio 2012\Projects\NeoBux\NeoBux\obj\Debug\Ball.bmp");            
  5.                System.Drawing.Bitmap template = new Bitmap(bmpScreenshot);
  6.                ExhaustiveTemplateMatching tm = new ExhaustiveTemplateMatching(0.921f);
  7.                TemplateMatch[] matchings = tm.ProcessImage(sourceImage, template);//fallo aquí
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.810



Ver Perfil
Re: [C#] detectar imagen y obtener coordenadas
« Respuesta #6 en: 7 Febrero 2015, 14:56 pm »

sabrías qué falla aquí?

Porfavor, cuando formules una pregunta sobre un error expecífico, asegúrate de MOSTRAR el mensaje de la excepción.

Muestra la información necesaria para intentar ayudarte, ese método tiene muchos overloads y puede dar muchos errores distintos, que podrías solucioanrlo viendo la documentación oficial.

De todas formas me imagino que estás teniendo una excepción del tipo UnsuportedImageFormatException, ya que para el objeto template estás utilizando el constructor del Bitmap que por defecto asigna un canal ARGB de 32bpp, y aparte de eso estas asignando manualmente en el otro bitmap el mismo canal y profundidad de bits, y ese tipo de formato no está soportado por el método en cuestión, simplemente usa el formato de pixel a Format24bppRgb.

Saludos
« Última modificación: 7 Febrero 2015, 16:08 pm por Eleкtro » En línea

GonzaFz

Desconectado Desconectado

Mensajes: 69


Ver Perfil WWW
Re: [C#] detectar imagen y obtener coordenadas
« Respuesta #7 en: 7 Febrero 2015, 15:43 pm »

Yo una vez hice (copie en parte) un algoritmo ImageSearch bastante eficiente como para una imagen 1024 x 768.
El algoritmo se basa en ir pixel por pixel comparando el primer pixel de la imagen X (imagen a buscar) con los pixeles de la imagen B (imagen base).
Por primera vez yo lo había hecho con GetPixel (funcion de la libreria grafica de C#) pero era muy lento. Buscando en internet encontré que a través de punteros podes acceder directamente a la memoria donde se encuentran almacenados cada pixel, haciendo que la velocidad aumente considerablemente.

Acá te dejo un link con la información necesaria:
http://bobpowell.net/lockingbits.aspx

Nunca probé AForge pero el metodo que yo te digo lo podes comprobar acá:


Quizas te parezca algo lento pero eso se debe a que la imagen la obtiene de un WebBrowser, si la sacas de algún archivo estático y comparás, va a ser muy veloz.

Obviamente se podria optimizar mucho mas, haciendo por ejemplo, lo que dice Elektro, dividir en partes de 100x100.

Saludos
En línea

nevachana

Desconectado Desconectado

Mensajes: 61


Ver Perfil
Re: [C#] detectar imagen y obtener coordenadas
« Respuesta #8 en: 7 Febrero 2015, 17:39 pm »

Porfavor, cuando formules una pregunta sobre un error expecífico, asegúrate de MOSTRAR el mensaje de la excepción.

Muestra la información necesaria para intentar ayudarte, ese método tiene muchos overloads y puede dar muchos errores distintos, que podrías solucioanrlo viendo la documentación oficial.

De todas formas me imagino que estás teniendo una excepción del tipo UnsuportedImageFormatException, ya que para el objeto template estás utilizando el constructor del Bitmap que por defecto asigna un canal ARGB de 32bpp, y aparte de eso estas asignando manualmente en el otro bitmap el mismo canal y profundidad de bits, y ese tipo de formato no está soportado por el método en cuestión, simplemente usa el formato de pixel a Format24bppRgb.

Saludos
Me da esta exepción:
'AForge.Imaging.UnsupportedImageFormatException' en AForge.Imaging.dll

Información adicional: Unsupported pixel format of the source or template image.

Código
  1.  Bitmap bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format24bppRgb);
  2.                Graphics gfxScreenshot = Graphics.FromImage(bmpScreenshot);
  3.                gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);
  4.                System.Drawing.Bitmap sourceImage = new Bitmap (@"C:\Users\PC\Documents\Visual Studio 2012\Projects\NeoBux\NeoBux\obj\Debug\Ball.bmp");            
  5.                System.Drawing.Bitmap template = new Bitmap(bmpScreenshot);
  6.                ExhaustiveTemplateMatching tm = new ExhaustiveTemplateMatching(0.921f);
  7.                TemplateMatch[] matchings = tm.ProcessImage(sourceImage, template);//fallo en esta línea
En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines