using System.Collections; using UnityEngine; using UnityEngine.Serialization; using OpenCVForUnity.CoreModule; using OpenCVForUnity.ImgprocModule; namespace OpenCVForUnity.UnityUtils.Helper { /// /// Image optimization helper. /// v 1.1.0 /// public class ImageOptimizationHelper : MonoBehaviour { /// /// The downscale ratio. /// [SerializeField, FormerlySerializedAs ("downscaleRatio"), TooltipAttribute ("Set the ratio of down scaling.")] protected float _downscaleRatio = 2f; public float downscaleRatio { get { return _downscaleRatio; } set { _downscaleRatio = Mathf.Clamp (value, 1f, float.MaxValue); } } /// /// The frame skipping ratio. /// [SerializeField, FormerlySerializedAs ("frameSkippingRatio"), TooltipAttribute ("Set the ratio of frame skipping.")] protected int _frameSkippingRatio = 2; public int frameSkippingRatio { get { return _frameSkippingRatio; } set { _frameSkippingRatio = (int)Mathf.Clamp (value, 1f, float.MaxValue); } } /// /// The frame count. /// protected int frameCount = 0; /// /// The downscale frame mat. /// protected Mat downScaleFrameMat; protected void OnValidate () { _downscaleRatio = Mathf.Clamp (_downscaleRatio, 1f, float.MaxValue); _frameSkippingRatio = (int)Mathf.Clamp (_frameSkippingRatio, 1f, float.MaxValue); } /// /// Indicates whether the current frame is skipped. /// /// true, if the current frame is skipped, false otherwise. public virtual bool IsCurrentFrameSkipped () { frameCount++; if (frameCount % frameSkippingRatio == 0) { return false; } return true; } /// /// Gets the mat that downscaled the original mat. /// if downscaleRatio == 1 , return originalMat. /// /// The downscale mat. /// Original mat. public virtual Mat GetDownScaleMat (Mat originalMat) { if (Mathf.Approximately (_downscaleRatio, 1f)) return originalMat; if (downScaleFrameMat == null) { downScaleFrameMat = new Mat (); } Imgproc.resize (originalMat, downScaleFrameMat, new Size (), 1.0 / _downscaleRatio, 1.0 / _downscaleRatio, Imgproc.INTER_LINEAR); return downScaleFrameMat; } /// /// To release the resources for the initialized method. /// public virtual void Dispose () { frameCount = 0; if (downScaleFrameMat != null) { downScaleFrameMat.Dispose (); downScaleFrameMat = null; } } } }