0

少し変更を加えてデスクトップの2つのスクリーショットを撮り、win32apiを使用してプログラムで2つの画像を比較します。私の画像拡張子はjpgで、画像の高さと幅はどちらも:-height:-768 width:-1366でした。stopwatchクラスを使用して、diff画像を取得してデスクトップに保存するのにかかる時間を確認します。私はそれが47ミリ秒かかっていることを発見しました。ルーチンにかかる時間を最小限に抑える方法はありますか。これが私のルーチンコードです。私のルーチンを見て、このルーチンにかかる時間をどのように短縮できるかを調べてください。ありがとう

    private void button1_Click(object sender, EventArgs e)
    {
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();

        Bitmap firstImg = new Bitmap(@"C:\Users\TRIDIP\Desktop\pic1.jpg");
        Bitmap secondImg = new Bitmap(@"C:\Users\TRIDIP\Desktop\pic2.jpg");

        Rectangle bounds = GetBoundingBoxForChanges(firstImg, secondImg);

        if (bounds == Rectangle.Empty)
        {
    return;
        }

        Bitmap diff = new Bitmap(bounds.Width, bounds.Height);
        Graphics g = Graphics.FromImage(diff);
        g.DrawImage(secondImg, 0, 0, bounds, GraphicsUnit.Pixel);
        g.Dispose();

        stopwatch.Stop();

        string strmm = string.Format("Time elapsed {0} {1} {2} {3}",  stopwatch.Elapsed.Hours.ToString(), stopwatch.Elapsed.Minutes.ToString(), stopwatch.Elapsed.Seconds.ToString(), stopwatch.Elapsed.Milliseconds.ToString());
        MessageBox.Show(strmm);
    }

    private Rectangle GetBoundingBoxForChanges(Bitmap _prevBitmap, Bitmap _newBitmap)
    {
        // The search algorithm starts by looking
        //    for the top and left bounds. The search
        //    starts in the upper-left corner and scans
        //    left to right and then top to bottom. It uses
        //    an adaptive approach on the pixels it
        //    searches. Another pass is looks for the
        //    lower and right bounds. The search starts
        //    in the lower-right corner and scans right
        //    to left and then bottom to top. Again, an
        //    adaptive approach on the search area is used.
        //

        // Note: The GetPixel member of the Bitmap class
        //    is too slow for this purpose. This is a good
        //    case of using unsafe code to access pointers
        //    to increase the speed.
        //

        // Validate the images are the same shape and type.
        //
        if (_prevBitmap.Width != _newBitmap.Width ||
            _prevBitmap.Height != _newBitmap.Height ||
            _prevBitmap.PixelFormat != _newBitmap.PixelFormat)
        {
            // Not the same shape...can't do the search.
            //
            return Rectangle.Empty;
        }

        // Init the search parameters.
        //
        int width = _newBitmap.Width;
        int height = _newBitmap.Height;
        int left = width;
        int right = 0;
        int top = height;
        int bottom = 0;

        BitmapData bmNewData = null;
        BitmapData bmPrevData = null;
        try
        {
            // Lock the bits into memory.
            //
            bmNewData = _newBitmap.LockBits(new Rectangle(0, 0, _newBitmap.Width, _newBitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
            bmPrevData = _prevBitmap.LockBits(new Rectangle(0, 0, _prevBitmap.Width, _prevBitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);

            // The images are ARGB (4 bytes)
            //
            int numBytesPerPixel = 4;

            // Get the number of integers (4 bytes) in each row
            //    of the image.
            //
            int strideNew = bmNewData.Stride / numBytesPerPixel;
            int stridePrev = bmPrevData.Stride / numBytesPerPixel;

            // Get a pointer to the first pixel.
            //
            // Note: Another speed up implemented is that I don't
            //    need the ARGB elements. I am only trying to detect
            //    change. So this algorithm reads the 4 bytes as an
            //    integer and compares the two numbers.
            //
            System.IntPtr scanNew0 = bmNewData.Scan0;
            System.IntPtr scanPrev0 = bmPrevData.Scan0;

            // Enter the unsafe code.
            //
            unsafe
            {
                // Cast the safe pointers into unsafe pointers.
                //
                int* pNew = (int*)(void*)scanNew0;
                int* pPrev = (int*)(void*)scanPrev0;

                // First Pass - Find the left and top bounds
                //    of the minimum bounding rectangle. Adapt the
                //    number of pixels scanned from left to right so
                //    we only scan up to the current bound. We also
                //    initialize the bottom & right. This helps optimize
                //    the second pass.
                //
                // For all rows of pixels (top to bottom)
                //
                for (int y = 0; y < _newBitmap.Height; ++y)
                {
                    // For pixels up to the current bound (left to right)
                    //
                    for (int x = 0; x < left; ++x)
                    {
                        // Use pointer arithmetic to index the
                        //    next pixel in this row.
                        //
                        if ((pNew + x)[0] != (pPrev + x)[0])
                        {
                            // Found a change.
                            //
                            if (x < left)
                            {
                                left = x;
                            }
                            if (x > right)
                            {
                                right = x;
                            }
                            if (y < top)
                            {
                                top = y;
                            }
                            if (y > bottom)
                            {
                                bottom = y;
                            }
                        }
                    }

                    // Move the pointers to the next row.
                    //
                    pNew += strideNew;
                    pPrev += stridePrev;
                }

                // If we did not find any changed pixels
                //    then no need to do a second pass.
                //
                if (left != width)
                {
                    // Second Pass - The first pass found at
                    //    least one different pixel and has set
                    //    the left & top bounds. In addition, the
                    //    right & bottom bounds have been initialized.
                    //    Adapt the number of pixels scanned from right
                    //    to left so we only scan up to the current bound.
                    //    In addition, there is no need to scan past
                    //    the top bound.
                    //

                    // Set the pointers to the first element of the
                    //    bottom row.
                    //
                    pNew = (int*)(void*)scanNew0;
                    pPrev = (int*)(void*)scanPrev0;
                    pNew += (_newBitmap.Height - 1) * strideNew;
                    pPrev += (_prevBitmap.Height - 1) * stridePrev;

                    // For each row (bottom to top)
                    //
                    for (int y = _newBitmap.Height - 1; y > top; y--)
                    {
                        // For each column (right to left)
                        //
                        for (int x = _newBitmap.Width - 1; x > right; x--)
                        {
                            // Use pointer arithmetic to index the
                            //    next pixel in this row.
                            //
                            if ((pNew + x)[0] != (pPrev + x)[0])
                            {
                                // Found a change.
                                //
                                if (x > right)
                                {
                                    right = x;
                                }
                                if (y > bottom)
                                {
                                    bottom = y;
                                }
                            }
                        }

                        // Move up one row.
                        //
                        pNew -= strideNew;
                        pPrev -= stridePrev;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            int xxx = 0;
        }
        finally
        {
            // Unlock the bits of the image.
            //
            if (bmNewData != null)
            {
                _newBitmap.UnlockBits(bmNewData);
            }
            if (bmPrevData != null)
            {
                _prevBitmap.UnlockBits(bmPrevData);
            }
        }

        // Validate we found a bounding box. If not
        //    return an empty rectangle.
        //
        int diffImgWidth = right - left + 1;
        int diffImgHeight = bottom - top + 1;
        if (diffImgHeight < 0 || diffImgWidth < 0)
        {
            // Nothing changed
            return Rectangle.Empty;
        }

        // Return the bounding box.
        //
        return new Rectangle(left, top, diffImgWidth, diffImgHeight);
    }
4

3 に答える 3

1

まず、平均速度を決定するために、コードを数百/数千回実行するタイミングをとることをお勧めします。単一のパスは、コードのタイミングを計る良い方法ではありません。また、ディスクから 2 つの大きなイメージをロードしているため、差分操作全体よりも簡単に時間がかかる可能性があるため、タイミング テストからロード プロセスを削除したい場合があります (そのコードを最適化するためにできることは何もないため)。

上/左、次に下/右を探すことで、正しい道を歩み始めました。しかし、おそらくあなたはもう少しうまくやることができます。早期終了や不必要な作業を探す必要があります。たとえば、最初のループが上/左/下/右を追跡するのはなぜですか? 最初の差分に到達する前に、ボトムを更新する必要があるかどうかを確認しても意味がありません。top が見つかったら、それを更新する必要があるかどうかを確認しても意味がありません。したがって、ループ内の状態をあまり更新しないようにループを分割することを検討してください (ただし、考慮するピクセル数を増やすことはありません)。

次に、ピクセルあたりのオーバーヘッドを減らし、プロセッサ/バス/メモリ アーキテクチャの知識を活用する必要があります。たとえば、64 ビット プロセッサを使用している場合、一度に 32 ビットを読み取ると、一度に 64 ビットを読み取るため、long (Int64) を使用してペアを比較します1つだけではなく、反復ごとのピクセル数。これにより、プロセッサのレジスタ幅がより有効に利用され、ループの反復回数が半分になります (x 値への加算回数と、ループを再度周回する分岐の回数が半分になります)。(注: 幅が奇数の画像には注意する必要があります。異なるピクセルのペアを見つけた場合は、ペア内の各ピクセルをチェックして、差分がどこにあるかを正確に判断する必要があります)。プロセッサ/バス アーキテクチャに応じて、より広いデータ型を使用すると、さらに効果が得られる場合があります。

次に、キャッシュの一貫性が役立つかどうかを確認できます。2 番目 (下/右) のループでは、X 値を逆方向に反復しています。プロセッサのアーキテクチャによっては、前方に反復するよりもはるかに遅くなる可能性があります。そのため、各スキャンラインを前方に検索することで、平均してより良い時間を得ることができます。

(注:上記はこれを行うための「最適な方法」ではない可能性があり、プロセッサを高速化するハードウェアアクセラレーションのトリックが存在する可能性がありますが、怠惰がどのように役立つかについてのアイデアを提供してくれることを願っています.はるかに速く進みます)

于 2012-12-12T21:32:00.597 に答える
0

このようなコードでは、x>ループのすぐ内側を削除できます(ループ「x」にも同じチェックがあります)

for (int x = _newBitmap.Width - 1; x > right; x--)
// Found a change.
//
if (x > right)
{
    right = x;
}

ただし、最適化する前にコードをリファクタリングしてみてください。

于 2012-12-12T19:29:58.120 に答える
0

質問に対する答えではありませんが、参考になるかもしれません。

まず第一に、あなたは画面上での画像の描画にほとんどの時間を費やしており、画像を比較していないと思います. 通常は重い操作であるドローなしで時間を測定してみてください。

第 2 に、時間測定の前にメソッドを 1 回 (または 2 回) 実行することをお勧めします。最初にコードを実行するときは、実行に少し時間がかかる可能性があるためです。合計時間を 1000 倍して、平均見積もりを取得します。

最後になりましたが、おそらくいくつかのピクセルをスキップして、すべてのピクセルをチェックしても、良い結果が得られるでしょうか?

于 2012-12-12T19:18:48.347 に答える