Exemplo n.º 1
0
        public async Task TestUploadDirectory()
        {
            // First create the file hierarchy on the local file system
            var rootPath = await CreateLocalFileTree(nameof(TestUploadDirectory));

            // Then upload the directory to blob storage
            var container = _blobClient.GetContainerReference("container");

            container.CreateIfNotExists();
            string blobDirPath = $"{nameof(TestUploadDirectory)}/app/1.0.0";
            await BlobUtils.UploadDirectory(rootPath, container, blobDirPath);


            var blobDirectory = container.GetDirectoryReference(blobDirPath);
            var blobs         = await blobDirectory.ListBlobsAsync();

            ISet <string> relativePathSet = new HashSet <string>();

            foreach (var blobItem in blobs)
            {
                var blob    = (CloudBlockBlob)blobItem;
                var relPath = BlobUtils.GetBlobRelativePath(blob, blobDirectory);
                relativePathSet.Add(relPath);
            }

            // Then verify that the hierachy on the blob storage matches the one the local file system
            VerifyThatAllFilesAreThere(relativePathSet, "/");
        }
        private static CloudBlobContainer GetApplicationsContainerReference(string connectionString)
        {
            CloudBlobContainer blobContainer = BlobUtils.GetBlobContainer(connectionString,
                                                                          ApplicationsRootFolderName);

            return(blobContainer);
        }
        public async Task DownloadApplicationBinaries(AppIdentity appIdentity, string localPath,
                                                      ConflictResolutionMode conflictResolutionMode)
        {
            bool exists = !FileUtils.DirectoryDoesntExistOrEmpty(localPath);

            if (exists)
            {
                if (conflictResolutionMode == ConflictResolutionMode.DoNothingIfBinariesExist)
                {
                    return;
                }
                if (conflictResolutionMode == ConflictResolutionMode.FailIfBinariesExist)
                {
                    throw new DuplicateBinariesException(
                              $"Cannot download the binaries because the destination directory {localPath} contains files");
                }
            }
            CloudBlobDirectory blobDirectory = GetBlobDirectory(appIdentity);

            if (!await blobDirectory.ExistsAsync())
            {
                throw new BinariesNotFoundException("The binaries were not found in the Yams repository");
            }
            await BlobUtils.DownloadBlobDirectory(blobDirectory, localPath);
        }
 private static async Task CreateBlobIfNoneExists(ICloudBlob updateBlob)
 {
     if (!await updateBlob.ExistsAsync())
     {
         await BlobUtils.CreateEmptyBlob(updateBlob);
     }
 }
        public async Task UploadApplicationBinaries(AppIdentity appIdentity, string localPath,
                                                    ConflictResolutionMode conflictResolutionMode)
        {
            if (FileUtils.DirectoryDoesntExistOrEmpty(localPath))
            {
                throw new BinariesNotFoundException(
                          $"Binaries were not be uploaded because they were not found at the given path {localPath}");
            }

            if (conflictResolutionMode == ConflictResolutionMode.OverwriteExistingBinaries)
            {
                await DeleteApplicationBinaries(appIdentity);
            }
            else
            {
                bool exists = await HasApplicationBinaries(appIdentity);

                if (exists)
                {
                    if (conflictResolutionMode == ConflictResolutionMode.DoNothingIfBinariesExist)
                    {
                        return;
                    }

                    if (conflictResolutionMode == ConflictResolutionMode.FailIfBinariesExist)
                    {
                        throw new DuplicateBinariesException(
                                  $"Cannot override binaries when flag {ConflictResolutionMode.FailIfBinariesExist} is used");
                    }
                }
            }

            // at this point we know that it is either OverwriteExistingBinaries mode or the binaries don't exist
            await BlobUtils.UploadDirectory(localPath, _blobContainer, GetBlobDirectoryRelPath(appIdentity));
        }
