C# RGB圖像和灰度圖像互轉的實現
更新時間:2023年08月18日 15:18:43 作者:wangnaisheng
在我們的圖像類型教程中定義了RGB顏色模型和灰度格式,本文主要介紹了C# RGB圖像和灰度圖像互轉的實現,文中通過代碼介紹的非常清楚,具有一定的參考價值,感興趣的可以了解一下
RGB圖像轉為灰度圖像
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); // 計算灰度圖像的總像素數 int grayPixelCount = width * height; // 遍歷RGB圖像的每個像素,將其轉為灰度值并寫入灰度圖像 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("灰度圖像路徑"); } } }
灰度圖像轉為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); // 計算RGB圖像的總像素數 int rgbPixelCount = width * height; // 遍歷灰度圖像的每個像素,將其轉為RGB值并寫入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圖像路徑"); } } }
到此這篇關于C# RGB圖像和灰度圖像互轉的實現的文章就介紹到這了,更多相關C# RGB圖像和灰度圖像互轉內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!