画像(干し草の山)の中から画像(針)を見つけたいのですが。
簡単にするために、デスクトップのスクリーンショットを2枚撮ります。1つのフルサイズ(干し草の山)と小さなもの(針)。次に、干し草の山の画像をループして、針の画像を見つけようとします。
- 針と干し草の山のスクリーンショットをキャプチャします
- 干し草の山をループし、干し草の山を探します[i]==針の最初のピクセル
- [2.がtrueの場合:]針の最後から2番目のピクセルをループして、それをhaystack[i]と比較します。
期待される結果:針の画像が正しい位置にあります。
私はすでにいくつかの座標/幅/高さ(A)でそれを動作させました。
ただし、ビットが「オフ」になっているように見えることがあるため、一致するものが見つかりません(B)。
何が間違っているのでしょうか?どんな提案でも大歓迎です。ありがとう。
var needle_height = 25;
var needle_width = 25;
var haystack_height = 400;
var haystack_width = 500;
A.入力例-一致
var needle = screenshot(5, 3, needle_width, needle_height);
var haystack = screenshot(0, 0, haystack_width, haystack_height);
var result = findmatch(haystack, needle);
B.入力例-一致なし
var needle = screenshot(5, 5, needle_width, needle_height);
var haystack = screenshot(0, 0, haystack_width, haystack_height);
var result = findmatch(haystack, needle);
1.針と干し草の山の画像をキャプチャします
private int[] screenshot(int x, int y, int width, int height)
{
Bitmap bmp = new Bitmap(width, height, PixelFormat.Format32bppArgb);
Graphics.FromImage(bmp).CopyFromScreen(x, y, 0, 0, bmp.Size);
var bmd = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height),
ImageLockMode.ReadOnly, bmp.PixelFormat);
var ptr = bmd.Scan0;
var bytes = bmd.Stride * bmp.Height / 4;
var result = new int[bytes];
Marshal.Copy(ptr, result, 0, bytes);
bmp.UnlockBits(bmd);
return result;
}
2.一致するものを見つけてください
public Point findmatch(int[] haystack, int[] needle)
{
var firstpixel = needle[0];
for (int i = 0; i < haystack.Length; i++)
{
if (haystack[i] == firstpixel)
{
var y = i / haystack_height;
var x = i % haystack_width;
var matched = checkmatch(haystack, needle, x, y);
if (matched)
return (new Point(x,y));
}
}
return new Point();
}
3.完全一致を確認します
public bool checkmatch(int[] haystack, int[] needle, int startx, int starty)
{
for (int y = starty; y < starty + needle_height; y++)
{
for (int x = startx; x < startx + needle_width; x++)
{
int haystack_index = y * haystack_width + x;
int needle_index = (y - starty) * needle_width + x - startx;
if (haystack[haystack_index] != needle[needle_index])
return false;
}
}
return true;
}