//public void CountWords() public void CountWords( System.ComponentModel.BackgroundWorker worker, System.ComponentModel.DoWorkEventArgs e) { var state = SearchInFile(); worker.ReportProgress(0, state); }
public void IndexFiles(FileInfo[] imageFiles, System.ComponentModel.BackgroundWorker IndexBgWorker, object argument = null) { List<RGBProjectionRecord> listOfRecords = new List<RGBProjectionRecord>(); RgbProjections projections = null; int totalFileCount = imageFiles.Length; for (int i = 0; i < totalFileCount; i++) { var fi = imageFiles[i]; using (Bitmap bitmap = ImageUtility.ResizeBitmap(new Bitmap(fi.FullName), 100, 100)) { projections = new RgbProjections(ImageUtility.GetRgbProjections(bitmap)); } RGBProjectionRecord record = new RGBProjectionRecord { Id = i, ImageName = fi.Name, ImagePath = fi.FullName, RGBProjection = projections }; listOfRecords.Add(record); IndexBgWorker.ReportProgress(i); } BinaryAlgoRepository<List<RGBProjectionRecord>> repo = new BinaryAlgoRepository<List<RGBProjectionRecord>>(); repo.Save(listOfRecords); }
public override Raster ProcessRaster(Raster rOriginal, System.ComponentModel.BackgroundWorker worker) { worker.WorkerReportsProgress = true; DateTime startTime = DateTime.Now; int width = rOriginal.Width; int height = rOriginal.Height; Raster raster; //stamping filter LinearFilter filter = Cip.Filters.LinearFilter.Stamping(); raster = filter.ProcessRaster(rOriginal, worker); //VectorHSI hsi; int intensity; byte g; //convert to gray image and increase lightness for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { intensity = Cip.Foundations.ColorspaceHelper.RGB2GRAYI(raster[i, j]); intensity += 128; g = VectorRgb.ClampByte(intensity); raster[i, j] = new VectorRgb(g, g, g); } worker.ReportProgress((int)(100f * j / height), DateTime.Now - startTime); } return raster; }
private FullSpriteSet( IList<AbstractSprite> sprites, System.ComponentModel.BackgroundWorker worker, int tasksComplete, int tasks ) { bool haveWorker = worker != null; if ( haveWorker ) worker.ReportProgress( ( tasksComplete++ * 100 ) / tasks, "Sorting" ); sprites.Sort( ( a, b ) => a.Name.CompareTo( b.Name ) ); this.sprites = sprites; Thumbnails = new ImageList(); Thumbnails.ImageSize = new System.Drawing.Size( 80, 48 ); foreach ( var sprite in sprites ) { if ( haveWorker ) worker.ReportProgress( ( tasksComplete++ * 100 ) / tasks, string.Format( "Generating thumbnail for {0}", sprite.Name ) ); Thumbnails.Images.Add( sprite.Name, sprite.GetThumbnail() ); } }
private FullSpriteSet( IList<AbstractSprite> sprites, System.ComponentModel.BackgroundWorker worker, int tasksComplete, int tasks ) { bool haveWorker = worker != null; if ( haveWorker ) worker.ReportProgress( ( tasksComplete++ * 100 ) / tasks, "Sorting" ); sprites.Sort( ( a, b ) => a.Name.CompareTo( b.Name ) ); this.sprites = sprites; }
public void parallelPingServers(System.ComponentModel.BackgroundWorker worker, System.ComponentModel.DoWorkEventArgs e, int[] speeds, ARSMonitor.serverControl server ) { Ping pingSender = new Ping(); PingOptions options = new PingOptions(); options.DontFragment = true; string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; // сделать размер буфера изменяемым в настройках CurrentState state = new CurrentState(); byte[] buffer = Encoding.ASCII.GetBytes(data); // сделать изменяемым в настройках int timeout = 120; // сделать изменяемым в настройках double count = serverList.Count; double i = 0; int progress; i++; progress = (int)Math.Round((i / count) * 100); //elements.Find(el => el.Child == server); string host = server.objectAddress; // сделать изменяемым в настройках while (!worker.CancellationPending) { PingReply reply = pingSender.Send(host, timeout, buffer, options); if (reply.Status == IPStatus.Success) { state.address = server.objectAddress; state.isOnline = true; /*while (worker.IsBusy) System.Threading.Thread.Sleep(100);*/ worker.ReportProgress(progress, state); } else { state.address = server.objectAddress; state.isOnline = false; worker.ReportProgress(progress, state); } if (!workState) System.Threading.Thread.Sleep(1000); System.Threading.Thread.Sleep(speeds[1]); } e.Cancel = true; }
public void CountWords( System.ComponentModel.BackgroundWorker worker, System.ComponentModel.DoWorkEventArgs e) { CurrentState state = new CurrentState(); string line = ""; int elapsedTime = 20; DateTime lastReportDateTime = DateTime.Now; if (CompareString == null || CompareString == string.Empty) { throw new Exception("CompareString not specified."); } try { using (System.IO.StreamReader stream = new System.IO.StreamReader(SourceFile)) { while (!stream.EndOfStream) { if (worker.CancellationPending) { e.Cancel = true; break; } else { line = stream.ReadLine(); WordCount += CountInString(line, CompareString); LinesCounted += 1; int compare = DateTime.Compare( DateTime.Now, lastReportDateTime.AddMilliseconds(elapsedTime)); if (compare > 0) { state.LinesCounted = LinesCounted; state.WordsMatched = WordCount; worker.ReportProgress(0, state); lastReportDateTime = DateTime.Now; } } } state.LinesCounted = LinesCounted; state.WordsMatched = WordCount; worker.ReportProgress(0, state); } } catch (Exception exc) { throw exc; } }
public static void GetDiffs(List<string> filePaths, System.ComponentModel.BackgroundWorker worker, out TagDiffs diffs, out FileErrors errors) { diffs = new TagDiffs(); errors = new FileErrors(); int index = 0; int total = filePaths.Count(); foreach (var filePath in filePaths) { if (worker.CancellationPending) return; index += 1; worker.ReportProgress(index*100/total, filePath); AddDiffs(diffs, errors, filePath); } }
public static void Analyze(System.ComponentModel.BackgroundWorker worker) { int i = 0; foreach (string file in Directory.GetFiles("C:\\Users\\Forpatril\\Documents\\Visual Studio 2010\\Projects\\Diploma_cs\\Images", "*.jpg")) { Image img = new Image(file); for (int w = 2; w < 35; w++) for (int sig = 1; sig < w / 2; sig++) { filterclass fc = new filterclass(); Noise n = new Noise(); Image img_n = n.addNoise("gaussian", img, 0, 0.055); double[] p = new double[] {w, sig, 0.2}; MWNumericArray parameters = new MWNumericArray(p); MWLogicalArray mw_print = new MWLogicalArray(Form1.print); MWArray[] Result = fc.filter2(2, img_n.image, "bilateral", parameters, mw_print); MWNumericArray descriptor = null; descriptor = (MWNumericArray)Result[0]; double[,] result = null; result = (double[,])descriptor.ToArray(MWArrayComponent.Real); Image ret = new Image(result); MWNumericArray e_descriptor = null; e_descriptor = (MWNumericArray)Result[1]; ret.Time = (double)e_descriptor.ToScalarDouble(); filterDataContext db = new filterDataContext(); psnrClass ps = new psnrClass(); double psnr = (double)((MWNumericArray)ps.psnr(ret.image, img.image)).ToScalarDouble(); db.add_line("bilateral", "gaussian", img.Height, img.Width, ret.Time, psnr, p[0], p[1], p[2]); Result = null; e_descriptor = null; result = null; parameters = null; img_n = null; n = null; descriptor = null; ret = null; ps = null; fc = null; GC.Collect(); } worker.ReportProgress(i++); img = null; GC.Collect(); } }
public static void Fill(string path, int id, System.ComponentModel.BackgroundWorker worker) { int i = 0; foreach (string file in Directory.GetFiles(path, "*.jpg")) { filterDataContext db = new filterDataContext(); Image img = new Image(file); Noise n = new Noise(); img = n.addNoise("gaussian", img, 0, 0.055); RunFilter rf = new RunFilter(); Image ret = rf.Do(img, id); psnrClass ps = new psnrClass(); double psnr = (double)((MWNumericArray)ps.psnr(ret.image, img.image)).ToScalarDouble(); db.add_line(Filters.type[id],"gaussian",img.Height,img.Width,ret.Time,psnr,Form1.pars.par[id][0],Form1.pars.par[id][1],Form1.pars.par[id][2]); worker.ReportProgress(i++); } }
public static void ReceiveMails(System.ComponentModel.BackgroundWorker backgroundWorker) { string pop, port, mailname, mailpassword, keyword; try { BLL.SettingBLL bll = new BLL.SettingBLL(); Dictionary<string, string> dic = bll.GetMailSet(); pop = dic["POP"]; port = dic["Port"]; mailname = dic["Mail"]; mailpassword = dic["MailPwd"]; keyword = dic["Keyword"]; if (pop3Client.Connected) pop3Client.Disconnect(); pop3Client.Connect(pop, int.Parse(port), true); pop3Client.Authenticate(mailname, mailpassword); int count = pop3Client.GetMessageCount(); for (int i = 1; i <= count; i++) { backgroundWorker.ReportProgress((int)(((double)i / count) * 100)); /* * 1.接收邮件,筛选出带有关键字开头的邮件 * 2.将邮件格式转成xaml便于读取 * 3.判断邮件时间,如果当天邮件则进行合并和显示操作;如果是以前的时间,就进行合并和保存操作 * 4.删除已读取的邮件 */ Message message = pop3Client.GetMessage(i); if (message.Headers.Subject.StartsWith(keyword)) { SaveMail(i, message); pop3Client.DeleteMessage(i); continue; } } } catch { return; } //提交删除的更改信息 TryMail(pop, port, mailname, mailpassword); }
/// <summary> /// Gets the columns to be displayed from Bugzilla - colchange.cgi /// /// </summary> /// <param name="BugzillaUrl">Url of the bugzilla system</param> /// <returns>Hashtable (key is column name, value is the index in the array of columns)</returns> public Hashtable GenerateColumnsToBeDisplayed( System.ComponentModel.BackgroundWorker backgroundWorker ) { TDSettings.ConnectionRow connection = MyZillaSettingsDataSet.GetInstance().GetConnectionById(_connectionId); HttpHelper httpRequest = new HttpHelper(_connectionId, connection.Charset); //GET HTML content for the page provided string htmlContent = httpRequest.GetFromUrl(String.Concat(connection.URL, DISPLAYED_COLUMNS_PAGE), false); ParseHtmlForColumnListValues(htmlContent); if (backgroundWorker != null) { backgroundWorker.ReportProgress(100); } return cols ; }
public override Raster ProcessRaster(Raster rOriginal, System.ComponentModel.BackgroundWorker worker) { worker.WorkerReportsProgress = true; byte r, g, b, rr, gg, bb; VectorRgb c; int width = rOriginal.Width; int height = rOriginal.Height; Raster raster = new Raster(width, height, Color.Black); DateTime startTime = DateTime.Now; //processing for (int i = 0; i < width; i++) { //moving by columns for (int j = 0; j < height; j++) { r = g = b = 0; rr = gg = bb = 255; for (int k = i - (n - 1) / 2; k <= i + (n - 1) / 2; k++) { for (int l = j - (n - 1) / 2; l <= j + (n - 1) / 2; l++) { if (k >= 0 && k < width && l < height && l >= 0) { c = rOriginal[k, l]; if (c.R > r) r = c.R; if (c.G > g) g = c.G; if (c.B > b) b = c.B; if (c.R < rr) rr = c.R; if (c.G < gg) gg = c.G; if (c.B < bb) bb = c.B; } } } raster[i, j].R = (byte)(255 - Math.Abs(r - rr)); raster[i, j].G = (byte)(255 - Math.Abs(g - gg)); raster[i, j].B = (byte)(255 - Math.Abs(b - bb)); } worker.ReportProgress((int)(100f * i / width), DateTime.Now - startTime); } return raster; }
public static void WriteDiffs(OrderedDiffs diffs, System.ComponentModel.BackgroundWorker worker, out FileErrors errors) { errors = new FileErrors(); int total = diffs.Count(); int index = 0; foreach (var filePath in diffs.Keys) { if (worker.CancellationPending) return; index += 1; worker.ReportProgress(index * 100 / total, filePath); try { WriteDiff(filePath, diffs[filePath]); } catch (Exception ex) { errors.Add(new FileError { FilePath = filePath, Message = ex.Message }); } } }
public void IndexFilesAsync(FileInfo[] imageFiles, System.ComponentModel.BackgroundWorker IndexBgWorker, object argument = null) { ConcurrentBag<RGBProjectionRecord> listOfRecords = new ConcurrentBag<RGBProjectionRecord>(); RgbProjections projections = null; int totalFileCount = imageFiles.Length; int i = 0; long nextSequence; //In the class scope: Object lockMe = new Object(); Parallel.ForEach(imageFiles, currentImageFile => { var fi = currentImageFile; using (Bitmap bitmap = ImageUtility.ResizeBitmap(new Bitmap(fi.FullName), 100, 100)) { projections = new RgbProjections(ImageUtility.GetRgbProjections(bitmap)); } lock (lockMe) { nextSequence = i++; } RGBProjectionRecord record = new RGBProjectionRecord { Id = nextSequence, ImageName = fi.Name, ImagePath = fi.FullName, RGBProjection = projections }; listOfRecords.Add(record); IndexBgWorker.ReportProgress(i); }); BinaryAlgoRepository<List<RGBProjectionRecord>> repo = new BinaryAlgoRepository<List<RGBProjectionRecord>>(); repo.Save(listOfRecords.ToList()); }
public override WorkerResult Run(IDalSessionFactory factory, System.ComponentModel.BackgroundWorker worker, System.ComponentModel.DoWorkEventArgs e) { try { IDalSession session = factory.CreateSession(); DateTime startDate = DateTime.Now; if (LoadExRates(session)) { string result = "The exchangerates were imported successfully"; e.Result = new WorkerResult(WorkerResult.STATE_NORMAL, WorkerResultStatus.Ok, result); } } catch (Exception ex) { e.Result = new WorkerResult(WorkerResult.STATE_EXCEPTION, WorkerResultStatus.Exception, "An error occured during the retrieval of the exchangerates", "", ex); } finally { worker.ReportProgress(100); } return (WorkerResult)e.Result; }
private string sendRequest(string req_xml, System.ComponentModel.BackgroundWorker bw) { int counter = 0; string ret = "Unknown Error"; XmlDocument soap_env = new XmlDocument(); soap_env.LoadXml(req_xml); request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); request.Headers.Add("SOAPAction", soap_action); request.ContentType = "text/xml;charset=\"utf-8\""; request.Method = "POST"; request.CookieContainer = cookie; request.KeepAlive = false; //true request.UserAgent = "Small Craft C#"; // Ignore SSL Error if using https System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate( Object obj, X509Certificate certificate, X509Chain chain, System.Net.Security.SslPolicyErrors errors) { return (true); }; Stream stream = request.GetRequestStream(); soap_env.Save(stream); try { string buf = ""; System.Net.WebResponse response = request.GetResponse(); Stream s = response.GetResponseStream(); StreamReader sr = new StreamReader(s); while (!sr.EndOfStream) { buf += sr.ReadLine(); counter++; if (reportProgress) { bw.ReportProgress(counter); } } ret = buf; } catch (System.Net.WebException webExc) { ret = webExc.ToString(); } return ret; }
private void SearchNext(System.ComponentModel.BackgroundWorker bw) { while (elements.Count > 0) { if (bw.CancellationPending) { elements.Clear(); return; } YouTubeElement elem = elements.First(); elem.Load(); bw.ReportProgress(0, (object)elem); elements.RemoveAt(0); } }
//public void CountWords() public void CountWords( System.ComponentModel.BackgroundWorker worker, System.ComponentModel.DoWorkEventArgs e) { // Initialize the variables. CurrentState state = new CurrentState(); string line = ""; int elapsedTime = 20; DateTime lastReportDateTime = DateTime.Now; if (CompareString == null || CompareString == System.String.Empty) { throw new Exception("CompareString not specified."); } using (FileStream fs = File.OpenRead(SourceFile)) { byte[] b = new byte[32768]; //5sec //byte[] b = new byte[131072]; //5sec //byte[] b = new byte[65536]; //5sec UTF8Encoding temp = new UTF8Encoding(true); int length = (int)fs.Length; // get file length //b = new byte[length]; // create buffer int count = 0; // actual number of bytes read int sum = 0; // total number of bytes read //Read File upper //int max = (int)(fs.Length / 2); //Get to the top fs.Seek(0, SeekOrigin.Begin); while (fs.Read(b, sum, b.Length) > 0) { //sum += count; //if (worker.CancellationPending) //{ // e.Cancel = true; // break; //} //else //{ line = temp.GetString(b); WordCount += StringHelper.Instance.CountInString(line, CompareString); LinesCounted += 1; // Raise an event so the form can monitor progress. int compare = DateTime.Compare(DateTime.Now, lastReportDateTime.AddMilliseconds(elapsedTime)); if (compare > 0) { state.LinesCounted = LinesCounted; state.WordsMatched = WordCount; //worker.ReportProgress(0, state); lastReportDateTime = DateTime.Now; } //} // Uncomment for testing. //System.Threading.Thread.Sleep(5); } } // Report the final count values. state.LinesCounted = LinesCounted; state.WordsMatched = WordCount; worker.ReportProgress(0, state); }
/// <summary> /// Processing resample. /// </summary> public override Raster ProcessRaster(Raster rOriginal, System.ComponentModel.BackgroundWorker worker) { worker.WorkerReportsProgress = true; DateTime startTime = DateTime.Now; if (newx == 0 || newy == 0) return null; if (rOriginal.Width == newx && rOriginal.Height == newy) return new Raster(rOriginal);//copy float xScale, yScale, fX, fY; xScale = (float)rOriginal.Width / (float)newx; yScale = (float)rOriginal.Height / (float)newy; Raster newImage = new Raster(newx, newy); switch (this.mode) { #region nearest pixel case Cip.Transformations.CipInterpolationMode.NearestPixel: { // nearest pixel for (int y = 0; y < newy; y++) { fY = y * yScale; for (int x = 0; x < newx; x++) { fX = x * xScale; newImage[x, y] = rOriginal[(int)fX, (int)fY]; } worker.ReportProgress((int)(100f * y / newy), DateTime.Now - startTime); } break; } #endregion nearest pixel #region bicubic interpolation case Cip.Transformations.CipInterpolationMode.BicubicSpline: { // bicubic interpolation by Blake L. Carlson <blake-carlson(at)uiowa(dot)edu float f_x, f_y, a, b, r1, r2; byte rr, gg, bb; int i_x, i_y, xx, yy; VectorRgb rgb; for (int y = 0; y < newy; y++) { f_y = (float)y * yScale - 0.5f; i_y = (int) Math.Floor(f_y); a = f_y - (float)Math.Floor(f_y); for (int x = 0; x < newx; x++) { f_x = (float)x * xScale - 0.5f; i_x = (int)Math.Floor(f_x); b = f_x - (float)Math.Floor(f_x); rr = gg = bb = 0; for (int m = -1; m < 3; m++) { r1 = CipInterpolationFunctions.KernelBSpline((float)m - a); yy = i_y + m; if (yy < 0) yy = 0; if (yy >= rOriginal.Height) yy = rOriginal.Height - 1; for (int n = -1; n < 3; n++) { r2 = r1 * CipInterpolationFunctions.KernelBSpline(b - (float)n); xx = i_x + n; if (xx < 0) xx = 0; if (xx >= rOriginal.Width) xx = rOriginal.Width - 1; rgb = rOriginal[xx, yy]; rr += (byte) (rgb.R * r2); gg += (byte) (rgb.G * r2); bb += (byte) (rgb.B * r2); }//end for n }//end for m newImage[x, y] = new VectorRgb(rr, gg, bb); }//end for x worker.ReportProgress((int)(100f * y / newy), DateTime.Now - startTime); }//end for y break; } #endregion bicubic interpolation #region bilinear interpolation case Cip.Transformations.CipInterpolationMode.Bilinear: { // bilinear interpolation double fraction_x, fraction_y, one_minus_x, one_minus_y; int ceil_x, ceil_y, floor_x, floor_y; VectorRgb c1 = new VectorRgb(); VectorRgb c2 = new VectorRgb(); VectorRgb c3 = new VectorRgb(); VectorRgb c4 = new VectorRgb(); byte red, green, blue; byte b1, b2; for (int x = 0; x < newx; ++x) { for (int y = 0; y < newy; ++y) { // Setup floor_x = (int)Math.Floor(x * xScale); floor_y = (int)Math.Floor(y * yScale); ceil_x = floor_x + 1; if (ceil_x >= rOriginal.Width) ceil_x = floor_x; ceil_y = floor_y + 1; if (ceil_y >= rOriginal.Height) ceil_y = floor_y; fraction_x = x * xScale - floor_x; fraction_y = y * yScale - floor_y; one_minus_x = 1.0f - fraction_x; one_minus_y = 1.0f - fraction_y; c1 = rOriginal[floor_x, floor_y]; c2 = rOriginal[ceil_x, floor_y]; c3 = rOriginal[floor_x, ceil_y]; c4 = rOriginal[ceil_x, ceil_y]; // Blue b1 = (byte)(one_minus_x * c1.B + fraction_x * c2.B); b2 = (byte)(one_minus_x * c3.B + fraction_x * c4.B); blue = (byte)(one_minus_y * (double)(b1) + fraction_y * (double)(b2)); // Green b1 = (byte)(one_minus_x * c1.G + fraction_x * c2.G); b2 = (byte)(one_minus_x * c3.G + fraction_x * c4.G); green = (byte)(one_minus_y * (double)(b1) + fraction_y * (double)(b2)); // Red b1 = (byte)(one_minus_x * c1.R + fraction_x * c2.R); b2 = (byte)(one_minus_x * c3.R + fraction_x * c4.R); red = (byte)(one_minus_y * (double)(b1) + fraction_y * (double)(b2)); newImage[x, y] = new VectorRgb(red, green, blue); } worker.ReportProgress((int)(100f * x / newx), DateTime.Now - startTime); } break; } #endregion bilinear interpolation default: { // nearest pixel for (int y = 0; y < newy; y++) { fY = y * yScale; for (int x = 0; x < newx; x++) { fX = x * xScale; newImage[x, y] = rOriginal[(int)fX, (int)fY]; } worker.ReportProgress((int)(100f * y / newy), DateTime.Now - startTime); } break; } }//end switch return newImage; }
public static FullSpriteSet FromShishiFile( string filename, System.ComponentModel.BackgroundWorker worker ) { Dictionary<string, Dictionary<string, List<string>>> manifest; List<AbstractSprite> sprites = new List<AbstractSprite>(); int tasks = 0; int tasksComplete = 0; using ( ZipFile zf = new ZipFile( filename ) ) { BinaryFormatter f = new BinaryFormatter(); manifest = f.Deserialize( zf.GetInputStream( zf.GetEntry( "manifest" ) ) ) as Dictionary<string, Dictionary<string, List<string>>>; foreach ( KeyValuePair<string, Dictionary<string, List<string>>> kvp in manifest ) { tasks += kvp.Value.Keys.Count * 3; } tasks += 1; foreach( string type in manifest.Keys ) { Type spriteType = Type.GetType( type ); ConstructorInfo constructor = spriteType.GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof( SerializedSprite ) }, null ); foreach( string name in manifest[type].Keys ) { List<string> filenames = manifest[type][name]; int size = filenames.Count; byte[][] bytes = new byte[size][]; worker.ReportProgress( ( tasksComplete++ * 100 ) / tasks, string.Format( "Extracting {0}", name ) ); ZipEntry entry = zf.GetEntry( string.Format( System.Globalization.CultureInfo.InvariantCulture, "{0}/{1}/Pixels", type, name ) ); byte[] pixels = new byte[entry.Size]; StreamUtils.ReadFully( zf.GetInputStream( entry ), pixels ); entry = zf.GetEntry( string.Format( System.Globalization.CultureInfo.InvariantCulture, "{0}/{1}/Palettes", type, name ) ); byte[] palettes = new byte[entry.Size]; StreamUtils.ReadFully( zf.GetInputStream( entry ), palettes ); entry = zf.GetEntry( string.Format( System.Globalization.CultureInfo.InvariantCulture, "{0}/{1}/Size", type, name ) ); byte[] sizeBytes = new byte[entry.Size]; StreamUtils.ReadFully( zf.GetInputStream( entry ), sizeBytes ); int origSize = Int32.Parse( new string( Encoding.UTF8.GetChars( sizeBytes ) ), System.Globalization.CultureInfo.InvariantCulture ); worker.ReportProgress( ( tasksComplete++ * 100 ) / tasks, string.Format( "Building {0}", name ) ); sprites.Add( constructor.Invoke( new object[] { new SerializedSprite( name, origSize, filenames, pixels, palettes ) } ) as AbstractSprite ); } } } return new FullSpriteSet( sprites, worker, tasksComplete, tasks ); }
public void IndexFiles(FileInfo[] imageFiles, System.ComponentModel.BackgroundWorker IndexBgWorker, Action<string> logWriter, SurfSettings surfSetting = null) { #region Surf Dectator Region double hessianThresh = 500; double uniquenessThreshold = 0.8; if (surfSetting != null) { hessianThresh = surfSetting.HessianThresh.Value; uniquenessThreshold = surfSetting.UniquenessThreshold.Value; } SURFDetector surfDectector = new SURFDetector(hessianThresh, false); #endregion int rows = 0; Matrix<float> superMatrix = null; List<SURFRecord1> observerSurfImageIndexList = new List<SURFRecord1>(); Stopwatch sw1, sw2; sw1 = Stopwatch.StartNew(); logWriter("Index started..."); int totalFileCount = imageFiles.Length; for (int i = 0; i < totalFileCount; i++) { var fi = imageFiles[i]; using (Image<Gray, byte> observerImage = new Image<Gray, byte>(fi.FullName)) { VectorOfKeyPoint observerKeyPoints = new VectorOfKeyPoint(); Matrix<float> observerDescriptor = surfDectector.DetectAndCompute(observerImage, null, observerKeyPoints); if (observerDescriptor.Rows > 4) { int initRow = rows; int endRows = rows + observerDescriptor.Rows - 1; SURFRecord1 record = new SURFRecord1 { Id = i, ImageName = fi.Name, ImagePath = fi.FullName, IndexStart = rows, IndexEnd = endRows }; observerSurfImageIndexList.Add(record); if (superMatrix == null) superMatrix = observerDescriptor; else superMatrix = superMatrix.ConcateVertical(observerDescriptor); rows = endRows + 1; } else { Debug.WriteLine(fi.Name + " skip from index, because it didn't have significant feature"); } } IndexBgWorker.ReportProgress(i); } sw1.Stop(); logWriter(string.Format("Index Complete, it tooked {0} ms. Saving Repository...", sw1.ElapsedMilliseconds)); SurfDataSet surfDataset = new SurfDataSet { SurfImageIndexRecord = observerSurfImageIndexList, SuperMatrix = superMatrix }; sw2 = Stopwatch.StartNew(); SurfRepository.AddSuperMatrixList(surfDataset); SurfRepository.SaveRepository(SurfAlgo.Flaan); sw2.Stop(); logWriter(string.Format("Index tooked {0} ms. Saving Repository tooked {1} ms", sw1.ElapsedMilliseconds, sw2.ElapsedMilliseconds)); }
public override bool PrepareStippling(double spacing, System.ComponentModel.BackgroundWorker worker) { if (stipplingData.settings.SourceFile.Length == 0 || !File.Exists(stipplingData.settings.SourceFile)) { return false; } Bitmap source = new Bitmap(stipplingData.settings.SourceFile); numClasses = stipplingData.colorBasis.Length; double[] rDiag = new double[numClasses]; resizedSource = new Bitmap((int)((float)Math.Max(1, source.Width * stipplingData.settings.ImageResizingFactor)), (int)((float)Math.Max(1, source.Height * stipplingData.settings.ImageResizingFactor))); { Graphics g = Graphics.FromImage(resizedSource); g.DrawImage(source, new Rectangle(0, 0, resizedSource.Width, resizedSource.Height)); } imageWidth = resizedSource.Width; imageHeight = resizedSource.Height; r = new double[imageWidth, imageHeight]; double pixelSize = 1.0 / imageWidth; for (int y = 0; y < imageHeight; ++y) { if (worker.WorkerSupportsCancellation && worker.CancellationPending) return false; if (worker.WorkerReportsProgress) worker.ReportProgress((int)((float)y / imageHeight * 100), "Building conflict check matrix"); for (int x = 0; x < imageWidth; ++x) { Color col = resizedSource.GetPixel(x, y); double component; if (stipplingData.additiveBlending) { double dR = (double)col.R / 255; double dG = (double)col.G / 255; double dB = (double)col.B / 255; component = 1.0 / Math.Max(0.0001, Math.Sqrt(dR * dR + dG * dG + dB * dB)); } else { double dR = (double)col.R / 255; double dG = (double)col.G / 255; double dB = (double)col.B / 255; double dist = Math.Sqrt(dR * dR + dG * dG + dB * dB); component = 1.0 / Math.Max(0.0001, Math.Sqrt(3) - dist); } r[x, y] = component * pixelSize * spacing; } } return true; }
public override void StartStippling(System.ComponentModel.BackgroundWorker worker) { InitSampleHash(); Random rnd = new Random(); if (r == null || imageWidth == 0 || imageHeight == 0) PrepareStippling(stipplingData.settings.Spacing, worker); // int numSamples = stipplingData.samples.Count; // in case we're resuming stippling do { // pick next sample class int numAttempts = 0; Sample_t s; do { if (worker.WorkerSupportsCancellation && worker.CancellationPending) return; if (cropRegion.HasValue) { double w = rnd.NextDouble() * cropRegion.Value.Width + cropRegion.Value.X; double h = rnd.NextDouble() * cropRegion.Value.Height + cropRegion.Value.Y; s.x = w; s.y = h; } else { double cellX = (double)rnd.Next(0, HashCells) / HashCells; double cellY = (double)rnd.Next(0, HashCells) / HashCells; double w = rnd.NextDouble() / HashCells; double h = rnd.NextDouble() / HashCells; s.x = cellX + w; s.y = cellY + h; } int sx = (int)(s.x * OutputImageWidth); int sy = (int)(s.y * OutputImageHeight); s.c = PickSampleColor(sx, sy, rnd); numAttempts++; } while (numAttempts < stipplingData.settings.Retries && !AcceptSample(s)); if (numAttempts < stipplingData.settings.Retries) { AddSample(s); } // otherwise the sample is considered lost if (worker != null && worker.WorkerReportsProgress && numSamples % stipplingData.settings.UpdateFrequency == 0) { worker.ReportProgress((int)(100 * (float)numSamples / stipplingData.settings.TotalSamples), String.Format("Stippling... {0} samples placed", stipplingData.samples.Count)); } } while (numSamples++ < stipplingData.settings.TotalSamples); }
public static void TransferTableToMongo(string tableName, string databaseName, string collectionName, System.ComponentModel.BackgroundWorker backgroundWorker) { SqlCommand cmd = new SqlCommand(); cmd.CommandText = "Select * from " + tableName; cmd.CommandType = CommandType.Text; YellowstonePathology.Business.Mongo.Server server = new Business.Mongo.TestServer(databaseName); MongoCollection mongoCollection = server.Database.GetCollection<BsonDocument>(collectionName); using (SqlConnection cn = new SqlConnection(YellowstonePathology.Business.Properties.Settings.Default.CurrentConnectionString)) { cn.Open(); cmd.Connection = cn; int transferredRowCount = 1; using (SqlDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { BsonDocument bsonDocument = YellowstonePathology.Business.Mongo.BSONDRBuilder.Build(dr); mongoCollection.Insert(bsonDocument); if (transferredRowCount > 100 && transferredRowCount % 1000 == 0) { backgroundWorker.ReportProgress(0, "Transfering " + tableName + ", " + transferredRowCount.ToString() + " rows transferred."); } transferredRowCount += 1; } } } }
/// <summary> /// Function that apply bloom filter to raster. /// </summary> /// <param name="rOriginal">Original raster.</param> /// <param name="worker">Background worker.</param> /// <returns>Modifyed raster.</returns> public override Raster ProcessRaster(Raster rOriginal, System.ComponentModel.BackgroundWorker worker) { worker.WorkerReportsProgress = true; int width = rOriginal.Width; int height = rOriginal.Height; Raster raster = new Raster(width, height); DateTime startTime = DateTime.Now; byte threshold = (byte)(this.lightThreshold * 255); VectorRgb color; //bright pass for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { color = rOriginal[i, j]; if (color.R > threshold || color.G > threshold || color.B > threshold) raster[i, j] = color; else raster[i, j] = new VectorRgb(0, 0, 0); } worker.ReportProgress((int)(100f * i / width), DateTime.Now - startTime); } //blur SmoothingFilter filterSmoothing = new SmoothingFilter(ColorSpaceMode.RGB, this.blurRadius); raster = filterSmoothing.ProcessRaster(raster, worker); //processing (mixing original raster with blured light raster) for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { color = raster[i, j] * this.bloomBlendFactor; raster[i, j] = rOriginal[i, j] + color; } worker.ReportProgress((int)(100f * i / width), DateTime.Now - startTime); } return raster; }
public override Raster ProcessRaster(Raster rOriginal, System.ComponentModel.BackgroundWorker worker) { worker.WorkerReportsProgress = true; int width = rOriginal.Width; int height = rOriginal.Height; Raster raster = new Raster(width, height); DateTime startTime = DateTime.Now; //processing for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) raster[i, j] = sepiacolor * VectorRgb.Dot(rOriginal[i, j], luminance); worker.ReportProgress((int)(100f * i / width), DateTime.Now - startTime); } return raster; }
public virtual Set<KeyValuePair<string, byte>> GetPreferredDTEPairs( Set<string> replacements, Set<KeyValuePair<string, byte>> currentPairs, Stack<byte> dteBytes, System.ComponentModel.BackgroundWorker worker ) { // Clone the sections var secs = GetCopyOfSections(); IList<byte> bytes = GetSectionByteArrays( secs, SelectedTerminator, CharMap, CompressionAllowed ).Join(); Set<KeyValuePair<string, byte>> result = new Set<KeyValuePair<string, byte>>(); // Determine if we even need to do DTE at all int bytesNeeded = bytes.Count - (Layout.Size - DataStart); if (bytesNeeded <= 0) { return result; } // Take the pairs that were already used for other files and encode this file with them result.AddRange( currentPairs ); TextUtilities.DoDTEEncoding( secs, DteAllowed, PatcherLib.Utilities.Utilities.DictionaryFromKVPs( result ) ); bytes = GetSectionByteArrays( secs, SelectedTerminator, CharMap, CompressionAllowed ).Join(); // If enough bytes were saved with the existing pairs, no need to look further bytesNeeded = bytes.Count - (Layout.Size - DataStart); if (bytesNeeded <= 0) { return result; } string terminatorString = string.Format( "{{0x{0:X2}", selectedTerminator ) + "}"; // Otherwise, get all the strings that can be DTE encoded StringBuilder sb = new StringBuilder( Layout.Size ); for (int i = 0; i < secs.Count; i++) { if (DteAllowed[i]) { secs[i].ForEach( t => sb.Append( t ).Append( terminatorString ) ); } } // ... determine pair frequency var dict = TextUtilities.GetPairAndTripleCounts( sb.ToString(), replacements ); // Sort the list by count var l = new List<KeyValuePair<string, int>>( dict ); l.Sort( ( a, b ) => b.Value.CompareTo( a.Value ) ); // Go through each one, encode the file with it, and see if we're below the limit while (bytesNeeded > 0 && l.Count > 0 && dteBytes.Count > 0) { /* byte currentDteByte = dteBytes.Pop(); for (int j = 0; j < l.Count; j++) { var tempResult = new Set<KeyValuePair<string, byte>>( result ); tempResult.Add( new KeyValuePair<string, byte>( l[j].Key, currentDteByte ) ); var oldBytesNeeded = bytesNeeded; TextUtilities.DoDTEEncoding( secs, DteAllowed, PatcherLib.Utilities.Utilities.DictionaryFromKVPs( tempResult ) ); bytes = GetSectionByteArrays( secs, SelectedTerminator, CharMap, CompressionAllowed ).Join(); var newBytesNeeded = bytes.Count - (Layout.Size - DataStart); if (newBytesNeeded < oldBytesNeeded) { bytesNeeded = newBytesNeeded; result.Add( new KeyValuePair<string, byte>( l[j].Key, currentDteByte ) ); TextUtilities.DoDTEEncoding( secs, DteAllowed, PatcherLib.Utilities.Utilities.DictionaryFromKVPs( result ) ); //bytes = GetSectionByteArrays( secs, SelectedTerminator, CharMap, CompressionAllowed ).Join(); //bytesNeeded = bytes.Count - (Layout.Size - DataStart); if (newBytesNeeded > 0) { StringBuilder sb2 = new StringBuilder( Layout.Size ); for (int i = 0; i < secs.Count; i++) { if (DteAllowed[i]) { secs[i].ForEach( t => sb2.Append( t ).Append( terminatorString ) ); } } l = new List<KeyValuePair<string, int>>( TextUtilities.GetPairAndTripleCounts( sb2.ToString(), replacements ) ); l.Sort( ( a, b ) => b.Value.CompareTo( a.Value ) ); secs = GetCopyOfSections(); } break; } } */ result.Add( new KeyValuePair<string, byte>( l[0].Key, dteBytes.Pop() ) ); TextUtilities.DoDTEEncoding( secs, DteAllowed, PatcherLib.Utilities.Utilities.DictionaryFromKVPs( result ) ); bytes = GetSectionByteArrays( secs, SelectedTerminator, CharMap, CompressionAllowed ).Join(); bytesNeeded = bytes.Count - (Layout.Size - DataStart); if (bytesNeeded > 0) { if (worker != null) worker.ReportProgress(0, new ProgressForm.FileProgress { File = this, State = ProgressForm.TaskState.Starting, Task = ProgressForm.Task.CalculateDte, BytesLeft = bytesNeeded } ); StringBuilder sb2 = new StringBuilder( Layout.Size ); for (int i = 0; i < secs.Count; i++) { if (DteAllowed[i]) { secs[i].ForEach( t => sb2.Append( t ).Append( terminatorString ) ); } } l = new List<KeyValuePair<string, int>>( TextUtilities.GetPairAndTripleCounts( sb2.ToString(), replacements ) ); l.Sort( ( a, b ) => b.Value.CompareTo( a.Value ) ); secs = GetCopyOfSections(); } } // Ran out of available pairs and still don't have enough space --> error if (bytesNeeded > 0) { return null; } return result; }
private long Treatment(int nb, int max, System.ComponentModel.BackgroundWorker worker, DoWorkEventArgs e) { long result = 0; if (worker.CancellationPending) { e.Cancel = true; } else { int pourcent = (int)(((double)max - (double)nb) / (double)max * 100); worker.ReportProgress(pourcent); if (nb <= 1) { result = 1; } else { System.Threading.Thread.Sleep(100); result = Treatment(nb - 1, max, worker, e) + 1; } } return result; }
private void ReportProgress(System.ComponentModel.BackgroundWorker bgw, ref DoWorkEventArgs e, ref int i) { if (bgw.CancellationPending) { e.Cancel = true; return; } bgw.ReportProgress(i); i = (i + 10) % 100; }