我想在圖像(乾草堆)內找到圖像(針)。在C中識別圖像內的圖像#
爲了讓事情變得簡單,我拍了兩張桌面截圖。一個全尺寸(乾草堆)和一個小(針)。然後,我通過乾草堆圖像循環,嘗試找到針圖像。
- 捕獲針和乾草堆截圖
- 遍歷大海撈針,尋找出草堆[I] ==針的第一像素
- [2.若爲真:]通過第二到最後一個像素循環針並將其與乾草堆比較[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.示例性輸入 - NO匹配
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;
}
這個技巧。先生,你是一位真正的天才。非常感謝您的幫助,以及您如何改進編碼的努力。 – fanti