public static RemoveBg ( |
||
img | 原图片 | |
dgGrayValue | int | 前景背景分界灰度值 |
return | Image |
public static Image RemoveBg(Bitmap img, int dgGrayValue)
{
int width = img.Width;
int height = img.Height;
BitmapData bdata = img.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite,
PixelFormat.Format32bppRgb); //红绿蓝个八位,其余8位没使用
unsafe
{
byte* ptr = (byte*)bdata.Scan0.ToPointer();
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
if (ptr[1] > dgGrayValue)//背景点
{
ptr[0] = ptr[1] = ptr[2] = 255;
}
ptr += 4;
}
ptr += bdata.Stride - width * 4;
}
}
#region 内存法
//获取位图中第一个像素数据的地址
//int byteNum = width * height * 4;
////byte[] four = new byte[width *height ];
//byte[] rgbValue = new byte[byteNum];
////把内存中的图像copy到数组
//Marshal.Copy(ptr, rgbValue, 0, byteNum);
//for (int i = 0; i < rgbValue.Length; i += 4)
//{
// if (rgbValue[i] >= dgGrayValue) //是背景点
// {
// rgbValue[i] = rgbValue[i + 1] = rgbValue[i + 2] = 255;
// // four[i/4] = rgbValue[4];
// }
// else
// {
// //不是背景点的做标记,下一阶段处理噪点用**第四个字节默认值都是255**我们标记为 111
// rgbValue[i + 3] = 111;
// }
//}
////将修改好的数据复制到内存
//Marshal.Copy(rgbValue, 0, ptr, byteNum);
#endregion
//从内存中解锁
img.UnlockBits(bdata);
return img;
}
/// <summary> /// 去背景 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btn_bg_Click(object sender, EventArgs e) { Image img_noise = (Image)pb_grey.Image.Clone(); //得到灰度图像前景色临界值 // img_noise = ccccccmd.ImageHelper.RemoveBlock(img_noise,2);//报错 //int v = ImageProcess.GetDgGrayValue(img_noise); int v = ImageProcess.ComputeThresholdValue((Bitmap)img_noise); //Image test = ImageProcess.RemoveBg((Bitmap)img_noise ,v ); // int v2 = Test.ImageProcess.GetDgGrayValue(img_noise); Image img_bg = ImageProcess.RemoveBg((Bitmap)img_noise, v); //-----------去背景,内存法 imgBged = Image2Num((Bitmap)img_bg); WriteToFile(imgBged, "experiment\\" + Path.GetFileNameWithoutExtension(imgurl) + "_bged.txt"); pb_bg.Image = img_bg; }