C#,Aforge调用摄像头,实时处理图像,灰度化/二值化

王先生
2018-05-20 / 1 评论 / 20 阅读 / 正在检测是否收录...

https://img-blog.csdn.net/20180520180903818?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dhbmd5dTIzMw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70

//声明全局函数

private FilterInfoCollection videoDevices;
private VideoCaptureDevice videoSource;
private static int jj;

//Aforge调用摄像头

private void Form1_Load(object sender, EventArgs e)
        {
            videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            if (videoDevices.Count == 0)
            {
                throw new ApplicationException();
            }
            foreach(FilterInfo device in videoDevices)
            {
                comboBox1.Items.Add(device.Name);
            }
            comboBox1.SelectedIndex = 0;
        }

//链接摄像头

private void button1_Click(object sender, EventArgs e)
        {
            CameraConn();
        }

        private void CameraConn()
        {
            VideoCaptureDevice videoSource = new VideoCaptureDevice(videoDevices[comboBox1.SelectedIndex].MonikerString);

            videoSourcePlayer1.VideoSource = videoSource;
            videoSourcePlayer1.Start();

        }

//捕获摄像头当前画面,生成灰度化图片

private void button2_Click_1(object sender, EventArgs e)
        {
            pictureBox1.Image= videoSourcePlayer1.GetCurrentVideoFrame();
          
        }

//捕获摄像头当前画面,生成成二值化图片

private void button2_Click(object sender, EventArgs e)
        {
            Bitmap b = videoSourcePlayer1.GetCurrentVideoFrame();
            pictureBox1.Image = ConvertTo1Bpp1(b);
        }

--------------------------------------------------------灰度化,二值化函数操作方法-------------------------------------------

// 图像灰度化操作函数

public static Bitmap ToGray(Bitmap bmp)

{
    for (int i = 0; i < bmp.Width; i++)
    {
        for (int j = 0; j < bmp.Height; j++)
        {
            //获取该点的像素的RGB的颜色
            Color color = bmp.GetPixel(i, j);
            //利用公式计算灰度值
            int gray = (int)(color.R * 0.3 + color.G * 0.59 + color.B * 0.11);
            Color newColor = Color.FromArgb(gray, gray, gray);
            bmp.SetPixel(i, j, newColor);
        }
    }
    return bmp;
}

// 图像二值化1:取图片的平均灰度作为阈值,低于该值的全都为0,高于该值的全都为255

public static Bitmap ConvertTo1Bpp1(Bitmap bmp)

{
    int average = 0;

    average = 122;
    jj = average;  //将阈值传递出来
    for (int i = 0; i < bmp.Width; i++)
    {
        for (int j = 0; j < bmp.Height; j++)
        {
            //获取该点的像素的RGB的颜色
            Color color = bmp.GetPixel(i, j);
            int value = 255 - color.B;
            Color newColor = value > average ? Color.FromArgb(0, 0, 0) : Color.FromArgb(255, 255, 255);
            bmp.SetPixel(i, j, newColor);
        }
    }
    return bmp;
}

//用到的指令集

using AForge.Video.DirectShow;
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

评论 (1)

取消
  1. 头像
    admin 作者
    Windows 10 · Google Chrome
    @

    不错不错!

    回复