Exemplo n.º 6
0
        // POST api/BinaryItem
        public async Task <HttpResponseMessage> Post(BinaryUploadRequest binaryUploadRequest)
        {
            var binaryItem = new BinaryItem
            {
                Id         = Guid.NewGuid().ToString("N"),
                ObjectId   = binaryUploadRequest.BinaryId,
                BinaryType = binaryUploadRequest.BinaryType,
                UserId     = binaryUploadRequest.UserId
            };

            binaryItem.BinaryUrl =
                await BlobUtils.SaveBinaryToAzureStorage(settings, binaryItem.Id, binaryUploadRequest.BinaryData);

            if (!string.IsNullOrEmpty(binaryItem.BinaryUrl))
            {
                BeerDrinkinContext context = new BeerDrinkinContext();
                context.BinaryItems.Add(binaryItem);
                await context.SaveChangesAsync();

                return(this.Request.CreateResponse(HttpStatusCode.OK));
            }

            return(this.Request.CreateResponse(HttpStatusCode.Conflict,
                                               "Something wrong"));
        }
Exemplo n.º 7
0
 private async Task FetchOrCreate()
 {
     if (!await _blob.ExistsAsync())
     {
         await BlobUtils.CreateEmptyBlob(_blob);
     }
 }
Exemplo n.º 8
0
        private async Task <CloudBlobDirectory> CreateBlobsTree()
        {
            // root
            // |__b1
            // |__b2
            // |__d1
            // |  |__b1
            // |  |__b2
            // |__d2
            // |  |__b3
            // |  |__b4
            // |  |__d3
            // |  |  |__b5
            // |  |  |__b6
            // |__d4
            // |  |__d5
            // |  |  |__b7

            var container = _blobClient.GetContainerReference("container");

            container.CreateIfNotExists();

            var root = container.GetDirectoryReference("root");

            ICloudBlob b1 = root.GetBlockBlobReference("b1");
            await BlobUtils.CreateEmptyBlob(b1);

            ICloudBlob b2 = root.GetBlockBlobReference("b2");
            await BlobUtils.CreateEmptyBlob(b2);

            var        d1   = root.GetDirectoryReference("d1");
            ICloudBlob d1b1 = d1.GetBlockBlobReference("b1");
            ICloudBlob d1b2 = d1.GetBlockBlobReference("b2");
            await BlobUtils.CreateEmptyBlob(d1b1);

            await BlobUtils.CreateEmptyBlob(d1b2);

            var        d2   = root.GetDirectoryReference("d2");
            ICloudBlob d2b3 = d2.GetBlockBlobReference("b3");
            ICloudBlob d2b4 = d2.GetBlockBlobReference("b4");
            await BlobUtils.CreateEmptyBlob(d2b3);

            await BlobUtils.CreateEmptyBlob(d2b4);

            var        d2d3   = d2.GetDirectoryReference("d3");
            ICloudBlob d2d3b5 = d2d3.GetBlockBlobReference("b5");
            ICloudBlob d2d3b6 = d2d3.GetBlockBlobReference("b6");
            await BlobUtils.CreateEmptyBlob(d2d3b5);

            await BlobUtils.CreateEmptyBlob(d2d3b6);

            await BlobUtils.CreateEmptyBlob(
                root.GetDirectoryReference("d4").GetDirectoryReference("d5").GetBlockBlobReference("b7"));

            return(root);
        }
Exemplo n.º 9
0
        async Task ITaskHub.DeleteAsync()
        {
            if (await this.taskhubParameters.ExistsAsync().ConfigureAwait(false))
            {
                await BlobUtils.ForceDeleteAsync(this.taskhubParameters).ConfigureAwait(false);
            }

            // todo delete consumption checkpoints
            await this.host.StorageProvider.DeleteAllPartitionStatesAsync().ConfigureAwait(false);
        }
Exemplo n.º 10
0
        private async Task <CloudBlockBlob> CreateEmptyBlob(string blobName)
        {
            const string       containerName = "container";
            CloudBlobContainer container     = _blobClient.GetContainerReference(containerName);

            container.CreateIfNotExists();
            CloudBlockBlob blob = container.GetBlockBlobReference(blobName);
            await BlobUtils.CreateEmptyBlob(blob);

            return(blob);
        }
