欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C# RGB圖像和灰度圖像互轉(zhuǎn)的實(shí)現(xiàn)

 更新時(shí)間:2023年08月18日 15:18:43   作者:wangnaisheng  
在我們的圖像類型教程中定義了RGB顏色模型和灰度格式,本文主要介紹了C# RGB圖像和灰度圖像互轉(zhuǎn)的實(shí)現(xiàn),文中通過(guò)代碼介紹的非常清楚,具有一定的參考價(jià)值,感興趣的可以了解一下

RGB圖像轉(zhuǎn)為灰度圖像

using System;
using System.Drawing;
using System.Drawing.Imaging;
namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // 創(chuàng)建RGB圖像
            Image img = new Bitmap("RGB圖像路徑");
            // 獲取RGB圖像的Width和Height
            int width = img.Width;
            int height = img.Height;
            // 創(chuàng)建灰度圖像
            Image grayImg = new Bitmap(width, height);
            // 獲取灰度圖像的BytesPerPixel
            int grayBytesPerPixel = grayImg.GetPixelFormatSize(Color.Format32bppArgb);
            // 計(jì)算灰度圖像的總像素?cái)?shù)
            int grayPixelCount = width * height;
            // 遍歷RGB圖像的每個(gè)像素,將其轉(zhuǎn)為灰度值并寫(xiě)入灰度圖像
            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    Color c = img.GetPixel(x, y);
                    int r = (int)(c.R / 255 * 255);
                    int g = (int)(c.G / 255 * 255);
                    int b = (int)(c.B / 255 * 255);
                    int gray = (r + g + b) / 3;
                    grayImg.SetPixel(x, y, Color.FromArgb(gray));
                }
            }
            // 顯示灰度圖像
            grayImg.Save("灰度圖像路徑");
        }
    }
}

灰度圖像轉(zhuǎn)為RGB圖像

using System;
using System.Drawing;
using System.Drawing.Imaging;
namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // 創(chuàng)建灰度圖像
            Image img = new Bitmap("灰度圖像路徑");
            // 獲取灰度圖像的Width和Height
            int width = img.Width;
            int height = img.Height;
            // 創(chuàng)建RGB圖像
            Image rgbImg = new Bitmap(width, height);
            // 獲取RGB圖像的BytesPerPixel
            int rgbBytesPerPixel = rgbImg.GetPixelFormatSize(Color.Format32bppArgb);
            // 計(jì)算RGB圖像的總像素?cái)?shù)
            int rgbPixelCount = width * height;
            // 遍歷灰度圖像的每個(gè)像素,將其轉(zhuǎn)為RGB值并寫(xiě)入RGB圖像
            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    Color c = img.GetPixel(x, y);
                    int gray = c.R;
                    rgbImg.SetPixel(x, y, Color.FromArgb(gray, gray, gray));
                }
            }
            // 顯示RGB圖像
            rgbImg.Save("RGB圖像路徑");
        }
    }
}

到此這篇關(guān)于C# RGB圖像和灰度圖像互轉(zhuǎn)的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)C# RGB圖像和灰度圖像互轉(zhuǎn)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論