OpenCV是一个基于BSD许可(开源)发行的跨平台计算机视觉库,可以运行在Linux、Windows、Android和Mac OS操作系统上。它轻量级而且高效——由一系列 C 函数和少量 C++ 类构成,同时提供了Python、Ruby、MATLAB等语言的接口,实现了图像处理和计算机视觉方面的很多通用算法。
导入资源包后新建Image,随便插入一张图片,同时建立一个2DGameObject,锚点设置为左下角,并随意放置在图片上任意一像素点上,该点用于确定像素点位置
新建一个测试脚本,用于使用OpenCv检测颜色
(1)首先先截屏,因为当前是在编辑器模式下,所以使用Application.dataPath路径,该路径直接指向项目路径,打包时需要更换成Application.persistentDataPath路径下
///
/// 截屏
///
///
IEnumerator ScreenShot()
{
yield return new WaitForEndOfFrame();
ScreenCapture.CaptureScreenshot(Application.dataPath + "/ScreenShot/1.png");
}
(2)获取当前像素点位置,需要注意的一点是OpenCV像素点的计算方式是从左上角开始计算
void Start ()
{
Position = GetComponent().anchoredPosition3D;
Point = Vector3Topoint(new Vector3(Position.x, Camera.main.pixelHeight - Position.y, 0));
StartCoroutine(ScreenShot());
}
///
/// 转换位置类型
///
///
///
public static Point Vector3Topoint(Vector3 vector)
{
return new Point(vector.x, vector.y);
}
(3)随后使用OpenCv读取图片,并且进行获取像素点颜色操作,需要说明的一点是OpenCV使用的BGR的颜色通道,在获取颜色时需要额外注意,同时OpenCV获取像素点是以高*宽的顺序进行获取
///
/// 通过OpenCV获取像素点颜色
///
void CheckColorForOpencv()
{
var src = Imgcodecs.imread(Application.dataPath + "/ScreenShot/1.png");
var dst = new Mat(src.cols(), src.rows(), CvType.CV_8UC4);
Imgproc.cvtColor(src,dst,Imgproc.COLOR_BGR2BGRA);
double b = dst.get((int) Point.y, (int) Point.x)[0];
double g = dst.get((int) Point.y, (int) Point.x)[1];
double r = dst.get((int) Point.y, (int) Point.x)[2];
double a = dst.get((int) Point.y, (int) Point.x)[3];
Color = new Color((float) r / 255, (float) g / 255, (float) b / 255, (float) a / 255);
}
(4)然后将脚本挂载在2DGameObject上,并运行测试,在面板中可以看到获取到的像素点颜色
//获取颜色
public Color32 Color;
//检测时间间隔
private float CheckTIme;
private float MaxCheckTime;
//像素位置点
public Point Point;
private Vector3 Position;
// Use this for initialization
void Start ()
{
MaxCheckTime = 3.0f;
// Point = Camera.main.WorldToScreenPoint(transform.position);
Position = GetComponent().anchoredPosition3D;
Point = Vector3Topoint(new Vector3(Position.x, Camera.main.pixelHeight - Position.y, 0));
StartCoroutine(ScreenShot());
}
// Update is called once per frame
void Update ()
{
CheckTIme += Time.deltaTime;
if (CheckTIme >= MaxCheckTime)
{
CheckColorForOpencv();
CheckTIme = 0;
}
}
///
/// 转换位置类型
///
///
///
public static Point Vector3Topoint(Vector3 vector)
{
return new Point(vector.x, vector.y);
}
///
/// 截屏
///
///
IEnumerator ScreenShot()
{
yield return new WaitForEndOfFrame();
ScreenCapture.CaptureScreenshot(Application.dataPath + "/ScreenShot/1.png");
}
///
/// 通过OpenCV获取像素点颜色
///
void CheckColorForOpencv()
{
var src = Imgcodecs.imread(Application.dataPath + "/ScreenShot/1.png");
var dst = new Mat(src.cols(), src.rows(), CvType.CV_8UC4);
Imgproc.cvtColor(src,dst,Imgproc.COLOR_BGR2BGRA);
double b = dst.get((int) Point.y, (int) Point.x)[0];
double g = dst.get((int) Point.y, (int) Point.x)[1];
double r = dst.get((int) Point.y, (int) Point.x)[2];
double a = dst.get((int) Point.y, (int) Point.x)[3];
Color = new Color((float) r / 255, (float) g / 255, (float) b / 255, (float) a / 255);
}