Exemplo n.º 11
0
        private async Task TestThatLockFailsIfBlobLeaseCantBeAcquired(IBlobLease blobLeaseStub)
        {

            var leaseFactoryMock = new StubIBlobLeaseFactory
            {
                CreateLease_ICloudBlob = blob => blobLeaseStub
            };
            var testBlob = _container.GetBlockBlobReference("testBlob");
            await BlobUtils.CreateEmptyBlob(testBlob);
            UpdateBlob updateBlob = new UpdateBlob(testBlob, leaseFactoryMock);
            Assert.False(await updateBlob.TryLock());
        }
Exemplo n.º 12
0
        public async Task TestNameOfBlobInDirectory()
        {
            string blobName = "blob";

            CloudBlobContainer container = _blobClient.GetContainerReference("container");

            container.CreateIfNotExists();
            CloudBlobDirectory directory = container.GetDirectoryReference("directory");
            CloudBlockBlob     blob      = directory.GetBlockBlobReference(blobName);
            await BlobUtils.CreateEmptyBlob(blob);

            AzureBlob azureBlob = new AzureBlob(blob);

            Assert.AreEqual(blobName, azureBlob.Name);
        }
Exemplo n.º 13
0
        public async Task <IUpdateBlob> TryLockUpdateBlob(string appId)
        {
            string     updateBlobName = GetUpdateBlobName(appId);
            ICloudBlob blob           = GetBlob(updateBlobName);
            await BlobUtils.CreateBlobIfNotExists(blob);

            UpdateBlob updateBlob = new UpdateBlob(blob, _blobLeaseFactory);
            bool       locked     = await updateBlob.TryLock();

            if (locked == false)
            {
                throw new UpdateBlobUnavailableException();
            }
            return(updateBlob);
        }
Exemplo n.º 14
0
        public async Task TestCreateBlobIfNotExists()
        {
            var container = _blobClient.GetContainerReference("container");

            container.CreateIfNotExists();
            var blob = container.GetBlockBlobReference("createIfNotExistsTestBlob.txt");
            await BlobUtils.CreateBlobIfNotExists(blob);

            Assert.True(await blob.ExistsAsync());
            string text = "test content";
            await blob.UploadTextAsync(text);

            await BlobUtils.CreateBlobIfNotExists(blob);

            Assert.Equal(text, await blob.DownloadTextAsync());
        }
Exemplo n.º 15
0
        public async Task TestDownloadBlobsFromBlobDirectory()
        {
            // First create the file hierarchy in the blob storage
            CloudBlobDirectory root = await CreateBlobsTree();

            // The upload the directory to a local temporary folder
            var tempPath = GetTestDirPath(nameof(TestDownloadBlobsFromBlobDirectory));
            var appPath  = Path.Combine(tempPath, "app\\1.0.0");
            await BlobUtils.DownloadBlobDirectory(root, appPath);

            ISet <string> relativePathSet = new HashSet <string>();

            foreach (var path in FileUtils.ListFilesRecursively(appPath))
            {
                var relPath = FileUtils.GetRelativePath(appPath, path);
                relativePathSet.Add(relPath);
            }

            // Then verify that the hierachy on the local file system matches the one in the blob directory
            VerifyThatAllFilesAreThere(relativePathSet, "\\");

            // get the modified data of d1/b1
            string   d1b1Path      = Path.Combine(appPath, "d1", "b1");
            DateTime d1b1WriteTime = File.GetLastWriteTimeUtc(d1b1Path);

            // delete and modify some files to make sure that they will be download
            File.Delete(Path.Combine(appPath, "b1"));
            File.Delete(Path.Combine(appPath, "d1", "b2"));

            // modify a file to make sure it'll be replaced
            string   b2FilePath  = Path.Combine(appPath, "b2");
            DateTime b2WriteTime = File.GetLastWriteTimeUtc(b2FilePath);

            File.WriteAllText(b2FilePath, "blabla");
            Assert.Equal("blabla", File.ReadAllText(b2FilePath));

            await BlobUtils.DownloadBlobDirectory(root, appPath);

            VerifyThatAllFilesAreThere(relativePathSet, "\\");
            string newFileContent = File.ReadAllText(b2FilePath);

            Assert.Equal(d1b1WriteTime, File.GetLastWriteTimeUtc(d1b1Path));
            Assert.NotEqual(b2WriteTime, File.GetLastWriteTimeUtc(b2FilePath));
        }
