欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#灰度化图像的实例代码

程序员文章站 2024-02-19 14:18:34
用伪语句可以表示如下 public bitmap grayscal(bitmap orgbmp){    建立一个与原图片等大的8位的图片...

用伪语句可以表示如下

public bitmap grayscal(bitmap orgbmp)
{
    建立一个与原图片等大的8位的图片
    取出原图像中的每一个点
    新图像的点=原图像点的红色量*系数1+绿色量*系数2+黄色量*系统3
    返回新图像
}

复制代码 代码如下:

/// <summary>
    /// 对图像进行点运算,
    /// </summary>
    public class pointtrans
    {
        private readonly double cb;
        private readonly double cg;
        private readonly double cr;

        /// <summary>
        /// 做点运算,要给每一个偏量,做一下设置,比如做图像的灰度图就需要现设置
        /// </summary>
        /// <param name="cr"></param>
        /// <param name="cg"></param>
        /// <param name="cb"></param>
        public pointtrans(double cr, double cg, double cb)
        {
            this.cr = cr;
            this.cg = cg;
            this.cb = cb;
        }

        public  bitmap grayscalebmp(bitmap orgdata)
        {
            int bmpwidth = orgdata.width, bmpheight = orgdata.height;
            bitmap destdata = imagetools.creategrayscaleimage(bmpwidth, bmpheight);
            rectangle bmprect=new rectangle(0,0,bmpwidth,bmpheight);

            bitmapdata orgbmpdata = orgdata.lockbits(bmprect, imagelockmode.readonly, pixelformat.format24bpprgb);

            bitmapdata destbmpdata = destdata.lockbits(bmprect, imagelockmode.writeonly, pixelformat.format8bppindexed);
            processfilter(orgbmpdata,destbmpdata);

            orgdata.unlockbits(orgbmpdata);
            destdata.unlockbits(destbmpdata);
            return destdata;

        }


        protected unsafe void processfilter(bitmapdata sourcedata, bitmapdata destinationdata)
        {
            // get width and height
            int width = sourcedata.width;
            int height = sourcedata.height;

            int srcoffset = sourcedata.stride - width*3;
            int dstoffset = destinationdata.stride - width;

            // do the job
            byte* src = (byte*) sourcedata.scan0.topointer();
            byte* dst = (byte*) destinationdata.scan0.topointer();

            // for each line
            for (int y = 0; y < height; y++)
            {
                // for each pixel
                for (int x = 0; x < width; x++, src += 3, dst++)
                {
                    *dst = (byte) (cr*src[rgb.r] + cg*src[rgb.g] + cb*src[rgb.b]);
                }
                src += srcoffset;
                dst += dstoffset;
            }
        }


    }