Analizador De Imágenes PGM Y Visualización De Consola En C#

Este programa lee un archivo de imagen PGM en formato binario (P5) y representa sus tonos de gris en la consola con diferentes caracteres según el valor de intensidad. El programa primero procesa el encabezado del archivo PGM, extrayendo el ancho, la altura y el valor máximo de intensidad. A continuación, lee los valores de píxel y los muestra en la consola con símbolos específicos para los diferentes rangos de intensidad. La asignación es la siguiente:

- Intensidad > 200: espacio en blanco
- Intensidad entre 150 y 199: punto (.)
- Intensidad entre 100 y 149: guión (-)
- Intensidad entre 50 y 99: signo igual (=)
- Intensidad entre 0 y 49: almohadilla (#)

El nombre del archivo debe proporcionarse mediante la línea de comandos y el programa procesará y mostrará automáticamente la imagen utilizando estas representaciones.



Grupo

Manejo de archivos en C#

Objectivo

1. Lea el archivo PGM en formato binario (P5) desde el argumento de la línea de comandos.
2. Analice el encabezado para obtener el ancho, la altura y el valor máximo de intensidad de la imagen.
3. Lea los valores de los píxeles (tonos de gris) y asigne la intensidad de cada píxel a un carácter específico.
4. Envíe la representación de la imagen a la consola.
5. Asegúrese de que el programa pueda gestionar diferentes tamaños de imagen y tonos de gris.

El formato PGM es una de las versiones de los formatos de imagen NetPBM. Específicamente, es la variante capaz de gestionar imágenes en tonos de gris.

Ejemplo de ejercicio en C#

 Copiar código C#
using System;
using System.IO;

class PGMParser
{
    // Main method to execute the program
    static void Main(string[] args)
    {
        // Check if the user has provided a file name as a command-line argument
        if (args.Length == 0)
        {
            Console.WriteLine("Please provide a PGM file name as a command-line argument.");
            return;
        }

        // Define the file path from the command-line argument
        string filePath = args[0];

        // Open the PGM file for reading in binary mode
        using (BinaryReader reader = new BinaryReader(File.Open(filePath, FileMode.Open)))
        {
            // Read the header (first line is P5)
            string header = new string(reader.ReadChars(2)); // "P5"
            if (header != "P5")
            {
                Console.WriteLine("Invalid PGM format. This program only supports binary PGM (P5) format.");
                return;
            }

            // Skip comments (if any) and read the width and height from the next line
            string line;
            do
            {
                line = ReadLine(reader);
            } while (line.StartsWith("#")); // Ignore comment lines

            // Read the width and height from the header
            string[] dimensions = line.Split(' ');
            int width = int.Parse(dimensions[0]);
            int height = int.Parse(dimensions[1]);

            // Read the maximum intensity value (usually 255)
            int maxIntensity = int.Parse(ReadLine(reader));

            // Read the pixel values (shades of gray)
            byte[] pixels = reader.ReadBytes(width * height);

            // Process and display the image in the console
            int pixelIndex = 0;
            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    // Get the intensity of the current pixel
                    int intensity = pixels[pixelIndex++];

                    // Map the intensity to a specific character
                    char displayChar = MapIntensityToChar(intensity);

                    // Output the character to the console
                    Console.Write(displayChar);
                }
                // Move to the next line after each row of pixels
                Console.WriteLine();
            }
        }

        // Notify the user that the operation is complete
        Console.WriteLine("PGM file has been processed and displayed.");
    }

    // Helper method to read a line from the file
    static string ReadLine(BinaryReader reader)
    {
        string line = "";
        char c;
        while ((c = reader.ReadChar()) != '\n') // Read until newline character
        {
            line += c;
        }
        return line.Trim();
    }

    // Helper method to map intensity to corresponding character
    static char MapIntensityToChar(int intensity)
    {
        if (intensity > 200) return ' ';
        if (intensity >= 150) return '.';
        if (intensity >= 100) return '-';
        if (intensity >= 50) return '=';
        return '#';
    }
}

 Output

# . - =
= # . .
. - = #

Comparte este ejercicio de C#

Practica más ejercicios C# de Manejo de archivos en C#

¡Explora nuestro conjunto de ejercicios de práctica de C#! Diseñados específicamente para principiantes, estos ejercicios te ayudarán a desarrollar una sólida comprensión de los fundamentos de C#. Desde variables y tipos de datos hasta estructuras de control y funciones simples, cada ejercicio está diseñado para desafiarte gradualmente a medida que adquieres confianza en la programación en C#..