Exemplo n.º 16
0
        public async Task TestUploadFile()
        {
            var container = _blobClient.GetContainerReference("container");

            container.CreateIfNotExists();

            var testDirPath     = GetTestDirPath(nameof(TestUploadFile));
            var testFilePath    = Path.Combine(testDirPath, "testFile.txt");
            var testFileContent = "TestUploadFileToBlob";

            File.WriteAllText(testFilePath, testFileContent);

            var testBlobPath = "testBlob.txt";
            await BlobUtils.UploadFile(testFilePath, container, testBlobPath);

            var blob = container.GetBlockBlobReference(testBlobPath);

            Assert.True(await blob.ExistsAsync());
            Assert.Equal(testFileContent, await blob.DownloadTextAsync());
        }
Exemplo n.º 17
0
        public async Task TestDownloadBlobsFromBlobDirectory()
        {
            // First create the file hierarchy in the blob storage
            CloudBlobDirectory root = await CreateBlobsTree();

            // The upload the directory to a local temporary folder
            var tempPath = GetTestDirPath(nameof(TestDownloadBlobsFromBlobDirectory));
            var appPath  = Path.Combine(tempPath, "app\\1.0.0");
            await BlobUtils.DownloadBlobDirectory(root, appPath);

            ISet <string> relativePathSet = new HashSet <string>();

            foreach (var path in FileUtils.ListFilesRecursively(appPath))
            {
                var relPath = FileUtils.GetRelativePath(appPath, path);
                relativePathSet.Add(relPath);
            }

            // Then verify that the hierachy on the local file system matches the one in the blob directory
            VerifyThatAllFilesAreThere(relativePathSet, "\\");
        }
        public static ContainerBuilder RegisterTypes(string deploymentId,
                                                     string instanceId,
                                                     string updateDomain,
                                                     string connectionString,
                                                     string blobContainerName                   = "applications",
                                                     int lockBlobRetryCount                     = 20,
                                                     int lockBlobRetryIntervalInSeconds         = 1,
                                                     int storageExceptionRetryCount             = 20,
                                                     int storageExceptionRetryIntervalInSeconds = 1)
        {
            var containerBuilder = new ContainerBuilder();

            containerBuilder.RegisterType <BlobLeaseFactory>().As <IBlobLeaseFactory>().SingleInstance();

            containerBuilder.Register <IUpdateBlobFactory>(c =>
                                                           new UpdateBlobFactoryRetryLockDecorator(
                                                               new UpdateBlobFactory(deploymentId,
                                                                                     BlobUtils.GetBlobContainer(connectionString, blobContainerName),
                                                                                     c.Resolve <IBlobLeaseFactory>()),
                                                               c.ResolveNamed <RetryStrategy>(UpdateBlobFactoryRetryStrategyModuleName)
                                                               )).SingleInstance();

            containerBuilder.Register <RetryStrategy>(
                c => new FixedInterval(lockBlobRetryCount, TimeSpan.FromSeconds(lockBlobRetryIntervalInSeconds)))
            .Named <RetryStrategy>(UpdateBlobFactoryRetryStrategyModuleName).SingleInstance();

            containerBuilder.Register <RetryStrategy>(
                c => new FixedInterval(storageExceptionRetryCount, TimeSpan.FromSeconds(storageExceptionRetryIntervalInSeconds)))
            .Named <RetryStrategy>(UpdateSessionRetryStrategyModuleName).SingleInstance();

            containerBuilder.Register(
                c => new BlobBasedUpdateSessionManager(c.Resolve <IUpdateBlobFactory>(), instanceId, updateDomain));

            containerBuilder.Register <IUpdateSessionManager>(
                c => new UpdateSessionManagerRetryDecorator(
                    c.Resolve <BlobBasedUpdateSessionManager>(),
                    c.ResolveNamed <RetryStrategy>(UpdateSessionRetryStrategyModuleName),
                    new StorageExceptionErrorDetectionStrategy()));
            return(containerBuilder);
        }
