[英]How can I search for a string say “xyz” in the pixel value's of an image using c# or Vb.net
我面临一个挑战,我需要找到一个特定的字符串:例如“ 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。如果是,则找到了它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.