Esempio n. 1
0
        /// <summary>
        /// Detect keypoints in an image.
        /// </summary>
        /// <param name="image">The image.</param>
        /// <param name="mask">Mask specifying where to look for keypoints (optional).
        /// Must be a char matrix with non-zero values in the region of interest.</param>
        /// <returns>The detected keypoints.</returns>
        public KeyPoint[] Detect(InputArray image, Mat?mask = null)
        {
            if (image == null)
            {
                throw new ArgumentNullException(nameof(image));
            }
            ThrowIfDisposed();

            image.ThrowIfDisposed();
            try
            {
                using (var keypoints = new VectorOfKeyPoint())
                {
                    NativeMethods.features2d_Feature2D_detect_InputArray(ptr, image.CvPtr, keypoints.CvPtr,
                                                                         Cv2.ToPtr(mask));
                    return(keypoints.ToArray());
                }
            }
            finally
            {
                GC.KeepAlive(this);
                GC.KeepAlive(image);
                GC.KeepAlive(mask);
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Creates a window
        /// </summary>
        /// <param name="name">Name of the window which is used as window identifier and appears in the window caption. </param>
        /// <param name="image">Image to be shown.</param>
        /// <param name="flags">Flags of the window. Currently the only supported flag is WindowMode.AutoSize.
        /// If it is set, window size is automatically adjusted to fit the displayed image (see cvShowImage), while user can not change the window size manually. </param>
        public Window(string name, Mat?image = null, WindowFlags flags = WindowFlags.AutoSize)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException("Null or empty window name.", nameof(name));
            }

            this.name = name;
            NativeMethods.HandleException(
                NativeMethods.highgui_namedWindow(name, (int)flags));

            if (image != null)
            {
                ShowImage(image);
            }

            trackbars = new Dictionary <string, CvTrackbar>();

            if (!Windows.ContainsKey(name))
            {
                Windows.Add(name, this);
            }

            callbackHandle = null;
        }