Exemplo n.º 19
0
        public void MergeChunksBody()
        {
            var entities = new List <BlobEntity>()
            {
                new BlobEntity()
                {
                    Body = new byte[] { 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00 }
                },
                new BlobEntity()
                {
                    Body = new byte[] { 0x00, 0x00, 0x0b, 0x62, 0x64, 0x62, 0x06 }
                },
                new BlobEntity()
                {
                    Body = new byte[] { 0x00, 0x00, 0x00, 0xff, 0xff }
                },
            };

            Assert.Equal(
                JsonConvert.SerializeObject(new byte[] { 1, 2, 3 }),
                JsonConvert.SerializeObject(BlobUtils.MergeChunksBody(entities)));
        }
Exemplo n.º 20
0
        private Content CreateContent(HttpPostedFileBase contentFile, Artifact artifact, DateTime publishDate, User creator)
        {
            CloudBlockBlob contentBlob;
            Content        content = new Content();

            if (contentFile != null && contentFile.ContentLength != 0)
            {
                contentBlob = BlobUtils.UploadAndSaveBlob(cmsContentBlobContainer, contentFile);

                content.Artifact    = artifact;
                content.ArtifactId  = artifact.ArtifactId;
                content.ContentUrl  = contentBlob.Uri.ToString();
                content.CreatorId   = creator.UserId;
                content.CreateDate  = DateTime.Now.Date;
                content.PublishDate = publishDate;
                if (artifact.Version > 0)
                {
                    artifact.Version++;
                }
                content.Version = artifact.Version;
            }

            return(content);
        }
Exemplo n.º 21
0
 private async Task CreateEmptyBlob(ICloudBlob blob)
 {
     await BlobUtils.CreateEmptyBlob(blob);
 }
Exemplo n.º 22
0
 public Task Download(string destPath)
 {
     return(BlobUtils.DownloadBlobContainer(_blobContainer, destPath));
 }
Exemplo n.º 23
0
        public async Task TestDownloadBlobsFromBlobDirectory()
        {
            CloudBlobContainer container = _blobClient.GetContainerReference("container");

            container.CreateIfNotExists();

            CloudBlobDirectory root = container.GetDirectoryReference("root");

            ICloudBlob b1 = root.GetBlockBlobReference("b1");
            await BlobUtils.CreateEmptyBlob(b1);

            ICloudBlob b2 = root.GetBlockBlobReference("b2");
            await BlobUtils.CreateEmptyBlob(b2);

            CloudBlobDirectory d1   = root.GetDirectoryReference("d1");
            ICloudBlob         d1b1 = d1.GetBlockBlobReference("b1");
            ICloudBlob         d1b2 = d1.GetBlockBlobReference("b2");
            await BlobUtils.CreateEmptyBlob(d1b1);

            await BlobUtils.CreateEmptyBlob(d1b2);

            CloudBlobDirectory d2   = root.GetDirectoryReference("d2");
            ICloudBlob         d2b3 = d2.GetBlockBlobReference("b3");
            ICloudBlob         d2b4 = d2.GetBlockBlobReference("b4");
            await BlobUtils.CreateEmptyBlob(d2b3);

            await BlobUtils.CreateEmptyBlob(d2b4);

            CloudBlobDirectory d2d3   = d2.GetDirectoryReference("d3");
            ICloudBlob         d2d3b5 = d2d3.GetBlockBlobReference("b5");
            ICloudBlob         d2d3b6 = d2d3.GetBlockBlobReference("b6");
            await BlobUtils.CreateEmptyBlob(d2d3b5);

            await BlobUtils.CreateEmptyBlob(d2d3b6);

            await BlobUtils.CreateEmptyBlob(
                root.GetDirectoryReference("d4").GetDirectoryReference("d5").GetBlockBlobReference("b7"));

            // The hierarchy in the blob storage is as follows:
            //
            // root
            // |__b1
            // |__b2
            // |__d1
            // |  |__b1
            // |  |__b2
            // |__d2
            // |  |__b3
            // |  |__b4
            // |  |__d3
            // |  |  |__b5
            // |  |  |__b6
            // |__d4
            // |  |__d5
            // |  |  |__b7

            string tempPath = Path.Combine(Path.GetTempPath(), "TestDownloadBlobsFromBlobDirectory");
            await BlobUtils.DownloadBlobDirectory(root, tempPath);

            ISet <string> relativePathSet = new HashSet <string>();

            foreach (string path in Directory.GetFiles(tempPath, "*.*", SearchOption.AllDirectories))
            {
                string hash = path.Remove(0, tempPath.Length);
                relativePathSet.Add(hash);
            }

            Assert.AreEqual(9, relativePathSet.Count);
            Assert.IsTrue(relativePathSet.Contains("\\b1"));
            Assert.IsTrue(relativePathSet.Contains("\\b2"));
            Assert.IsTrue(relativePathSet.Contains("\\d1\\b1"));
            Assert.IsTrue(relativePathSet.Contains("\\d1\\b2"));
            Assert.IsTrue(relativePathSet.Contains("\\d2\\b3"));
            Assert.IsTrue(relativePathSet.Contains("\\d2\\b4"));
            Assert.IsTrue(relativePathSet.Contains("\\d2\\d3\\b5"));
            Assert.IsTrue(relativePathSet.Contains("\\d2\\d3\\b6"));
            Assert.IsTrue(relativePathSet.Contains("\\d4\\d5\\b7"));
        }
