C# RGB图像转为灰度图像、灰度图像转为RGB图像

RGB图像转为灰度图像

cs 复制代码
using System;
using System.Drawing;
using System.Drawing.Imaging;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // 创建RGB图像
            Image img = new Bitmap("RGB图像路径");
            // 获取RGB图像的Width和Height
            int width = img.Width;
            int height = img.Height;
            // 创建灰度图像
            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图像

cs 复制代码
using System;
using System.Drawing;
using System.Drawing.Imaging;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // 创建灰度图像
            Image img = new Bitmap("灰度图像路径");
            // 获取灰度图像的Width和Height
            int width = img.Width;
            int height = img.Height;
            // 创建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图像路径");
        }
    }
}
相关推荐
R-G-B5 分钟前
【05】VM二次开发——模块参数配置--带渲染/不带渲染(WinForm界面调用 模块参数配置)
c#·vm二次开发·vm模块参数配置·vm在winform界面调用
R-G-B7 小时前
【12】大恒相机SDK C#开发 ——多相机开发,枚举所有相机,并按配置文件中的相机顺序 将所有相机加入设备列表,以便于对每个指定的相机操作
c#·大恒相机sdk·大恒多相机开发·大恒多相机枚举·大恒多相机指定顺序
R-G-B7 小时前
【13】大恒相机SDK C#开发 —— Fom1中实时处理的8个图像 实时显示在Form2界面的 pictureBox中
c#·大恒相机sdk·图像实时显示在另一个界面
向宇it12 小时前
【unity小技巧】封装一套 Unity 的植物生长系统
游戏·unity·c#·游戏引擎
NFA晨曦14 小时前
力扣刷题日常(7-8)
算法·leetcode·c#
踏上青云路15 小时前
C# 闭包
java·前端·c#
86Eric15 小时前
C# 入门教程(四)委托详解
c#·委托·多播委托
80岁小姑娘18 小时前
.NET Core部署服务器
c#
bubiyoushang88818 小时前
基于C#的CAN通讯接口程序
stm32·单片机·c#
工程师00718 小时前
C#接口的定义与使用
开发语言·c#·接口