using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing ;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Bitmap bmp1;
private void 打开图像_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog()==DialogResult.OK)
{
bmp1 = (Bitmap)Image.FromFile(openFileDialog1.FileName);
}
pictureBox1.Image = bmp1;
}
public static Bitmap Cut(Bitmap b)
{
if (b == null)
{
return null;
}
int w = b.Width;
int h = b.Height;
int StartX = (w / 2) - 500;
int StartY = (h / 2) - 500;
int endX = (w / 2) + 500;
int endY = (w / 2) + 500;
int iWidth = 1000;
int iHeight = 1000;
Bitmap bitOut = new Bitmap(iWidth, iHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
Graphics g = Graphics.FromImage(bitOut);
g.DrawImage(b, new Rectangle(0, 0, iWidth, iHeight), new Rectangle(StartX, StartY, endX, endY), GraphicsUnit.Pixel);
g.Dispose();
return bitOut;
}
Bitmap bmp2 = Cut(bmp1);\\总是提示字段初始值无法引用非静态字段
private void button1_Click(object sender, EventArgs e)
{
Rectangle rect = new Rectangle(0, 0, bmp2.Width, bmp2.Height);
//以可读的方式锁定全部位图像素
System.Drawing.Imaging.BitmapData bmpData = bmp2.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, bmp2.PixelFormat);
IntPtr ptr = bmpData.Scan0;
int bytes = bmpData.Stride * bmpData.Height;
byte[] rgbValues = new byte[bytes];
System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
//灰度化
double colorTemp = 0;
//for (int i = 0; i < rgbValues.Length; i += 3)//对24位图像
//{
// colorTemp = rgbValues[i + 2] * 0.299 + rgbValues[i + 1] * 0.587 + rgbValues * 0.114;
// rgbValues = rgbValues[i + 1] = rgbValues[i + 2] = (byte)colorTemp;
//}
double R, G, B;
int n;
for (int i = 0; i < bmpData.Height; i++)
{
//只处理每行中是图像像素的数据,舍弃未用空间。
for (int j = 0; j < bmpData.Width * 3; j += 3)
{
colorTemp = rgbValues[i * bmpData.Stride + j + 2] * 0.299 + + rgbValues[i * bmpData.Stride + j] * 0.114;
R = rgbValues[i * bmpData.Stride + j + 2];
G = rgbValues[i * bmpData.Stride + j + 1] ;
B = rgbValues[i * bmpData.Stride + j];
if(R<G&&B<G)
{
if(R>40&&R<100)
{
R=G=B=0;
n++;
}
}
}
}
System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes);
bmp1.UnlockBits(bmpData);
Invalidate();
pictureBox2.Image = bmp1;
text1.Text = (n / (bmp2.Width * bmp2.Height)).ToString();
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
|