Exemplo n.º 24
0
 private Task CreateEmptyBlob(ICloudBlob blob)
 {
     return(BlobUtils.CreateEmptyBlob(blob));
 }
Exemplo n.º 25
0
 public Task Download(string destPath)
 {
     return(BlobUtils.DownloadBlobDirectory(_cloudBlobDirectory, destPath));
 }
Exemplo n.º 26
0
        public static void TestMain()
        {
            while (true)
            {
                string fileName = @"./Images/";
                Console.WriteLine("输入图片名称");
                fileName += Console.ReadLine();
                Console.WriteLine(DateTime.Now.ToString("HH:mm:ss fff"));
                bool isNeedToSave = BlobUtils.IsNeedToSave(fileName);
                Console.WriteLine("IsNeedToSave = " + isNeedToSave);
                Console.WriteLine(DateTime.Now.ToString("HH:mm:ss fff"));
            }


            //图片名称
            string imgFile = @"./Images/check1.jpg";
            //光线模式文件
            string lightPatternFile = @"./Images/blank.jpg";
            //移除背景光线的方法  0 different差  1 div 除 (根据测试除的效果略好于差,均大幅好于不用)
            int lightMethod = 0;

            Console.WriteLine("lightmethod = " + lightMethod);
            // 分割的方法  1 connected component    2 connected components with statistic(统计)  3 find contour(轮廓线)
            int segmentMethod = 1;

            //转换为单通道灰度图
            Mat img      = Cv2.ImRead(imgFile, ImreadModes.GrayScale);
            Mat cloneImg = img.Clone();

            //noise removal 噪音去除
            img = img.MedianBlur(3);

            //使用光照模型去除背景, 拍摄同样一张图片但是不带物体
            Mat light = Cv2.ImRead(lightPatternFile, ImreadModes.GrayScale);

            light = light.MedianBlur(3);
            if (lightMethod == 0)
            {
                img = light - img;
            }
            else if (lightMethod == 1)
            {
                img.ConvertTo(img, MatType.CV_32F);
                light.ConvertTo(light, MatType.CV_32F);
                img = (1 - (light / img)) * 255;
                img.ConvertTo(img, MatType.CV_8U);
            }

            //二值化图像
            if (lightMethod == 0 || lightMethod == 1)
            {
                img = img.Threshold(30, 255, ThresholdTypes.Binary);
            }
            else
            {
                img = img.Threshold(140, 255, ThresholdTypes.BinaryInv);
            }


            if (segmentMethod == 1)
            {
                // 1 connected component    2 connected components with statistic(统计)  3 find contour(轮廓线)
                //int nLabels = Cv2.ConnectedComponents(img, label, PixelConnectivity.Connectivity8, MatType.CV_32S);

                ConnectedComponents components = img.ConnectedComponentsEx();
                int       nLabels   = components.LabelCount;
                Point[][] points    = img.FindContoursAsArray(RetrievalModes.External, ContourApproximationModes.ApproxSimple);
                int       findCount = 0;
                for (int i = 0; i < points.Length; i++)
                {
                    if (points[i].Length > 100)
                    {
                        findCount++;
                    }
                }
                findCount--;
                Console.WriteLine(points.Length + "=find" + findCount);
                Console.WriteLine("number of objects = " + components.LabelCount);
                int count = 0;
                List <ConnectedComponents.Blob> list = new List <ConnectedComponents.Blob>();

                for (int i = 0; i < components.Blobs.Count; i++)
                {
                    if (i == 0)
                    {
                        continue;
                    }
                    ConnectedComponents.Blob blob = components.Blobs[i];
                    //实际区域大小
                    if (blob.Area > 2200 && blob.Width > 50 && blob.Height > 50)
                    {
                        //一瓶矿泉水  width = 227 height=171 area=15907
                        count++;
                        list.Add(blob);
                    }
                }


                list = list.OrderBy(r => r.Centroid.X).ToList();
                Console.WriteLine("实际个数是:" + count);
                Console.WriteLine("width=" + img.Width + ",height=" + img.Height);
                foreach (var blob in list)
                {
                    Console.WriteLine("area=" + blob.Area + ", (" + blob.Centroid.X + "," + blob.Centroid.Y + ")  width=" + blob.Width + ",height=" + blob.Height + "left=" + blob.Left);
                }

                Mat output = Mat.Zeros(img.Rows, img.Cols, MatType.CV_8UC3);

                for (int m = 1; m < nLabels; m++)
                {
                    //Mat mask = label.Equals(m);
                    //output.SetTo(Scalar.RandomColor(),mask);

                    Scalar scalar = Scalar.RandomColor();
                    Vec3b  vec3B  = scalar.ToVec3b();
                    for (int i = 0; i < img.Rows; i++)
                    {
                        for (int j = 0; j < img.Cols; j++)
                        {
                            int num = components.Labels[i, j];

                            if (num == m)
                            {
                                output.Set <Vec3b>(i, j, vec3B);
                            }
                        }
                    }
                }

                using (Window window = new Window("check"))
                {
                    window.ShowImage(output);
                    Cv2.WaitKey(0);
                }
            }


            using (Window window = new Window("check"))
            {
                window.ShowImage(cloneImg);
                Cv2.WaitKey(0);
            }

            //Mat src = Cv2.ImRead("./Images/check1.jpg", ImreadModes.GrayScale);

            //// Histogram view
            //const int Width = 260, Height = 200;
            //Mat render = new Mat(new Size(Width, Height), MatType.CV_8UC3, Scalar.All(255));

            //// Calculate histogram
            //Mat hist = new Mat();
            //int[] hdims = { 256 }; // Histogram size for each dimension
            //Rangef[] ranges = { new Rangef(0, 256), }; // min/max
            //Cv2.CalcHist(
            //    new Mat[] { src },
            //    new int[] { 0 },
            //    null,
            //    hist,
            //    1,
            //    hdims,
            //    ranges);

            //// Get the max value of histogram
            //double minVal, maxVal;
            //Cv2.MinMaxLoc(hist, out minVal, out maxVal);

            //Scalar color = Scalar.All(100);
            //// Scales and draws histogram
            //hist = hist * (maxVal != 0 ? Height / maxVal : 0.0);
            //for (int j = 0; j < hdims[0]; ++j)
            //{
            //    int binW = (int)((double)Width / hdims[0]);

            //    render.Rectangle(
            //        new Point(j * binW, render.Rows - (int)(hist.Get<float>(j))),
            //        new Point((j + 1) * binW, render.Rows),
            //        color);
            //}

            //using (new Window("Image", WindowMode.AutoSize | WindowMode.FreeRatio, src))
            //using (new Window("Histogram", WindowMode.AutoSize | WindowMode.FreeRatio, render))
            //{
            //    Cv2.WaitKey();
            //}

            //Mat mat = new Mat("./Images/check1.jpg",ImreadModes.GrayScale);

            //StringBuilder sb = new StringBuilder();
            //for (int i = 0; i < mat.Rows; i++)
            //{
            //    for (int j = 0; j < mat.Cols; j++)
            //    {
            //        double[] arr = mat.GetArray(i, j);
            //        sb.Append("(");
            //        for (int k = 0; k < arr.Length; k++)
            //        {
            //            sb.Append(arr[k] + ",");
            //        }
            //        sb.Append(")");

            //    }
            //    sb.AppendLine();
            //}

            //File.WriteAllText("1.txt",sb.ToString(),Encoding.UTF8);

            //using (Window window = new Window("Lena", WindowMode.Normal, mat))
            //{


            //    window.ShowImage(mat);

            //    Cv2.WaitKey(100000);
            //}


            //VideoCapture videoCapture = new VideoCapture(@"D:\BaiduYunDownload\希赛系统架构师视频\3 JG:第03章 系统开发基础.wmv");
            //Console.WriteLine(videoCapture.Fps+""+videoCapture.IsOpened());
            //int sleepTime = (int)Math.Round(1000/25.0);

            //using (Window window = new Window("capture"))
            //{
            //    using (Mat image = new Mat())
            //    {
            //        while (true)
            //        {
            //            videoCapture.Read(image);
            //            if (image.Empty())
            //            {
            //                break;
            //            }
            //            window.ShowImage(image);
            //            Cv2.WaitKey(sleepTime);
            //        }
            //    }
            //}
        }
