写在Shader前,Unity数字图像处理(下)
发表于2017-10-11
写在Shader前, 接Unity数字图像处理(上),下面开始介绍下半部分的内容。
4、模糊
using UnityEngine; using System.Collections; public class Test : MonoBehaviour { public Texture2D t; [Range(0, 15)] public int intensity = 2; Texture2D tt; void Start() { transform.localScale = new Vector3((float)t.width / (float)t.height, 1); //InvokeRepeating("MyUpdate", 0, 3); MyUpdate(); } void MyUpdate() { if (tt != null) { Destroy(tt); } tt = new Texture2D(t.width, t.height); for (int y = 1; y < t.height - 1; y ) { for (int x = 1; x < t.width - 1; x ) { Color c = t.GetPixel(x, y); if (intensity > 0) { for (int i = 0; i < intensity - 1; i ) // 这个循环太大会卡住! { for (int k = 0; k < intensity - 1; k ) { c = t.GetPixel(x i, y k); } } c = c / Mathf.Pow(intensity, 2) * 1.2f; } tt.SetPixel(x, y, c); } } tt.Apply(); GetComponent<Renderer>().material.mainTexture = tt; } }
5、 二值化 另一种实现方式
就是讲图片变成自己想要的两种颜色( 自己查看和 第二个Demo的区别 )比之前的好太多了!
脚本设置 (0和 1之间的值)
using UnityEngine; using System.Collections; public class Test : MonoBehaviour { public Texture2D t; [Range(0, 1)] public float intensity = 0.8f; // 这个代表 灰度值的 分割线 public Color drawColor = new Color32(240, 190, 170, 255); public Color defaultColor = new Color32(0, 0, 0, 0); Texture2D tt; void Start() { transform.localScale = new Vector3((float)t.width / (float)t.height, 1); InvokeRepeating("MyUpdate", 0, 1); } void MyUpdate() { if (tt != null) { Destroy(tt); } tt = new Texture2D(t.width, t.height); for (int y = 1; y < t.height - 1; y ) { for (int x = 1; x < t.width - 1; x ) { // 这个语句将图片变成两种颜色 tt.SetPixel(x, y, t.GetPixel(x, y).grayscale < intensity ? defaultColor : drawColor); } } tt.Apply(); GetComponent<Renderer>().material.mainTexture = tt; } }
6、边缘检测
脚本的设置 :
using UnityEngine; using System.Collections; public class Test : MonoBehaviour { public Texture2D t; [Range(0, 0.5f)] public float intensity = 0.15f; public Color drawColor = new Color32(124, 89, 54, 255); public Color defaultColor = new Color32(0, 0, 0, 0); Texture2D tt; void Start() { transform.localScale = new Vector3((float)t.width / (float)t.height, 1); InvokeRepeating("MyUpdate", 0, 5); } void MyUpdate() { if (tt != null) { Destroy(tt); } tt = new Texture2D(t.width, t.height); for (int y = 1; y < t.height - 1; y ) { for (int x = 1; x < t.width - 1; x ) { // 5个位置的灰度值 float g = t.GetPixel(x, y).grayscale; float gL = t.GetPixel(x - 1, y).grayscale; float gR = t.GetPixel(x 1, y).grayscale; float gT = t.GetPixel(x, y - 1).grayscale; float gB = t.GetPixel(x, y 1).grayscale; // 如果和上下左右 的弧度差值大于一个指定的值, 就认为这个是边缘! if (Mathf.Abs(g - gL) > intensity) { tt.SetPixel(x, y, drawColor); } else if (Mathf.Abs(g - gR) > intensity) { tt.SetPixel(x, y, drawColor); } else if (Mathf.Abs(g - gT) > intensity) { tt.SetPixel(x, y, drawColor); } else if (Mathf.Abs(g - gB) > intensity) { tt.SetPixel(x, y, drawColor); } else { tt.SetPixel(x, y, defaultColor); } } } tt.Apply(); GetComponent<Renderer>().material.mainTexture = tt; } }