Unity 使用 GPGPU 計算,使用 ComputeShader 將圖片轉成灰階圖

傳統用 Texture2D 來做速度太慢,甚至使用 Texture2D.GetPixel(x, y).grayscale 也太慢,而且不能對細節微調。所以今天為大家展示用 ComputeShader ( GPU ) 將圖片轉成灰階。只要是你之前都使用 Texture2D 來做影像處理的話,那你今後可以用 ComputeShader 來取代,畢竟速度快上幾千倍嘛。不要說 Lag 了,以前不能 Realtime 的現在都能 Realtime,好了,唬爛到此結束,讓我們看以下程式碼。


C # :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Test : MonoBehaviour
{
    public Texture2D inputTexture;
    public RawImage outputImage;
    public ComputeShader shader;

    void Start ()
    {
        RenderTexture t = new RenderTexture (inputTexture.width, inputTexture.height, 24);
        t.enableRandomWrite = true;
        t.Create ();
        outputImage.texture = t;

        int k = shader.FindKernel ("CSMain");
        shader.SetTexture (k, "inputTexture", inputTexture);
        shader.SetTexture (k, "outputTexture", t);
        shader.Dispatch (k, inputTexture.width, inputTexture.height, 1);
    }
}

Compute Shader :

#pragma kernel CSMain

// ( CPU -> GPU )
Texture2D inputTexture;

// ( GPU -> CPU )
RWTexture2D <float4> outputTexture;

[numthreads(1, 1, 1)]
void CSMain (uint3 id : SV_DispatchThreadID)
{
    float R = inputTexture[id.xy].r;
    float G = inputTexture[id.xy].g;
    float B = inputTexture[id.xy].b;
    float A = 1;

    float Y = R * 0.299 + G * 0.587 + B * 0.114; // RGB 轉 灰階

    outputTexture[id.xy] = float4(Y, Y, Y, A); // 丟回 CPU
}

結果:

这里写图片描述

  • 4
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 11
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值