Exemplo n.º 27
0
        public async Task PerformWithRetriesAsync(
            SemaphoreSlim semaphore,
            bool requireLease,
            string name,
            string intent,
            string data,
            string target,
            int expectedLatencyBound,
            bool isCritical,
            Func <int, Task <long> > operation)
        {
            try
            {
                if (semaphore != null)
                {
                    await semaphore.WaitAsync();
                }

                Stopwatch stopwatch   = new Stopwatch();
                int       numAttempts = 0;

                while (true) // retry loop
                {
                    numAttempts++;
                    try
                    {
                        if (requireLease)
                        {
                            await this.ConfirmLeaseIsGoodForAWhileAsync().ConfigureAwait(false);
                        }

                        this.StorageTracer?.FasterStorageProgress($"storage operation {name} started attempt {numAttempts}; target={target} {data}");

                        stopwatch.Restart();

                        long size = await operation(numAttempts).ConfigureAwait(false);

                        stopwatch.Stop();
                        this.StorageTracer?.FasterStorageProgress($"storage operation {name} ({intent}) succeeded on attempt {numAttempts}; target={target} latencyMs={stopwatch.Elapsed.TotalMilliseconds:F1} {data} ");

                        if (stopwatch.ElapsedMilliseconds > expectedLatencyBound)
                        {
                            this.TraceHelper.FasterPerfWarning($"storage operation {name} ({intent}) took {stopwatch.Elapsed.TotalSeconds:F1}s on attempt {numAttempts}, which is excessive; {data}");
                        }

                        this.TraceHelper.FasterAzureStorageAccessCompleted(intent, size, name, target, stopwatch.Elapsed.TotalMilliseconds, numAttempts);

                        return;
                    }
                    catch (StorageException e) when(BlobUtils.IsTransientStorageError(e, this.PartitionErrorHandler.Token) && numAttempts < BlobManager.MaxRetries)
                    {
                        stopwatch.Stop();
                        if (BlobUtils.IsTimeout(e))
                        {
                            this.TraceHelper.FasterPerfWarning($"storage operation {name} ({intent}) timed out on attempt {numAttempts} after {stopwatch.Elapsed.TotalSeconds:F1}s, retrying now; target={target} {data}");
                        }
                        else
                        {
                            TimeSpan nextRetryIn = BlobManager.GetDelayBetweenRetries(numAttempts);
                            this.HandleStorageError(name, $"storage operation {name} ({intent}) failed transiently on attempt {numAttempts}, retry in {nextRetryIn}s", target, e, false, true);
                            await Task.Delay(nextRetryIn);
                        }
                        continue;
                    }
                    catch (Exception exception) when(!Utils.IsFatal(exception))
                    {
                        this.HandleStorageError(name, $"storage operation {name} ({intent}) failed on attempt {numAttempts}", target, exception, isCritical, this.PartitionErrorHandler.IsTerminated);
                        throw;
                    }
                }
            }
            finally
            {
                if (semaphore != null)
                {
                    semaphore.Release();
                }
            }
        }