今天花了點時間,幫一個朋友做了一個小工具。他需要判斷圖檔中,黑色及白色的分佈。
其實這是有問題的需求,但因為我朋友也不是專科,哪裡會懂問題在哪。
其實問題很簡單,就是圖檔的灰階,沒有純黑或純白。就算有~也是只少數的像素有這個特徵。
那怎麼辦?不就不用寫了....嗯~但,既然沒辦法100%符合期待,那就轉個彎囉~~
這個觀念是從相片後製而來。其實在圖檔像素中,我們會利用「灰色」來做所謂的白平衡。
因為灰色在RGB中,是中間色,所以可以利用這個中間值來大概的判斷。
程式中,就是把每一個像素取出後,判斷若色彩值大於灰色。就是偏黑,反之就是偏白。
利用此作法,來判斷圖檔中,黑白的分佈情況。
以下是程式寫法~~在此貼出,我想我以後還是會用到
private void button1_Click(object sender, EventArgs e)
{
openFileDialog.ShowDialog(this);
txtImgPath.Text = openFileDialog.FileName;
FilePath = openFileDialog.FileName;
int WhitePixel = 0;
int BlackPixel = 0;
int TTLPixel = 0;
System.IO.FileStream fs = new System.IO.FileStream(FilePath, System.IO.FileMode.Open);
System.IO.BinaryReader br = new System.IO.BinaryReader(fs);
Image oImg = Image.FromStream(br.BaseStream);
br.Close();
fs.Close();
fs.Dispose();
pictureBox.Image = oImg;
Bitmap oBitMap = new Bitmap(oImg);
int Height = oBitMap.Height;
int Width = oBitMap.Width;
int[, ,] rgbData = new int[Width, Height, 3];
int PixVal = 0;
for (int y = 0; y < Height; y++)
{
for (int x = 0; x < Width; x++)
{
Color color = oBitMap.GetPixel(x, y);
rgbData[x, y, 0] = color.R;
rgbData[x, y, 1] = color.G;
rgbData[x, y, 2] = color.B;
PixVal = color.R + (color.G * 256) + (color.B * 256 * 256);
if (PixVal <= 8421504 && color.R >= 128 && color.G >= 128 && color.B >= 128)
{
BlackPixel++;
}
else
{ WhitePixel++; }
TTLPixel++;
}
}
txtPixelTtl.Text = TTLPixel.ToString();
txtPixelWhite.Text = WhitePixel.ToString();
txtPixelBlack.Text = BlackPixel.ToString();
txtBlackkPercent.Text = decimal.Round((Convert.ToDecimal(BlackPixel) / Convert.ToDecimal(TTLPixel) * 100), 0).ToString() + "%";
txtWhitePercent.Text = decimal.Round((Convert.ToDecimal(WhitePixel) / Convert.ToDecimal(TTLPixel) * 100), 0).ToString() + "%";
}
留言列表