效果: 功能: 通过过滤条件找到图片有效边缘,然后剪切 其他说明: 1.时间匆忙,代码没有组织,比较乱 2.没想到什么好算法,最土的,4次嵌套找到4个点,然后剪裁 3.过滤条件可以根据实际情况自己修改 4.嵌套循环一次跨10像素,所以最后为了避免意外,追加20像素边距. 代码: Bitmap image =new Bitmap(pictureBox1.Image); Bitmap new_image; //只保留有效区域 int iWidth = image.Width; int iHeight = image.Height; int startX = -1; int startX_T = -1; int startY = -1; int startY_T = -1; int endX = -1; int endX_T = -1; int endY = -1; int endY_T = -1; Color colCurr; //通过两次嵌套确定起点xy for (int y = 0; y < iheight;="" y="y" +="" 10)="" {="" for="" (int="" x="0;" x="">< iwidth;="" x="x" +="" 10)="" {="" colcurr="image.GetPixel(x," y);="" if="" (convert.toint32(=""><200) {="" startx_t="x;" starty_t="y;" break;="" }="" }="" if="" (startx_t="" !="-1)" {="" break;="" }="" }="" for="" (int="" x="0;" x="">200)>< iwidth;="" x="x" +="" 10)="" {="" for="" (int="" y="0;" y="">< iheight;="" y="y" +="" 10)="" {="" colcurr="image.GetPixel(x," y);="" if="" (convert.toint32(colcurr.r.tostring())="">< 200)="" {="" if="" (startx_t=""> x) { startX = x; } else { startX = startX_T; } if (startY_T > y) { startY = y; } else { startY = startY_T; } break; } } if (startX != -1) { break; } } //通过两次嵌套确定结束点xy for (int y = iHeight - 1; y >= 0; y = y - 10) { for (int x = iWidth - 1; x >= 0; x = x - 10) { colCurr = image.GetPixel(x, y); if (Convert.ToInt32(colCurr.R.ToString()) < 200)="" {="" endy_t="y;" endx_t="x;" break;="" }="" }="" if="" (endy_t="" !="-1)" {="" break;="" }="" }="" for="" (int="" x="iWidth" -="" 1;="" x="">= 0; x = x - 10) { for (int y = iHeight - 1; y >= 0; y = y - 10) { colCurr = image.GetPixel(x, y); if (Convert.ToInt32(colCurr.R.ToString()) < 200)="" {="" if="" (endx_t=""> x) { endX = endX_T; } else { endX = x; } if (endY_T > y) { endY = endY_T; } else { endY = y; } break; } } if (endY != -1) { break; } } Console.WriteLine('startX:' + startX + 'startY:' + startY + 'entX:' + endX + 'endY:' + endY); //处理边缘,强制+20 if (startX > 20) { startX = startX - 20; } else { startX = 0; } if (startY > 20) { startY = startY - 20; } else { startY = 0; } if (iWidth - endX > 20) { endX = endX + 20; } else { endX = iWidth; } if (iHeight - endY > 20) { endY = endY + 20; } else { endY = iHeight; } Rectangle cropArea = new Rectangle(); cropArea.X = startX; cropArea.Y = startY; cropArea.Width = endX - startX; cropArea.Height = endY - startY; new_image = image.Clone(cropArea, image.PixelFormat); this.pictureBox2.Image = new_image; new_image.Save('eff_new.png', System.Drawing.Imaging.ImageFormat.Png); http://download.csdn.net/detail/wenshanshan0824/9548644 |
|
来自: goodwangLib > 《C#图像》