c#读取图像灰度值

0 篇文章 0 订阅
0 篇文章 0 订阅

1. 申请位图载入图像

 Bitmap bm =(Bitmap ) pictureBox1.Image; 

2. 读取其中的灰度值

     bm.GetPixel(x,y)

         上述返回的是4元组,alpha值,R,G,B分别值

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#中进行图像二值化,可以使用以下步骤: 1. 读取图像:使用Bitmap类加载要处理的图像。 2. 转换为灰度图像:将加载的图像转换为灰度图像,方便后续处理。可以使用ColorMatrix类进行转换。 3. 进行二值化:将灰度图像中的像素灰度值与一个阈值进行比较,将灰度值大于阈值的像素设置为白色,小于阈值的像素设置为黑色。可以使用Bitmap类的SetPixel方法进行像素操作。 下面是一段示例代码: ```csharp Bitmap bmp = new Bitmap("image.jpg"); // 读取图像 Bitmap grayBmp = new Bitmap(bmp.Width, bmp.Height); // 创建灰度图像 float[][] colorMatrixElements = { new float[] { 0.299f, 0.299f, 0.299f, 0, 0 }, new float[] { 0.587f, 0.587f, 0.587f, 0, 0 }, new float[] { 0.114f, 0.114f, 0.114f, 0, 0 }, new float[] { 0, 0, 0, 1, 0 }, new float[] { 0, 0, 0, 0, 1 } }; ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements); // 创建灰度转换矩阵 using (Graphics g = Graphics.FromImage(grayBmp)) { g.DrawImage(bmp, new Rectangle(0, 0, grayBmp.Width, grayBmp.Height), 0, 0, bmp.Width, bmp.Height, GraphicsUnit.Pixel, new ImageAttributes() { ColorMatrix = colorMatrix }); // 转换为灰度图像 } int threshold = 128; // 设置阈值 for (int x = 0; x < grayBmp.Width; x++) { for (int y = 0; y < grayBmp.Height; y++) { Color color = grayBmp.GetPixel(x, y); int gray = (int)(color.R * 0.299 + color.G * 0.587 + color.B * 0.114); // 计算灰度值 Color newColor = gray > threshold ? Color.White : Color.Black; // 判断二值化结果 grayBmp.SetPixel(x, y, newColor); // 设置像素颜色 } } grayBmp.Save("binary.jpg"); // 保存二值化结果 ``` 以上代码中,将灰度值大于128的像素设置为白色,小于等于128的像素设置为黑色。可以根据实际情况调整阈值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值