123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446 |
- using System;
- using System.Collections.Generic;
- using System.Runtime.InteropServices;
- using UnityEngine;
- using OpenCVForUnity;
- using OpenCVForUnity.CoreModule;
- using OpenCVForUnity.ImgcodecsModule;
- using OpenCVForUnity.ImgprocModule;
- using OpenCVForUnity.UnityUtils;
- using OpenCVForUnity.Calib3dModule;
- using System.Text;
- using System.IO;
- using System.Net;
- namespace Seengene.XDKUnityPluginCloud {
- public class XDKTools {
- #region File tools
- /// <summary>
- /// 格式化路径成Asset的标准格式
- /// </summary>
- /// <param name="filePath"></param>
- /// <returns></returns>
- public static string FormatAssetPath(string filePath) {
- var newFilePath1 = filePath.Replace("\\", "/");
- var newFilePath2 = newFilePath1.Replace("//", "/").Trim();
- newFilePath2 = newFilePath2.Replace("///", "/").Trim();
- newFilePath2 = newFilePath2.Replace("\\\\", "/").Trim();
- return newFilePath2;
- }
- public static string GetRelativePathFromFullPath(string fullPath) {
- string mp = fullPath;
- mp = mp.Substring(mp.IndexOf("Assets"));
- mp = mp.Replace('\\', '/');
- return mp;
- }
- /// <summary>
- /// 获取下载文件的大小
- /// </summary>
- /// <returns>The length.</returns>
- /// <param name="url">URL.</param>
- public static long GetFileLengthByUrl(string url) {
- HttpWebRequest requet = HttpWebRequest.Create(url) as HttpWebRequest;
- requet.Method = "HEAD";
- HttpWebResponse response = requet.GetResponse() as HttpWebResponse;
- return response.ContentLength;
- }
- /// <summary>
- /// 计算文件大小函数(保留两位小数),Size为字节大小
- /// </summary>
- /// <param name="size">初始文件大小</param>
- /// <returns></returns>
- public static string GetFormatFileSize(long size) {
- var num = 1024.00; //byte
- if (size < num)
- return size + "B";
- if (size < Math.Pow(num, 2))
- return (size / num).ToString("f2") + "K"; //kb
- if (size < Math.Pow(num, 3))
- return (size / Math.Pow(num, 2)).ToString("f2") + "M"; //M
- if (size < Math.Pow(num, 4))
- return (size / Math.Pow(num, 3)).ToString("f2") + "G"; //G
- return (size / Math.Pow(num, 4)).ToString("f2") + "T"; //T
- }
- #endregion of File tools
- #region Texture Format Compress
- public static byte[] GetGrayTextureBytes(byte[] imageBuffer, TextureFormat textureFormat, int imageHeight, int imageWidth) {
- if (textureFormat == TextureFormat.R8) {
- Mat grayMat = new Mat(imageHeight, imageWidth, CvType.CV_8UC1);
- grayMat.put(0, 0, imageBuffer);
- try {
- MatOfInt compressionParams = new MatOfInt(Imgcodecs.IMWRITE_JPEG_QUALITY, 100);
- MatOfByte jpgMat = new MatOfByte();
- if (Imgcodecs.imencode(".jpeg", grayMat, jpgMat, compressionParams)) {
- return jpgMat.toArray();
- } else {
- return null;
- }
- } catch (Exception e) {
- Debug.LogErrorFormat("图片转灰度图、压缩JPG格式失败: ", e.Message);
- return null;
- }
- } else if (textureFormat == TextureFormat.RGB24) {
- Mat imgMat = new Mat(imageHeight, imageWidth, CvType.CV_8UC3);
- imgMat.put(0, 0, imageBuffer);
- Mat grayMat = new Mat(imageHeight, imageWidth, CvType.CV_8UC1);
- Imgproc.cvtColor(imgMat, grayMat, Imgproc.COLOR_RGBA2GRAY);
- MatOfInt compressionParams = new MatOfInt(Imgcodecs.IMWRITE_JPEG_QUALITY, 90);
- MatOfByte jpgMat = new MatOfByte();
- if (Imgcodecs.imencode(".jpeg", grayMat, jpgMat, compressionParams)) {
- return jpgMat.toArray();
- } else {
- return null;
- }
- } else if (textureFormat == TextureFormat.ARGB32) {
- Mat imgMat = new Mat(imageHeight, imageWidth, CvType.CV_8UC4);
- imgMat.put(0, 0, imageBuffer);
- Mat grayMat = new Mat(imageHeight, imageWidth, CvType.CV_8UC1);
- Imgproc.cvtColor(imgMat, grayMat, Imgproc.COLOR_RGBA2GRAY);
- MatOfInt compressionParams = new MatOfInt(Imgcodecs.IMWRITE_JPEG_QUALITY, 90);
- MatOfByte jpgMat = new MatOfByte();
- if (Imgcodecs.imencode(".jpeg", grayMat, jpgMat, compressionParams)) {
- return jpgMat.toArray();
- } else {
- return null;
- }
- } else {
- Debug.LogErrorFormat("XDKTools.GetGrayTextureBytesAndroid,图片压缩失败,不支持的图片格式:{0}", textureFormat);
- return null;
- }
- }
- public static byte[] GetGrayUndistortTextureBytes(byte[] imageBuffer, TextureFormat textureFormat, int imageHeight, int imageWidth, float[] cameraIntrinsic, float[] disCoeffsArray) {
- if (textureFormat == TextureFormat.R8) {
- Mat grayMat = new Mat(imageHeight, imageWidth, CvType.CV_8UC1);
- grayMat.put(0, 0, imageBuffer);
- try {
- Mat undistortMat = Mat.zeros(imageHeight, imageWidth, CvType.CV_8UC1);
- Mat cameraMatrix = new Mat(3, 3, CvType.CV_32FC1);
- cameraMatrix.put(0, 0, cameraIntrinsic);
- //Debug.LogFormat("cameraMatrix: {0}", cameraMatrix.dump());
- Mat discoeffs = new Mat(1, 8, CvType.CV_32FC1);
- discoeffs.put(0, 0, disCoeffsArray);
- //Debug.LogFormat("discoeffs: {0}", discoeffs.dump());
- Calib3d.undistort(grayMat, undistortMat, cameraMatrix, discoeffs);
- MatOfInt compressionParams = new MatOfInt(Imgcodecs.IMWRITE_JPEG_QUALITY, 100);
- MatOfByte jpgMat = new MatOfByte();
- if (Imgcodecs.imencode(".jpeg", undistortMat, jpgMat, compressionParams)) {
- return jpgMat.toArray();
- } else {
- return null;
- }
- } catch (Exception e) {
- Debug.LogErrorFormat("图片转灰度图、去畸变、压缩JPG格式失败: ", e.Message);
- return null;
- }
- } else if (textureFormat == TextureFormat.RGB24) {
- Mat imgMat = new Mat(imageHeight, imageWidth, CvType.CV_8UC3);
- imgMat.put(0, 0, imageBuffer);
- Mat grayMat = new Mat(imageHeight, imageWidth, CvType.CV_8UC1);
- Imgproc.cvtColor(imgMat, grayMat, Imgproc.COLOR_RGBA2GRAY);
- MatOfInt compressionParams = new MatOfInt(Imgcodecs.IMWRITE_JPEG_QUALITY, 90);
- MatOfByte jpgMat = new MatOfByte();
- if (Imgcodecs.imencode(".jpeg", grayMat, jpgMat, compressionParams)) {
- return jpgMat.toArray();
- } else {
- return null;
- }
- } else if (textureFormat == TextureFormat.ARGB32) {
- Mat imgMat = new Mat(imageHeight, imageWidth, CvType.CV_8UC4);
- imgMat.put(0, 0, imageBuffer);
- Mat grayMat = new Mat(imageHeight, imageWidth, CvType.CV_8UC1);
- Imgproc.cvtColor(imgMat, grayMat, Imgproc.COLOR_RGBA2GRAY);
- MatOfInt compressionParams = new MatOfInt(Imgcodecs.IMWRITE_JPEG_QUALITY, 90);
- MatOfByte jpgMat = new MatOfByte();
- if (Imgcodecs.imencode(".jpeg", grayMat, jpgMat, compressionParams)) {
- return jpgMat.toArray();
- } else {
- return null;
- }
- } else {
- Debug.LogErrorFormat("XDKTools.GetGrayTextureBytesAndroid,图片压缩失败,不支持的图片格式:{0}", textureFormat);
- return null;
- }
- }
- public static byte[] GetGrayUndistortTextureBytes(byte[] imageBuffer, TextureFormat textureFormat, int imageHeight, int imageWidth, CameraCalibration cameraCalibration) {
- if (textureFormat == TextureFormat.R8) {
- Mat grayMat = new Mat(imageHeight, imageWidth, CvType.CV_8UC1);
- grayMat.put(0, 0, imageBuffer);
- try {
- Mat undistortMat = Mat.zeros(imageHeight, imageWidth, CvType.CV_8UC1);
- Mat cameraMatrix = new Mat(3, 3, CvType.CV_32FC1);
- // 计算相机内参
- float intrinsics_00 = cameraCalibration.focal_length.x;
- float intrinsics_01 = 0;
- float intrinsics_02 = cameraCalibration.principal_point.x;
- float intrinsics_10 = 0;
- float intrinsics_11 = cameraCalibration.focal_length.y;
- float intrinsics_12 = cameraCalibration.principal_point.y;
- float intrinsics_20 = 0;
- float intrinsics_21 = 0;
- float intrinsics_22 = 1;
- float[] cameraIntrinsicData = new float[9] { intrinsics_00, intrinsics_01, intrinsics_02 ,
- intrinsics_10, intrinsics_11, intrinsics_12 ,
- intrinsics_20, intrinsics_21, intrinsics_22 };
- cameraMatrix.put(0, 0, cameraIntrinsicData);
- Debug.LogFormat("cameraMatrix: {0}", cameraMatrix.dump());
- // 畸变参数
- Mat discoeffs = new Mat(1, 8, CvType.CV_32FC1);
- float discoeffs_0 = cameraCalibration.radial_distortion_8[0];
- float discoeffs_1 = cameraCalibration.radial_distortion_8[1];
- float discoeffs_2 = cameraCalibration.radial_distortion_8[2];
- float discoeffs_3 = cameraCalibration.radial_distortion_8[3];
- float discoeffs_4 = cameraCalibration.radial_distortion_8[4];
- float discoeffs_5 = cameraCalibration.radial_distortion_8[5];
- float discoeffs_6 = cameraCalibration.radial_distortion_8[6];
- float discoeffs_7 = cameraCalibration.radial_distortion_8[7];
- float[] disCoeffsData = new float[8] { discoeffs_0, discoeffs_1, discoeffs_2, discoeffs_3, discoeffs_4, discoeffs_5, discoeffs_6, discoeffs_7 };
- discoeffs.put(0, 0, disCoeffsData);
- Debug.LogFormat("discoeffs: {0}", discoeffs.dump());
- if (cameraCalibration.fish_eye == false) {
- Calib3d.undistort(grayMat, undistortMat, cameraMatrix, discoeffs);
- } else {
- Calib3d.fisheye_undistortImage(grayMat, undistortMat, cameraMatrix, discoeffs);
- }
- MatOfInt compressionParams = new MatOfInt(Imgcodecs.IMWRITE_JPEG_QUALITY, 100);
- MatOfByte jpgMat = new MatOfByte();
- if (Imgcodecs.imencode(".jpeg", undistortMat, jpgMat, compressionParams)) {
- return jpgMat.toArray();
- } else {
- return null;
- }
- } catch (Exception e) {
- Debug.LogErrorFormat("图片转灰度图、去畸变、压缩JPG格式失败: ", e.Message);
- return null;
- }
- } else if (textureFormat == TextureFormat.RGB24) {
- Mat imgMat = new Mat(imageHeight, imageWidth, CvType.CV_8UC3);
- imgMat.put(0, 0, imageBuffer);
- Mat grayMat = new Mat(imageHeight, imageWidth, CvType.CV_8UC1);
- Imgproc.cvtColor(imgMat, grayMat, Imgproc.COLOR_RGBA2GRAY);
- MatOfInt compressionParams = new MatOfInt(Imgcodecs.IMWRITE_JPEG_QUALITY, 90);
- MatOfByte jpgMat = new MatOfByte();
- if (Imgcodecs.imencode(".jpeg", grayMat, jpgMat, compressionParams)) {
- return jpgMat.toArray();
- } else {
- return null;
- }
- } else if (textureFormat == TextureFormat.ARGB32) {
- Mat imgMat = new Mat(imageHeight, imageWidth, CvType.CV_8UC4);
- imgMat.put(0, 0, imageBuffer);
- Mat grayMat = new Mat(imageHeight, imageWidth, CvType.CV_8UC1);
- Imgproc.cvtColor(imgMat, grayMat, Imgproc.COLOR_RGBA2GRAY);
- MatOfInt compressionParams = new MatOfInt(Imgcodecs.IMWRITE_JPEG_QUALITY, 90);
- MatOfByte jpgMat = new MatOfByte();
- if (Imgcodecs.imencode(".jpeg", grayMat, jpgMat, compressionParams)) {
- return jpgMat.toArray();
- } else {
- return null;
- }
- } else {
- Debug.LogErrorFormat("XDKTools.GetGrayTextureBytesAndroid,图片压缩失败,不支持的图片格式:{0}", textureFormat);
- return null;
- }
- }
- public static MatOfByte GetGrayTextureMat(Texture2D texture2D) {
- Mat imgMat = new Mat(texture2D.height, texture2D.width, CvType.CV_8UC4);
- Utils.texture2DToMat(texture2D, imgMat);
- Mat grayMat = new Mat(texture2D.height, texture2D.width, CvType.CV_8UC1);
- Imgproc.cvtColor(imgMat, grayMat, Imgproc.COLOR_RGBA2GRAY);
- MatOfByte grayMatOfByte = new MatOfByte(grayMat);
- return grayMatOfByte;
- }
- public static Texture2D VerticalFlipTexture(Texture2D texture) {
- //得到图片的宽高
- int width = texture.width;
- int height = texture.height;
- Texture2D flipTexture = new Texture2D(width, height);
- for (int i = 0; i < height; i++) {
- flipTexture.SetPixels(0, i, width, 1, texture.GetPixels(0, height - i - 1, width, 1));
- }
- flipTexture.Apply();
- return flipTexture;
- }
- //byte[]转换为Intptr
- public static IntPtr BytesToIntptr(byte[] bytes) {
- return System.Runtime.InteropServices.Marshal.UnsafeAddrOfPinnedArrayElement(bytes, 0);
- }
- public static IntPtr ArrayToIntptr(Array array) {
- return System.Runtime.InteropServices.Marshal.UnsafeAddrOfPinnedArrayElement(array, 0);
- }
- public static byte[] IntPtrToBytes(IntPtr imagePtr, int imageSize) {
- byte[] imageBytes = new byte[imageSize];
- Marshal.Copy(imagePtr, imageBytes, 0, imageSize);
- return imageBytes;
- }
- public static IntPtr FloatArrayToIntPtr(float[] floatArray) {
- int size = sizeof(float) * floatArray.Length;
- IntPtr ptr = Marshal.AllocHGlobal(size);
- Marshal.Copy(floatArray, 0, ptr, floatArray.Length);
- return ptr;
- }
- public static float[] IntPtrToFloatArray(IntPtr ptr, int count) {
- float[] image2DPoints = new float[count];
- Marshal.Copy(ptr, image2DPoints, 0, count);
- return image2DPoints;
- }
- public static Texture2D LoadLocalImage(string path) {
- FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
- fileStream.Seek(0, SeekOrigin.Begin);
- byte[] imgBytes = new byte[fileStream.Length];
- fileStream.Read(imgBytes, 0, (int)fileStream.Length);
- fileStream.Close();
- fileStream.Dispose();
- fileStream = null;
- Texture2D texture = new Texture2D(1280, 720);
- texture.LoadImage(imgBytes);
- return texture;
- }
- public static byte[] GetFileStream(string path) {
- FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
- fileStream.Seek(0, SeekOrigin.Begin);
- byte[] imgBytes = new byte[fileStream.Length];
- fileStream.Read(imgBytes, 0, (int)fileStream.Length);
- fileStream.Close();
- fileStream.Dispose();
- fileStream = null;
- return imgBytes;
- }
- #endregion of Texture Format Compress
- #region Debug String Format
- public static string ListVectro2ToString(List<Vector2> listV2, string format = "f2") {
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < listV2.Count; i++) {
- sb.Append(listV2[i].ToString(format));
- sb.Append(",");
- }
- return sb.ToString();
- }
- public static string ListVector3ToString(List<Vector3> listV3, string format = "f2") {
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < listV3.Count; i++) {
- sb.Append(listV3[i].ToString(format));
- sb.Append(",");
- }
- return sb.ToString();
- }
- public static string ListDoubleToString(List<double> listDouble, string format = "f2") {
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < listDouble.Count; i++) {
- sb.Append(listDouble[i].ToString(format));
- sb.Append(",");
- }
- return sb.ToString();
- }
- public static string ListFloatToString(List<float> listFloat, string format = "f2") {
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < listFloat.Count; i++) {
- sb.Append(listFloat[i].ToString(format));
- sb.Append(",");
- }
- return sb.ToString();
- }
- /// <summary>
- /// Float数组 格式化输出
- /// </summary>
- /// <param name="arrayFloat"></param>
- /// <param name="format">格式化,小数点保留几位</param>
- /// <returns></returns>
- public static string ArrayFloatToString(float[] arrayFloat, string format = "f2") {
- if (arrayFloat == null) return null;
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < arrayFloat.Length; i++) {
- sb.Append(arrayFloat[i].ToString(format));
- sb.Append(",");
- }
- return sb.ToString();
- }
- public static string OneDimensionArrayToString(string[] arr) {
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < arr.Length - 1; i++) {
- sb.Append(arr[i]);
- sb.Append(",");
- }
- sb.Append(arr[arr.Length - 1]);
- return sb.ToString();
- }
- public static string TwoDimensionArrayToString(float[,] arr) {
- StringBuilder sb = new StringBuilder();
- int coutRow = arr.GetLength(0);
- int countColumn = arr.GetLength(1);
- for (int i = 0; i < coutRow; i++) {
- for (int j = 0; j < countColumn; j++) {
- sb.Append(arr[i, j]);
- sb.Append(",");
- }
- }
- return sb.ToString();
- }
- //自定义输出字符数组方法
- public static string GetBytesString(byte[] bytes) {
- return GetBytesString(bytes, 0, bytes.Length, ",");
- }
- public static string GetBytesString(byte[] bytes, int index, int count, string sep) {
- if (count > bytes.Length) count = bytes.Length;
- var sb = new StringBuilder();
- for (int i = index; i < count - 1; i++) {
- sb.Append(bytes[i].ToString("X2") + sep);
- }
- sb.Append(bytes[index + count - 1].ToString("X2"));
- return sb.ToString();
- }
- }
- #endregion of Debug String Format
- }
|