1

今日は、C# での画像処理で sth new を試してみました。

次のようなシナリオ: 2 つの白黒画像があります。ここで、両方の画像からすべての白いピクセル (x、y) を取得し、それらを戻り画像に入れたいと考えています。したがって、最終的に私のimage3には、image1とimage2のすべての白いピクセルが含まれています。安全でないポインターは高速であるため、使用しています。

したがって、コードでは、(x,y) の image1 == (x,y) の image2 かどうかを確認します。これは、両方の写真の同じ場所に白いピクセルがある可能性が非常に低いためです。

今の私のアプローチ:

private unsafe static Bitmap combine_img(Bitmap img1, Bitmap img2)
    {
        Bitmap retBitmap = img1;

        int width = img1.Width;
        int height = img1.Height;
        BitmapData image1 = retBitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
        BitmapData image2 = img2.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); // here an error

        byte* scan1 = (byte*)image1.Scan0.ToPointer();
        int stride1 = image1.Stride;

        byte* scan2 = (byte*)image2.Scan0.ToPointer();
        int stride2 = image2.Stride;

        for (int y = 0; y < height; y++)
        {
            byte* row1 = scan1 + (y * stride1);
            byte* row2 = scan2 + (y * stride2);

            for (int x = 0; x < width; x++)
            {
                if (row1[x] == row2[x])
                    row1[x] = 255;
            }
        }

        img1.UnlockBits(image1);
        img2.UnlockBits(image2);

        return retBitmap;
    }

残念ながら、2 番目の画像をロックしようとすると、画像が既にロックされているというエラーが返されます。

4

2 に答える 2

1

問題は、奇妙なことに、同じ画像を渡したということでした。ここでは修正されたコードです。

private unsafe static void combine_img(Bitmap img1, Bitmap img2)
    {
        BitmapData image1 = img1.LockBits(new Rectangle(0, 0, img1.Width, img1.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
        BitmapData image2 = img2.LockBits(new Rectangle(0, 0, img2.Width, img2.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

        int bytesPerPixel = 3;

        byte* scan1 = (byte*)image1.Scan0.ToPointer();
        int stride1 = image1.Stride;

        byte* scan2 = (byte*)image2.Scan0.ToPointer();
        int stride2 = image2.Stride;

        for (int y = 0; y < img1.Height; y++)
        {
            byte* row1 = scan1 + (y * stride1);
            byte* row2 = scan2 + (y * stride2);

            for (int x = 0; x < img1.Width; x++)
            {
                if (row2[x * bytesPerPixel] == 255)
                    row1[x * bytesPerPixel] = row1[x * bytesPerPixel - 1] = row1[x * bytesPerPixel-2] = 255;
            }
        }
        img1.UnlockBits(image1);
        img2.UnlockBits(image2);
    }
于 2013-12-09T15:32:15.633 に答える
0

2 番目のイメージは 24 ビット イメージではないと思います。多分次のようなものを試してください:

BitmapData image2 = img2.LockBits(new Rectangle(0, 0, img2.Width, img2.Height), ImageLockMode.ReadWrite, img2.PixelFormat);

この場合、常にこの行を渡しますが (私が推測します)、問題は、実際に 24 ビット イメージまたは 32 ビット イメージを扱っているかどうかわからないことです。

于 2014-09-19T08:28:41.303 に答える