首页 > 解决方案 > 生成字节/asm 文件的图像

问题描述

我正在做一个机器学习项目。以下是我的要求。

  1. 给定一个不同文件大小的 *.bytes 或 .asm 文件
  2. 生成文件的灰度(rgb)图像,其值应介于 0 - 255 之间
  3. 将所有图像的大小调整为 N x N 像素。

我正在尝试在 C# 中生成图像(因为我比 Python 更熟悉它)。我在下面有这段代码,它试图创建图像,但我有两个问题

  1. 它使用 byte[] 的长度来确定宽度和高度,这意味着我必须找到 byte[] 的平方根来确定长度和宽度。我不想要这个,我希望它根据我给它的任何尺寸创建图像。
  2. 我不确定生成的图像是否正确,因为我从灰度图像中输入了一个字节 [],但生成的图像与原始图像完全不同。
    static void Main(string[] args)
        {
            string fileRead = @"C:\Users\User\source\repos\ExeTobinary\Testing\grayscale.jpg";
            string fileSave = @"C:\Users\User\source\repos\ExeTobinary\Testing\Test.jpg";

            Random r = new Random();
            int width = 1000;
            int height = 1000;
            byte[] pixelValues = new byte[width * height];
         /*   for (int i = 0; i < pixelValues.Length; ++i)
            {
                //Just create random pixel values
                pixelValues[i] = (byte)r.Next(0, 255);
            }*/

            pixelValues = File.ReadAllBytes(fileRead);


            GetBitmap(pixelValues, width, height, 1);

        }

继承人的方法

   public static Bitmap  GetBitmap(byte[] _rawDataPresented, int _width, int _height, double scalingFactor)
        {
            Bitmap image = new Bitmap(_width, _height, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);  //Format8bppIndexed

            // konwersja palety idexed na skale szarosci
            ColorPalette grayPalette = image.Palette;
            Color[] entries = grayPalette.Entries;
            for (int i = 0; i < 256; i++)
            {
                Color grayC = new Color();
                grayC = Color.FromArgb((byte)i, (byte)i, (byte)i);
                entries[i] = grayC;
            }
            image.Palette = grayPalette;

            // wrzut binary data do bitmapy
            BitmapData dataR = image.LockBits(new Rectangle(Point.Empty, image.Size), ImageLockMode.WriteOnly, image.PixelFormat);
            Marshal.Copy(_rawDataPresented, 0, dataR.Scan0, _rawDataPresented.Length);
            image.UnlockBits(dataR);

            // skalowanie wielkosci
            Size newSize = new Size((int)(image.Width * scalingFactor), (int)(image.Height * scalingFactor));
            Bitmap scaledImage = new Bitmap(image, newSize);

            string fileSave = @"C:\Users\User\source\repos\ExeTobinary\Testing\Test.jpg";
            scaledImage.Save(fileSave, ImageFormat.Jpeg);

            return scaledImage;
        }

我在这里使用了灰度图像来测试该方法的有效性,但输入文件可能是 *.bytes 或 .asm 文件。有人可以在这个方向上做过类似的帮助吗...回顾一下,我想从 .bytes 或 .asm 文件生成灰度图像,这些文件最终需要具有相同的尺寸。我更喜欢 C# 中的代码示例,但如果我得到一个 python 版本,我不会介意。

这是我在测试中使用的灰度图像 测试图像

这是我的结果 生成的图像

标签: c#image

解决方案


推荐阅读