Esempio n. 3
0
        public async Task DrawMatAsync(Mat mat)
        {
            Mat?rgba = null;

            try
            {
                var type = mat.Type();
                if (type == MatType.CV_8UC1)
                {
                    rgba = mat.CvtColor(ColorConversionCodes.GRAY2RGBA);
                }
                else if (type == MatType.CV_8UC3)
                {
                    rgba = mat.CvtColor(ColorConversionCodes.BGR2RGBA);
                }
                else
                {
                    throw new ArgumentException($"Invalid mat type ({mat.Type()})");
                }

                if (!rgba.IsContinuous())
                {
                    throw new InvalidOperationException("RGBA Mat should be continuous.");
                }
                var length     = (int)(rgba.DataEnd.ToInt64() - rgba.DataStart.ToInt64());
                var pixelBytes = new byte[length];
                Marshal.Copy(rgba.DataStart, pixelBytes, 0, length);

                await DrawPixelsAsync(pixelBytes);
            }
            finally
            {
                rgba?.Dispose();
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Computes an image descriptor using the set visual vocabulary.
        /// </summary>
        /// <param name="image">Image, for which the descriptor is computed.</param>
        /// <param name="keypoints">Keypoints detected in the input image.</param>
        /// <param name="imgDescriptor">Computed output image descriptor.</param>
        /// <param name="pointIdxsOfClusters">pointIdxsOfClusters Indices of keypoints that belong to the cluster.
        /// This means that pointIdxsOfClusters[i] are keypoint indices that belong to the i -th cluster(word of vocabulary) returned if it is non-zero.</param>
        /// <param name="descriptors">Descriptors of the image keypoints that are returned if they are non-zero.</param>
        public void Compute(InputArray image, ref KeyPoint[] keypoints, OutputArray imgDescriptor,
                            out int[][] pointIdxsOfClusters, Mat?descriptors = null)
        {
            ThrowIfDisposed();
            if (image == null)
            {
                throw new ArgumentNullException(nameof(image));
            }
            if (imgDescriptor == null)
            {
                throw new ArgumentNullException(nameof(imgDescriptor));
            }

            using (var keypointsVec = new VectorOfKeyPoint(keypoints))
                using (var pointIdxsOfClustersVec = new VectorOfVectorInt32())
                {
                    NativeMethods.HandleException(
                        NativeMethods.features2d_BOWImgDescriptorExtractor_compute11(ptr, image.CvPtr, keypointsVec.CvPtr,
                                                                                     imgDescriptor.CvPtr, pointIdxsOfClustersVec.CvPtr, Cv2.ToPtr(descriptors)));
                    keypoints           = keypointsVec.ToArray();
                    pointIdxsOfClusters = pointIdxsOfClustersVec.ToArray();
                }
            GC.KeepAlive(this);
            GC.KeepAlive(image);
            GC.KeepAlive(imgDescriptor);
            GC.KeepAlive(descriptors);
        }
Esempio n. 5
0
        /// <summary>
        /// Applies weighted median filter to an image.
        /// </summary>
        /// <remarks>
        /// For more details about this implementation, please see @cite zhang2014100+
        /// </remarks>
        /// <param name="joint">Joint 8-bit, 1-channel or 3-channel image.</param>
        /// <param name="src">Source 8-bit or floating-point, 1-channel or 3-channel image.</param>
        /// <param name="dst">Destination image.</param>
        /// <param name="r">Radius of filtering kernel, should be a positive integer.</param>
        /// <param name="sigma">Filter range standard deviation for the joint image.</param>
        /// <param name="weightType">The type of weight definition, see WMFWeightType</param>
        /// <param name="mask">A 0-1 mask that has the same size with I. This mask is used to ignore the effect of some pixels. If the pixel value on mask is 0,
        /// the pixel will be ignored when maintaining the joint-histogram.This is useful for applications like optical flow occlusion handling.</param>
        public static void WeightedMedianFilter(
            InputArray joint, InputArray src, OutputArray dst, int r,
            double sigma = 25.5, WMFWeightType weightType = WMFWeightType.EXP, Mat?mask = null)
        {
            if (joint == null)
            {
                throw new ArgumentNullException(nameof(joint));
            }
            if (src == null)
            {
                throw new ArgumentNullException(nameof(src));
            }
            if (dst == null)
            {
                throw new ArgumentNullException(nameof(dst));
            }
            joint.ThrowIfDisposed();
            src.ThrowIfDisposed();
            dst.ThrowIfNotReady();

            NativeMethods.ximgproc_weightedMedianFilter(
                joint.CvPtr, src.CvPtr, dst.CvPtr, r, sigma, (int)weightType, mask?.CvPtr ?? IntPtr.Zero);

            GC.KeepAlive(joint);
            GC.KeepAlive(src);
            GC.KeepAlive(dst);
            dst.Fix();
            GC.KeepAlive(mask);
        }
Esempio n. 6
0
        /// <summary>
        /// 指定したウィンドウ内に画像を表示する(cvShowImage相当).
        /// このウィンドウのフラグに AutoSize が指定されていた場合は,画像はオリジナルサイズで表示される.
        /// それ以外の場合,ウィンドウサイズに合わせて 表示画像サイズが変更される.
        /// </summary>
        /// <param name="img">画像ヘッダ</param>
#else
        /// <summary>
        /// Shows the image in this window
        /// </summary>
        /// <param name="img">Image to be shown. </param>
#endif
        public void ShowImage(Mat?img)
        {
            if (img != null)
            {
                this.image = img;
                NativeMethods.highgui_imshow(name, img.CvPtr);
                GC.KeepAlive(img);
            }
        }
Esempio n. 7
0
 public static void SafeDispose(this Mat?itemToDispose)
 {
     if (itemToDispose != null &&
         itemToDispose.IsEnabledDispose &&
         !itemToDispose.IsDisposed)
     {
         itemToDispose.Dispose();
     }
 }
Esempio n. 8
0
        /// <summary>
        /// computes predicted state
        /// </summary>
        /// <param name="control"></param>
        /// <returns></returns>
        public Mat Predict(Mat?control = null)
        {
            ThrowIfDisposed();

            var ret = NativeMethods.video_KalmanFilter_predict(ptr, Cv2.ToPtr(control));

            GC.KeepAlive(this);
            GC.KeepAlive(control);
            return(new Mat(ret));
        }
 private void ReportInitFaceProgress(Mat?img, Rect?face        = null,
                                     ProfileInitProgress state = Services.ProfileInitProgress.Progress,
                                     bool stopped = false)
 {
     InitFaceProgress?.Report(new ProfileInitProgressArgs()
     {
         ProgressState      = state,
         FaceRect           = face,
         Frame              = img,
         ProgressPercentage = (int)_progress,
         Stoped             = stopped,
     });
 }
Esempio n. 10
0
        private static string GetCacheKey(
            GeographicLevel geographicLevel,
            Country country,
            EnglishDevolvedArea?englishDevolvedArea,
            Institution?institution,
            LocalAuthority?localAuthority,
            LocalAuthorityDistrict?localAuthorityDistrict,
            LocalEnterprisePartnership?localEnterprisePartnership,
            MayoralCombinedAuthority?mayoralCombinedAuthority,
            Mat?multiAcademyTrust,
            OpportunityArea?opportunityArea,
            ParliamentaryConstituency?parliamentaryConstituency,
            PlanningArea?planningArea,
            Provider?provider,
            Region?region,
            RscRegion?rscRegion,
            School?school,
            Sponsor?sponsor,
            Ward?ward)
        {
            var locationAttributes = new ILocationAttribute?[]
            {
                country,
                englishDevolvedArea,
                institution,
                localAuthority,
                localAuthorityDistrict,
                localEnterprisePartnership,
                mayoralCombinedAuthority,
                multiAcademyTrust,
                parliamentaryConstituency,
                planningArea,
                provider,
                opportunityArea,
                region,
                rscRegion,
                school,
                sponsor,
                ward
            };

            var tokens = locationAttributes
                         .WhereNotNull()
                         .Select(attribute => attribute.GetCacheKey())
                         .ToList();

            const char separator = '_';

            return($"{geographicLevel}{separator}{tokens.JoinToString(separator)}");
        }
Esempio n. 11
0
        /// <summary>
        /// ウィンドウ名と画像の表示モードと始めから表示しておく画像を指定して初期化
        /// </summary>
        /// <param name="name">ウィンドウの識別に用いられるウィンドウ名で,ウィンドウのタイトルバ ーに表示される.</param>
        /// <param name="flags">ウィンドウのフラグ</param>
        /// <param name="image">ウィンドウに表示する画像</param>
#else
        /// <summary>
        /// Creates a window
        /// </summary>
        /// <param name="name">Name of the window which is used as window identifier and appears in the window caption. </param>
        /// <param name="flags">Flags of the window. Currently the only supported flag is WindowMode.AutoSize.
        /// If it is set, window size is automatically adjusted to fit the displayed image (see cvShowImage), while user can not change the window size manually. </param>
        /// <param name="image">Image to be shown.</param>
#endif
        public Window(string name, WindowMode flags, Mat?image)
        {
            this.name = name ?? throw new ArgumentNullException(nameof(name));
            NativeMethods.highgui_namedWindow(name, (int)flags);

            this.image = image;
            ShowImage(image);
            trackbars = new Dictionary <string, CvTrackbar>();
            if (!Windows.ContainsKey(name))
            {
                Windows.Add(name, this);
            }
            this.callbackHandle = null;
        }
Esempio n. 12
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="mat"></param>
 // ReSharper disable once SuggestBaseTypeForParameter
 internal InputArray(Mat?mat)
 {
     // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression
     if (mat == null)
     {
         ptr = IntPtr.Zero;
     }
     else
     {
         NativeMethods.HandleException(
             NativeMethods.core_InputArray_new_byMat(mat.CvPtr, out ptr));
     }
     GC.KeepAlive(mat);
     obj        = mat;
     handleKind = HandleKind.Mat;
 }
Esempio n. 13
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="defaultMat"></param>
        /// <returns></returns>
        public Mat ReadMat(Mat?defaultMat = null)
        {
            var value = new Mat();

            try
            {
                NativeMethods.core_FileNode_read_Mat(ptr, value.CvPtr, Cv2.ToPtr(defaultMat));
                GC.KeepAlive(this);
                GC.KeepAlive(defaultMat);
            }
            catch
            {
                value.Dispose();
                throw;
            }
            return(value);
        }
Esempio n. 14
0
        /// <summary>
        /// Convert to cv::Mat
        /// </summary>
        /// <returns></returns>
        public Mat ToMat()
        {
            Mat?mat = null;

            try
            {
                mat = new Mat();
                NativeMethods.HandleException(
                    NativeMethods.core_MatExpr_toMat(ptr, mat.CvPtr));
                GC.KeepAlive(this);
                return(mat);
            }
            catch
            {
                mat?.Dispose();
                throw;
            }
        }
Esempio n. 15
0
        public static double GetDifference(Mat mat1, Mat mat2, Mat? mask = null)
        {
            if (mask != null && !mask.IsEmpty)
            {
                var mat1Masked = new Mat();
                mat1.CopyTo(mat1Masked, mask);
                mat1 = mat1Masked;

                var mat2Masked = new Mat();
                mat2.CopyTo(mat2Masked, mask);
                mat2 = mat2Masked;
            }

            var foreground = new Mat();
            CvInvoke.AbsDiff(mat1, mat2, foreground);

            return CvInvoke.Mean(foreground).V0;
        }
        private static unsafe void CopyFrame(Bitmap?src, Mat?dst)
        {
            if (src == null || dst == null)
            {
                return;
            }
            var bits = src.LockBits(new Rectangle(0, 0, src.Width, src.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

            try
            {
                var length = bits.Stride * bits.Height;
                Buffer.MemoryCopy(bits.Scan0.ToPointer() !, dst.DataPointer.ToPointer() !, length, length);
            }
            finally
            {
                src.UnlockBits(bits);
            }
        }
Esempio n. 17
0
 /// <summary>
 /// Find one best match for each query descriptor (if mask is empty).
 /// </summary>
 /// <param name="queryDescriptors"></param>
 /// <param name="trainDescriptors"></param>
 /// <param name="mask"></param>
 /// <returns></returns>
 public DMatch[] Match(Mat queryDescriptors, Mat trainDescriptors, Mat? mask = null)
 {
     ThrowIfDisposed();
     if (queryDescriptors == null)
         throw new ArgumentNullException(nameof(queryDescriptors));
     if (trainDescriptors == null)
         throw new ArgumentNullException(nameof(trainDescriptors));
     using var matchesVec = new VectorOfDMatch();
     NativeMethods.HandleException(
         NativeMethods.features2d_DescriptorMatcher_match1(
             ptr, queryDescriptors.CvPtr, trainDescriptors.CvPtr,
             matchesVec.CvPtr, Cv2.ToPtr(mask)));
     GC.KeepAlive(this);
     GC.KeepAlive(queryDescriptors);
     GC.KeepAlive(trainDescriptors);
     GC.KeepAlive(mask);
     return matchesVec.ToArray();
 }
Esempio n. 18
0
 /// <summary>
 /// Find k best matches for each query descriptor (in increasing order of distances).
 /// compactResult is used when mask is not empty. If compactResult is false matches
 /// vector will have the same size as queryDescriptors rows. If compactResult is true
 /// matches vector will not contain matches for fully masked out query descriptors.
 /// </summary>
 /// <param name="queryDescriptors"></param>
 /// <param name="trainDescriptors"></param>
 /// <param name="k"></param>
 /// <param name="mask"></param>
 /// <param name="compactResult"></param>
 /// <returns></returns>
 public DMatch[][] KnnMatch(Mat queryDescriptors, Mat trainDescriptors,
     int k, Mat? mask = null, bool compactResult = false)
 {
     ThrowIfDisposed();
     if (queryDescriptors == null)
         throw new ArgumentNullException(nameof(queryDescriptors));
     if (trainDescriptors == null)
         throw new ArgumentNullException(nameof(trainDescriptors));
     using var matchesVec = new VectorOfVectorDMatch();
     NativeMethods.HandleException(
         NativeMethods.features2d_DescriptorMatcher_knnMatch1(
             ptr, queryDescriptors.CvPtr, trainDescriptors.CvPtr,
             matchesVec.CvPtr, k, Cv2.ToPtr(mask), compactResult ? 1 : 0));
     GC.KeepAlive(this);
     GC.KeepAlive(queryDescriptors);
     GC.KeepAlive(trainDescriptors);
     GC.KeepAlive(mask);
     return matchesVec.ToArray();
 }
Esempio n. 19
0
 private void StroqChanged(Stroq s, Mat?m)
 {
     if (!m.HasValue)
     {
         StroqChanged(s);
     }
     else
     {
         Stroke ms = _map[s];
         System.Drawing.Drawing2D.Matrix mm = new System.Drawing.Drawing2D.Matrix(
             (float)m.Value[0, 0],
             (float)m.Value[0, 1],
             (float)m.Value[1, 0],
             (float)m.Value[1, 1],
             (float)(m.Value[0, 2] * OldStrokeStuff.Scale),
             (float)(m.Value[1, 2] * OldStrokeStuff.Scale));
         ms.Transform(mm);
         if (StrokeTransformed != null)
         {
             StrokeTransformed(ms, mm);
         }
     }
 }
Esempio n. 20
0
 /// <summary>
 /// Find best matches for each query descriptor which have distance less than
 /// maxDistance (in increasing order of distances).
 /// </summary>
 /// <param name="queryDescriptors"></param>
 /// <param name="trainDescriptors"></param>
 /// <param name="maxDistance"></param>
 /// <param name="mask"></param>
 /// <param name="compactResult"></param>
 /// <returns></returns>
 public DMatch[][] RadiusMatch(Mat queryDescriptors, Mat trainDescriptors,
                               float maxDistance, Mat?mask = null, bool compactResult = false)
 {
     ThrowIfDisposed();
     if (queryDescriptors == null)
     {
         throw new ArgumentNullException(nameof(queryDescriptors));
     }
     if (trainDescriptors == null)
     {
         throw new ArgumentNullException(nameof(trainDescriptors));
     }
     using (var matchesVec = new VectorOfVectorDMatch())
     {
         NativeMethods.features2d_DescriptorMatcher_radiusMatch1(
             ptr, queryDescriptors.CvPtr, trainDescriptors.CvPtr,
             matchesVec.CvPtr, maxDistance, Cv2.ToPtr(mask), compactResult ? 1 : 0);
         GC.KeepAlive(this);
         GC.KeepAlive(queryDescriptors);
         GC.KeepAlive(trainDescriptors);
         GC.KeepAlive(mask);
         return(matchesVec.ToArray());
     }
 }
Esempio n. 21
0
 protected void _stroq_PointsModified(Stroq s, Mat?m)
 {
     Redraw();
 }
Esempio n. 22
0
        /// <summary>
        /// 適当なウィンドウ名で、画像の表示モードを指定して初期化
        /// </summary>
        /// <param name="flags">ウィンドウのフラグ</param>
        /// <param name="image">ウィンドウに表示する画像</param>
#else
        /// <summary>
        /// Creates a window with a specified image and flag
        /// </summary>
        /// <param name="flags">Flags of the window. Currently the only supported flag is WindowMode.AutoSize.
        /// If it is set, window size is automatically adjusted to fit the displayed image (see cvShowImage), while user can not change the window size manually. </param>
        /// <param name="image"></param>
#endif
        public Window(WindowMode flags, Mat?image)
            : this(DefaultName(), flags, image)
        {
        }
Esempio n. 23
0
        /// <summary>
        /// ウィンドウ名と始めから表示しておく画像を指定して初期化
        /// </summary>
        /// <param name="name">ウィンドウの識別に用いられるウィンドウ名で,ウィンドウのタイトルバ ーに表示される.</param>
        /// <param name="image">ウィンドウに表示する画像</param>
#else
        /// <summary>
        /// Creates a window
        /// </summary>
        /// <param name="name">Name of the window which is used as window identifier and appears in the window caption. </param>
        /// <param name="image">Image to be shown.</param>
#endif
        public Window(string name, Mat?image)
            : this(name, WindowMode.AutoSize, image)
        {
        }
Esempio n. 24
0
        /// <summary>
        /// Performs images matching.
        /// </summary>
        /// <param name="features">Features of the source images</param>
        /// <param name="mask">Mask indicating which image pairs must be matched</param>
        /// <returns>Found pairwise matches</returns>
        public virtual MatchesInfo[] Apply(
            IEnumerable <ImageFeatures> features, Mat?mask = null)
        {
            if (features == null)
            {
                throw new ArgumentNullException(nameof(features));
            }
            ThrowIfDisposed();

            var featuresArray = features.CastOrToArray();

            if (featuresArray.Length == 0)
            {
                throw new ArgumentException("Empty features array", nameof(features));
            }

            var keypointVecs   = new VectorOfKeyPoint?[featuresArray.Length];
            var wImageFeatures = new WImageFeatures[featuresArray.Length];

            try
            {
                for (int i = 0; i < featuresArray.Length; i++)
                {
                    if (featuresArray[i].Descriptors == null)
                    {
                        throw new ArgumentException("features contain null descriptor mat", nameof(features));
                    }
                    featuresArray[i].Descriptors.ThrowIfDisposed();

                    keypointVecs[i]   = new VectorOfKeyPoint();
                    wImageFeatures[i] = new WImageFeatures
                    {
                        ImgIdx      = featuresArray[i].ImgIdx,
                        ImgSize     = featuresArray[i].ImgSize,
                        Keypoints   = keypointVecs[i] !.CvPtr,
                        Descriptors = featuresArray[i].Descriptors.CvPtr,
                    };
                }

                using var srcImgIndexVecs = new VectorOfInt32();
                using var dstImgIndexVecs = new VectorOfInt32();
                using var matchesVec      = new VectorOfVectorDMatch();
                using var inlinersMaskVec = new VectorOfVectorByte();
                using var numInliersVecs  = new VectorOfInt32();
                using var hVecs           = new VectorOfMat();
                using var confidenceVecs  = new VectorOfDouble();
                NativeMethods.HandleException(
                    NativeMethods.stitching_FeaturesMatcher_apply2(
                        ptr,
                        wImageFeatures, wImageFeatures.Length,
                        mask?.CvPtr ?? IntPtr.Zero,
                        srcImgIndexVecs.CvPtr,
                        dstImgIndexVecs.CvPtr,
                        matchesVec.CvPtr,
                        inlinersMaskVec.CvPtr,
                        numInliersVecs.CvPtr,
                        hVecs.CvPtr,
                        confidenceVecs.CvPtr
                        ));

                var srcImgIndices = srcImgIndexVecs.ToArray();
                var dstImgIndices = dstImgIndexVecs.ToArray();
                var matches       = matchesVec.ToArray();
                var inlinersMasks = inlinersMaskVec.ToArray();
                var numInliers    = numInliersVecs.ToArray();
                var hs            = hVecs.ToArray();
                var confidences   = confidenceVecs.ToArray();
                var result        = new MatchesInfo[srcImgIndices.Length];
                for (int i = 0; i < srcImgIndices.Length; i++)
                {
                    result[i] = new MatchesInfo(
                        srcImgIndices[i],
                        dstImgIndices[i],
                        matches[i],
                        inlinersMasks[i],
                        numInliers[i],
                        hs[i],
                        confidences[i]);
                }
                return(result);
            }
            finally
            {
                foreach (var vec in keypointVecs)
                {
                    vec?.Dispose();
                }
                GC.KeepAlive(this);
            }
        }
Esempio n. 25
0
        private Location LookupOrCreate(
            StatisticsDbContext context,
            GeographicLevel geographicLevel,
            Country country,
            EnglishDevolvedArea?englishDevolvedArea,
            Institution?institution,
            LocalAuthority?localAuthority,
            LocalAuthorityDistrict?localAuthorityDistrict,
            LocalEnterprisePartnership?localEnterprisePartnership,
            MayoralCombinedAuthority?mayoralCombinedAuthority,
            Mat?multiAcademyTrust,
            OpportunityArea?opportunityArea,
            ParliamentaryConstituency?parliamentaryConstituency,
            PlanningArea?planningArea,
            Provider?provider,
            Region?region,
            RscRegion?rscRegion,
            School?school,
            Sponsor?sponsor,
            Ward?ward)
        {
            var location = Lookup(
                context,
                geographicLevel,
                country,
                englishDevolvedArea,
                institution,
                localAuthority,
                localAuthorityDistrict,
                localEnterprisePartnership,
                mayoralCombinedAuthority,
                multiAcademyTrust,
                opportunityArea,
                parliamentaryConstituency,
                planningArea,
                provider,
                region,
                rscRegion,
                school,
                sponsor,
                ward);

            if (location == null)
            {
                var entityEntry = context.Location.Add(new Location
                {
                    Id = _guidGenerator.NewGuid(),
                    GeographicLevel            = geographicLevel,
                    Country                    = country,
                    EnglishDevolvedArea        = englishDevolvedArea,
                    Institution                = institution,
                    LocalAuthority             = localAuthority,
                    LocalAuthorityDistrict     = localAuthorityDistrict,
                    LocalEnterprisePartnership = localEnterprisePartnership,
                    MayoralCombinedAuthority   = mayoralCombinedAuthority,
                    MultiAcademyTrust          = multiAcademyTrust,
                    OpportunityArea            = opportunityArea,
                    ParliamentaryConstituency  = parliamentaryConstituency,
                    PlanningArea               = planningArea,
                    Provider                   = provider,
                    Region    = region,
                    RscRegion = rscRegion,
                    School    = school,
                    Sponsor   = sponsor,
                    Ward      = ward
                });

                return(entityEntry.Entity);
            }

            return(location);
        }
Esempio n. 26
0
        private Location?Lookup(
            StatisticsDbContext context,
            GeographicLevel geographicLevel,
            Country country,
            EnglishDevolvedArea?englishDevolvedArea,
            Institution?institution,
            LocalAuthority?localAuthority,
            LocalAuthorityDistrict?localAuthorityDistrict,
            LocalEnterprisePartnership?localEnterprisePartnership,
            MayoralCombinedAuthority?mayoralCombinedAuthority,
            Mat?multiAcademyTrust,
            OpportunityArea?opportunityArea,
            ParliamentaryConstituency?parliamentaryConstituency,
            PlanningArea?planningArea,
            Provider?provider,
            Region?region,
            RscRegion?rscRegion,
            School?school,
            Sponsor?sponsor,
            Ward?ward)
        {
            var predicateBuilder = PredicateBuilder.True <Location>()
                                   .And(location => location.GeographicLevel == geographicLevel);

            predicateBuilder = predicateBuilder
                               .And(location => location.Country_Code == country.Code &&
                                    location.Country_Name == country.Name);

            predicateBuilder = predicateBuilder
                               .And(location => location.EnglishDevolvedArea_Code == (englishDevolvedArea != null ? englishDevolvedArea.Code : null) &&
                                    location.EnglishDevolvedArea_Name == (englishDevolvedArea != null ? englishDevolvedArea.Name : null));

            predicateBuilder = predicateBuilder
                               .And(location => location.Institution_Code == (institution != null ? institution.Code : null) &&
                                    location.Institution_Name == (institution != null ? institution.Name : null));

            // Also match the old LA code even if blank
            predicateBuilder = predicateBuilder
                               .And(location =>
                                    location.LocalAuthority_Code == (localAuthority != null && localAuthority.Code != null ? localAuthority.Code : null) &&
                                    location.LocalAuthority_OldCode == (localAuthority != null && localAuthority.OldCode != null ? localAuthority.OldCode : null) &&
                                    location.LocalAuthority_Name == (localAuthority != null ? localAuthority.Name : null));

            predicateBuilder = predicateBuilder
                               .And(location => location.LocalAuthorityDistrict_Code == (localAuthorityDistrict != null ? localAuthorityDistrict.Code : null) &&
                                    location.LocalAuthorityDistrict_Name == (localAuthorityDistrict != null ? localAuthorityDistrict.Name : null));

            predicateBuilder = predicateBuilder
                               .And(location => location.LocalEnterprisePartnership_Code == (localEnterprisePartnership != null ? localEnterprisePartnership.Code : null) &&
                                    location.LocalEnterprisePartnership_Name == (localEnterprisePartnership != null ? localEnterprisePartnership.Name : null));

            predicateBuilder = predicateBuilder
                               .And(location => location.MayoralCombinedAuthority_Code == (mayoralCombinedAuthority != null ? mayoralCombinedAuthority.Code : null) &&
                                    location.MayoralCombinedAuthority_Name == (mayoralCombinedAuthority != null ? mayoralCombinedAuthority.Name : null));

            predicateBuilder = predicateBuilder
                               .And(location => location.MultiAcademyTrust_Code == (multiAcademyTrust != null ? multiAcademyTrust.Code : null) &&
                                    location.MultiAcademyTrust_Name == (multiAcademyTrust != null ? multiAcademyTrust.Name : null));

            predicateBuilder = predicateBuilder
                               .And(location => location.OpportunityArea_Code == (opportunityArea != null ? opportunityArea.Code : null) &&
                                    location.OpportunityArea_Name == (opportunityArea != null ? opportunityArea.Name : null));

            predicateBuilder = predicateBuilder
                               .And(location => location.ParliamentaryConstituency_Code == (parliamentaryConstituency != null ? parliamentaryConstituency.Code : null) &&
                                    location.ParliamentaryConstituency_Name == (parliamentaryConstituency != null ? parliamentaryConstituency.Name : null));

            predicateBuilder = predicateBuilder
                               .And(location => location.PlanningArea_Code == (planningArea != null ? planningArea.Code : null) &&
                                    location.PlanningArea_Name == (planningArea != null ? planningArea.Name : null));

            predicateBuilder = predicateBuilder
                               .And(location => location.Provider_Code == (provider != null ? provider.Code : null) &&
                                    location.Provider_Name == (provider != null ? provider.Name : null));

            predicateBuilder = predicateBuilder
                               .And(location => location.Region_Code == (region != null ? region.Code : null) &&
                                    location.Region_Name == (region != null ? region.Name : null));

            // Note that Name is not included in the predicate here as it is the same as the code
            predicateBuilder = predicateBuilder
                               .And(location => location.RscRegion_Code == (rscRegion != null ? rscRegion.Code : null));

            predicateBuilder = predicateBuilder
                               .And(location =>
                                    location.School_Code == (school != null ? school.Code : null) &&
                                    location.School_Name == (school != null ? school.Name : null));

            predicateBuilder = predicateBuilder
                               .And(location => location.Sponsor_Code == (sponsor != null ? sponsor.Code : null) &&
                                    location.Sponsor_Name == (sponsor != null ? sponsor.Name : null));

            predicateBuilder = predicateBuilder
                               .And(location => location.Ward_Code == (ward != null ? ward.Code : null) &&
                                    location.Ward_Name == (ward != null ? ward.Name : null));

            // This can return multiple results because C# equality is translated directly to SQL equality
            // and our config of SqlServer is using the default case-insensitive collation
            // See https://docs.microsoft.com/en-us/ef/core/miscellaneous/collations-and-case-sensitivity
            var locations = context.Location
                            .AsNoTracking()
                            .Where(predicateBuilder)
                            .ToList();

            // Perform case-sensitive comparison on the Name fields
            return(locations.FirstOrDefault(location =>
                                            location.Country_Name == country.Name &&
                                            location.EnglishDevolvedArea_Name == englishDevolvedArea?.Name &&
                                            location.Institution_Name == institution?.Name &&
                                            location.LocalAuthority_Name == localAuthority?.Name &&
                                            location.LocalAuthorityDistrict_Name == localAuthorityDistrict?.Name &&
                                            location.LocalEnterprisePartnership_Name == localEnterprisePartnership?.Name &&
                                            location.MayoralCombinedAuthority_Name == mayoralCombinedAuthority?.Name &&
                                            location.MultiAcademyTrust_Name == multiAcademyTrust?.Name &&
                                            location.OpportunityArea_Name == opportunityArea?.Name &&
                                            location.ParliamentaryConstituency_Name == parliamentaryConstituency?.Name &&
                                            location.PlanningArea_Name == planningArea?.Name &&
                                            location.Provider_Name == provider?.Name &&
                                            location.Region_Name == region?.Name &&
                                            location.RscRegion_Code == rscRegion?.Code && // RscRegion codes function as the name
                                            location.School_Name == school?.Name &&
                                            location.Sponsor_Name == sponsor?.Name &&
                                            location.Ward_Name == ward?.Name
                                            ));
        }
Esempio n. 27
0
        public Location FindOrCreate(
            StatisticsDbContext context,
            GeographicLevel geographicLevel,
            Country country,
            EnglishDevolvedArea?englishDevolvedArea = null,
            Institution?institution       = null,
            LocalAuthority?localAuthority = null,
            LocalAuthorityDistrict?localAuthorityDistrict         = null,
            LocalEnterprisePartnership?localEnterprisePartnership = null,
            MayoralCombinedAuthority?mayoralCombinedAuthority     = null,
            Mat?multiAcademyTrust           = null,
            OpportunityArea?opportunityArea = null,
            ParliamentaryConstituency?parliamentaryConstituency = null,
            PlanningArea?planningArea = null,
            Provider?provider         = null,
            Region?region             = null,
            RscRegion?rscRegion       = null,
            School?school             = null,
            Sponsor?sponsor           = null,
            Ward?ward = null)
        {
            var cacheKey = GetCacheKey(
                geographicLevel,
                country,
                englishDevolvedArea,
                institution,
                localAuthority,
                localAuthorityDistrict,
                localEnterprisePartnership,
                mayoralCombinedAuthority,
                multiAcademyTrust,
                opportunityArea,
                parliamentaryConstituency,
                planningArea,
                provider,
                region,
                rscRegion,
                school,
                sponsor,
                ward);

            if (_memoryCache.Cache.TryGetValue(cacheKey, out Location location))
            {
                return(location);
            }

            location = LookupOrCreate(
                context,
                geographicLevel,
                country,
                englishDevolvedArea,
                institution,
                localAuthority,
                localAuthorityDistrict,
                localEnterprisePartnership,
                mayoralCombinedAuthority,
                multiAcademyTrust,
                opportunityArea,
                parliamentaryConstituency,
                planningArea,
                provider,
                region,
                rscRegion,
                school,
                sponsor,
                ward);
            _memoryCache.Cache.Set(cacheKey, location);

            return(location);
        }
Esempio n. 28
0
 public static bool IsEquals(Mat mat1, Mat mat2, Mat? mask = null) => IsEquals(GetDifference(mat1, mat2, mask));