我有一个挑战,我需要找到一个特定的字符串:示例"XYZ"(此字符串已在图像中编码)。
每个像素都由 ARGB 组成,我必须检查每个像素的红色 - 如果那样,则包含所需的字符串(3 个字符的字符串)。
我尝试了几件事,我能够读取每个像素的红色值的值,该值返回一个整数。
我的问题是:如何搜索图像的每个红色像素中出现这三个字符串?
任何建议将不胜感激
以下是我用来读取图像像素值的代码。
Bitmap img = new Bitmap("F:\pam\Wallpapers\red.jpg");
// MessageBox.Show("Image height:" + img.Height + "" + "Image width:" + img.Width);
// MessageBox.Show("Image found at"+img);
for (int i = 0; i < img.Width; i++)
{
for (int j = 0; j < img.Height; j++)
{
// String mark1 =
Color pixel = img.GetPixel(i,j);
pixel = Color.FromArgb(pixel.R);
// string a = Color.fr
int nPixelR = pixel.R;
// string q = img.GetPixel(0, 0);
//pixel.R
// img.GetPixel(0, 0);
string pixelColorStringValue =
pixel.R.ToString("D3") + " " +
pixel.G.ToString("D3") + " " +
pixel.B.ToString("D3") + ", ";
switch (pixelColorStringValue)
{
case "255 255 255":
{
// white pixel
break;
}
case "000 000 000":
{
// black pixel
break;
}
case "255 000 000":
{
// black pixel
break;
}
}
MessageBox.Show("pixel value" + pixel);
if (pixel.Equals("a"))
{
MessageBox.Show("Keyword Found:");
// **Store pixel here in a array or list or whatever**
}
}
}
您可以使用string strPix = (char)pixel.R + (char)pixel.G + (char)pixel.B;
,然后检查它是否与您的搜索字符串匹配?
编辑:或者更好的是:将您的 XYZ 转换为 RGB 并与像素进行比较?像这样:
var searchColor = Color.FromRgb('X', 'Y', 'Z');
然后将其与您的像素进行比较。
请注意,如果字符串从上到下编码为图像,则应交换for
循环。
private void Search()
{
SearchKeywordInRedPixels("xyz", "F:\pam\Wallpapers\red.jpg");
}
private void SearchKeywordInRedPixels(string keyword, string imagePath)
{
Bitmap image = new Bitmap(imagePath);
byte[] keywordBytes = Encoding.ASCII.GetBytes(keyword);
Point firstMatchingBytePos = Point.Empty;
int currentByteIndex = 0;
for (int y = 0; y < image.Height; y++)
{
for (int x = 0; x < image.Width; x++)
{
Color pixel = image.GetPixel(x, y);
if (pixel.R == keywordBytes[currentByteIndex])
{
if (currentByteIndex == 0)
firstMatchingBytePos = new Point(x, y);
if (currentByteIndex == keyword.Length - 1)
{
KeywordFound(keyword, firstMatchingBytePos);
currentByteIndex = 0;
}
else
{
currentByteIndex++;
}
}
else
{
currentByteIndex = 0;
}
}
}
}
private void KeywordFound(string keyword, Point pos)
{
string msg = String.Concat("Keyword ", keyword, "found at ", pos);
MessageBox.Show(msg);
}
遍历 2d 数组并查找 X。找到它后,检查右侧的值是否为 Y。如果是,请检查右侧两步的值是否为 Z。如果是,你已经找到了。