Faldt lige over dit problem, og så at ingen havde postet kode
Følgende virker fint, men er fuldstændigt uoptimeret. Denne metode matcher et helt bitmap, så du skal selvfølgelig kun matche på pixels, hvor din patterns har alpha!=0.
/**
* Do image match
*
* We do naive brute force pattern matching:
* We start with a source image, sImage, and a pattern image, pImage.
* To make things easy, the source must be at least the size of the pattern,
* i.e., we must be able to find a complete match.
*
* We proceed as follows:
* for all pixels in range in sImage
* for all pixels in pImage
* match = true;
* if !( sImage.pixelAt(s_x,s_y) == pImage.pixelAt(p_x,p_y) )
* match = false;
* break;
* end
* if match
* report results!
* end
*
* the ranges we must iterate through in the outer loop is
* [0..sImage.Height-pImage.Height] and [0..sImage.Width-pImage.Width]
*/
private void button2_Click(object sender, EventArgs e)
{
Bitmap sImage = (Bitmap)sourcePictureBox.Image,
pImage = (Bitmap)patternPictureBox.Image,
rImage; // result image
if (sImage != null && pImage != null && sImage.Width >= pImage.Width &&
sImage.Height >= pImage.Height) {
int difX = sImage.Width - pImage.Width;
int difY = sImage.Height - pImage.Height;
for (int i = 0; i < sImage.Height - difY; i++) {
for (int j = 0; j < sImage.Width - difX; j++) {
bool match = true;
for (int k = 0; k < pImage.Height && match; k++) {
for (int m = 0; m < pImage.Width; m++) {
if (!(sImage.GetPixel(j+m, i+k).Equals(pImage.GetPixel(m, k)))) {
match = false;
break;
}
}
}
if (match) {
rImage = new Bitmap(sImage);
Graphics g = Graphics.FromImage(rImage);
g.DrawRectangle(new Pen(Color.Red), j, i, pImage.Width-1, pImage.Height-1);
targetPictureBox.Image = rImage;
MessageBox.Show("match @ ("+j+","+i+")","Match!");
return;
}
}
}
MessageBox.Show("Sorry, no match was found.", "No match!");
}
}
Indlæg senest redigeret d. 11.03.2011 15:50 af Bruger #16471