async Task DoUpscale(int index, ModelData mdl, bool fullImage) { if (PreviewUI.previewImg.Image == null) { Program.ShowMessage("Please load an image first!", "Error"); return; } Program.mainForm.SetBusy(true); Upscale.currentMode = Upscale.UpscaleMode.Composition; //await ImageProcessing.PreProcessImages(Paths.previewPath, !bool.Parse(Config.Get("alpha"))); //if (cutoutMode) //currentSourcePath += ".png"; string outImg = null; try { bool useNcnn = (Config.Get("cudaFallback").GetInt() == 2 || Config.Get("cudaFallback").GetInt() == 3); bool useCpu = (Config.Get("cudaFallback").GetInt() == 1); ESRGAN.Backend backend = ESRGAN.Backend.CUDA; if (useCpu) { backend = ESRGAN.Backend.CPU; } if (useNcnn) { backend = ESRGAN.Backend.NCNN; } string inpath = Paths.previewPath; if (fullImage) { inpath = Paths.tempImgPath.GetParentDir(); } await ESRGAN.DoUpscale(inpath, Paths.compositionOut, mdl, false, Config.GetBool("alpha"), ESRGAN.PreviewMode.None, backend); if (backend == ESRGAN.Backend.NCNN) { outImg = Directory.GetFiles(Paths.compositionOut, "*.png*", SearchOption.AllDirectories)[0]; } else { outImg = Directory.GetFiles(Paths.compositionOut, "*.tmp", SearchOption.AllDirectories)[0]; } await Upscale.PostprocessingSingle(outImg, false); await ProcessImage(PreviewUI.lastOutfile, mdl.model1Name); IOUtils.TryCopy(PreviewUI.lastOutfile, Path.Combine(Paths.imgOutPath, $"{index}-{mdl.model1Name}.png"), true); } catch (Exception e) { if (e.StackTrace.Contains("Index")) { Program.ShowMessage("The upscale process seems to have exited before completion!", "Error"); } Logger.ErrorMessage("An error occured during upscaling:", e); Program.mainForm.SetProgress(0f, "Cancelled."); } Program.mainForm.SetProgress(0, "Done."); Program.mainForm.SetBusy(false); }
/// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns> /// A 32-bit signed integer that is the hash code for this instance. /// </returns> public override int GetHashCode() { unchecked { var hashCode = Size.GetHashCode(); hashCode = (hashCode * 397) ^ MaxSize.GetHashCode(); hashCode = (hashCode * 397) ^ (RestrictedSizes?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (int)ResizeMode; hashCode = (hashCode * 397) ^ (int)AnchorPosition; hashCode = (hashCode * 397) ^ Upscale.GetHashCode(); hashCode = (hashCode * 397) ^ (CenterCoordinates?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ AnchorPoint.GetHashCode(); return(hashCode); } }
private async void runBtn_Click(object sender, EventArgs e) { if (PreviewUI.previewImg.Image == null || !File.Exists(Paths.tempImgPath)) { Program.ShowMessage("No image loaded!", "Error"); return; } Enabled = false; cutoutMode = cropMode.SelectedIndex == 1; if (cutoutMode) { IOUtils.ClearDir(Paths.previewPath); PreviewUI.SaveCurrentCutout(); currentSourcePath = Path.Combine(Paths.previewPath, "preview.png"); } else { currentSourcePath = Paths.tempImgPath; } string[] lines = Regex.Split(modelPathsBox.Text, "\r\n|\r|\n"); if (comparisonMode.SelectedIndex == 0) { string outpath = Path.Combine(Paths.imgOutPath, "!Original.png"); await ImageProcessing.ConvertImage(currentSourcePath, GetSaveFormat(), false, ImageProcessing.ExtMode.UseNew, false, outpath); await ProcessImage(outpath, "Original"); } for (int i = 0; i < lines.Length; i++) { if (!File.Exists(lines[i])) { continue; } ModelData mdl = new ModelData(lines[i], null, ModelData.ModelMode.Single); await DoUpscale(i, mdl, !cutoutMode); } bool vert = compositionMode.SelectedIndex == 1; MagickImage merged = ImgUtils.MergeImages(Directory.GetFiles(Paths.imgOutPath, "*.png", SearchOption.AllDirectories), vert, true); string mergedPath = Path.Combine(Paths.imgOutPath, Path.GetFileNameWithoutExtension(Program.lastImgPath) + "-composition"); mergedPath = Path.ChangeExtension(mergedPath, GetSaveExt()); merged.Write(mergedPath); await Upscale.CopyImagesTo(Program.lastImgPath.GetParentDir()); IOUtils.ClearDir(Paths.previewPath); Enabled = true; Program.ShowMessage("Saved model composition to " + Program.lastImgPath.GetParentDir() + "\\" + Path.GetFileName(mergedPath), "Message"); }
private async void saveMergedPreviewBtn_Click(object sender, EventArgs e) { DialogForm loadingForm = new DialogForm("Post-Processing And Saving..."); await Task.Delay(50); Upscale.currentMode = Upscale.UpscaleMode.Single; string ext = Path.GetExtension(Program.lastFilename); string outPath = Path.ChangeExtension(Program.lastFilename, null) + "[temp]" + ext + ".tmp"; previewImg.Image.Save(outPath); await Upscale.PostprocessingSingle(outPath, true); string outFilename = Upscale.FilenamePostprocess(MainUIHelper.lastOutfile); string finalPath = IOUtils.ReplaceInFilename(outFilename, "[temp]", ""); loadingForm.Close(); Program.ShowMessage("Saved to " + finalPath + ".", "Message"); }
static void CopyBack(string path) { if (!File.Exists(path)) { Print("No video file was created!"); return; } string filename = Path.GetFileNameWithoutExtension(currentInPath); string ext = Path.GetExtension(path); string outPath = ""; try { if (Upscale.overwriteMode == Upscale.Overwrite.No) { outPath = Path.Combine(outDir.Text.Trim(), filename + "-" + Upscale.GetLastModelName() + ext); } else { outPath = Path.Combine(outDir.Text.Trim(), Path.GetFileName(currentInPath)); } } catch (Exception e) { Logger.Log($"Path Combine Error: {e.Message} - Path.Combine(outDir.Text.Trim() = {outDir.Text.Trim()}, filename = {filename} + \"-\" + Program.lastModelName = {Program.lastModelName} + ext = {ext}"); } outPath = Path.ChangeExtension(outPath, outputFormat.ToString().ToLower()); Print("Moving output video to " + outPath + "..."); try { if (File.Exists(outPath)) { File.Delete(outPath); } File.Move(path, outPath); } catch (Exception e) { Logger.ErrorMessage("Failed to move video file to output folder.\nMake sure no other programs are accessing files in that folder.\n", e); } }
public static async Task Run(bool preprocess, bool postProcess = true, string overrideOutDir = "") { int cudaFallback = Config.Get("cudaFallback").GetInt(); bool useNcnn = (cudaFallback == 2 || cudaFallback == 3); bool useCpu = (cudaFallback == 1); string imgOutDir = outDir.Text.Trim(); if (!string.IsNullOrWhiteSpace(overrideOutDir)) { imgOutDir = overrideOutDir; } if (useNcnn && !Program.mainForm.HasValidNcnnModelSelection()) { Program.ShowMessage("Invalid model selection - NCNN does not support interpolation or chaining.", "Error"); return; } if (string.IsNullOrWhiteSpace(currentInDir) && (currentInFiles == null || currentInFiles.Length < 1)) { Program.ShowMessage("No directory or files loaded.", "Error"); return; } if (!IOUtils.HasEnoughDiskSpace(8192, imgOutDir.Substring(0, 2), 2.0f)) { Program.ShowMessage($"Not enough disk space on {IOUtils.GetAppDataDir().Substring(0, 3)} to store temporary files!", "Error"); return; } Upscale.currentMode = Upscale.UpscaleMode.Batch; Program.mainForm.SetBusy(true); Program.mainForm.SetProgress(2f, "Loading images..."); await Task.Delay(20); Directory.CreateDirectory(imgOutDir); await CopyCompatibleImagesToTemp(); Program.mainForm.SetProgress(3f, "Pre-Processing..."); if (preprocess) { await ImageProcessing.PreProcessImages(Paths.imgInPath, !bool.Parse(Config.Get("alpha"))); } else { IOUtils.AppendToFilenames(Paths.imgInPath, ".png"); } ModelData mdl = Upscale.GetModelData(); GetProgress(Paths.imgOutPath, IOUtils.GetAmountOfFiles(Paths.imgInPath, true)); if (postProcess) { PostProcessingQueue.Start(imgOutDir); } List <Task> tasks = new List <Task>(); ESRGAN.Backend backend = ESRGAN.Backend.CUDA; if (useCpu) { backend = ESRGAN.Backend.CPU; } if (useNcnn) { backend = ESRGAN.Backend.NCNN; } tasks.Add(ESRGAN.DoUpscale(Paths.imgInPath, Paths.imgOutPath, mdl, Config.Get("tilesize"), bool.Parse(Config.Get("alpha")), ESRGAN.PreviewMode.None, backend, false)); if (postProcess) { tasks.Add(PostProcessingQueue.Update()); tasks.Add(PostProcessingQueue.ProcessQueue()); } sw.Restart(); await Task.WhenAll(tasks); if (!Program.cancelled) { Program.mainForm.SetProgress(0, $"Done - Upscaling took {(sw.ElapsedMilliseconds / 1000f).ToString("0")}s"); } Program.mainForm.SetBusy(false); }
public static async Task UpscaleImage() { if (previewImg.Image == null) { Program.ShowMessage("Please load an image first!", "Error"); return; } Program.mainForm.SetBusy(true); IOUtils.ClearDir(Paths.imgInPath); IOUtils.ClearDir(Paths.imgOutPath); Program.mainForm.SetProgress(3f, "Preprocessing..."); string inImg = CopyImage(); if (inImg == null) // Try to copy/move image to input folder, return if failed { Cancel("I/O Error"); return; } Upscale.currentMode = Upscale.UpscaleMode.Single; await ImageProcessing.PreProcessImage(inImg, !Config.GetBool("alpha")); ModelData mdl = Upscale.GetModelData(); string outImg = null; sw.Restart(); try { bool useNcnn = (Config.Get("cudaFallback").GetInt() == 2 || Config.Get("cudaFallback").GetInt() == 3); bool useCpu = (Config.Get("cudaFallback").GetInt() == 1); ESRGAN.Backend backend = ESRGAN.Backend.CUDA; if (useCpu) { backend = ESRGAN.Backend.CPU; } if (useNcnn) { backend = ESRGAN.Backend.NCNN; } await ESRGAN.DoUpscale(Paths.imgInPath, Paths.imgOutPath, mdl, false, Config.GetBool("alpha"), ESRGAN.PreviewMode.None, backend); if (backend == ESRGAN.Backend.NCNN) { outImg = Directory.GetFiles(Paths.imgOutPath, "*.png*", SearchOption.AllDirectories)[0]; } else { outImg = Directory.GetFiles(Paths.imgOutPath, "*.tmp", SearchOption.AllDirectories)[0]; } Program.mainForm.SetProgress(100f, "Post-Processing..."); await Task.Delay(50); await Upscale.PostprocessingSingle(outImg, false); string outFilename = Upscale.FilenamePostprocess(lastOutfile); await Upscale.CopyImagesTo(Path.GetDirectoryName(Program.lastImgPath)); } catch (Exception e) { Program.mainForm.SetProgress(0f, "Cancelled."); if (Program.cancelled) { return; } if (e.StackTrace.Contains("Index")) { Program.ShowMessage("The upscale process seems to have exited before completion!", "Error"); } Logger.ErrorMessage("An error occured during upscaling:", e); } if (!Program.cancelled) { Program.mainForm.SetProgress(0, $"Done - Upscaling took {(sw.ElapsedMilliseconds / 1000f).ToString("0.0")}s"); } Program.mainForm.SetBusy(false); }
public static async Task ProcessQueue() { Stopwatch sw = new Stopwatch(); while (run || AnyFilesLeft()) { if (outputFileQueue.Count > 0) { string file = outputFileQueue.Dequeue(); Logger.Log("[Queue] Post-Processing " + Path.GetFileName(file)); sw.Restart(); await Upscale.PostprocessingSingle(file, false); while (IOUtils.IsFileLocked(lastOutfile)) { Logger.Log($"{file} appears to be locked - waiting 500ms..."); await Task.Delay(500); } string outFilename = Upscale.FilenamePostprocess(lastOutfile); outputFiles.Add(outFilename); Logger.Log("[Queue] Done Post-Processing " + Path.GetFileName(file) + " in " + sw.ElapsedMilliseconds + "ms"); try { if (Upscale.overwriteMode == Upscale.Overwrite.Yes) { string suffixToRemove = "-" + Program.lastModelName.Replace(":", ".").Replace(">>", "+"); if (copyMode == CopyMode.KeepStructure) { string combinedPath = currentOutPath + outFilename.Replace(Paths.imgOutPath, ""); Directory.CreateDirectory(combinedPath.GetParentDir()); File.Copy(outFilename, combinedPath.ReplaceInFilename(suffixToRemove, "", true), true); } if (copyMode == CopyMode.CopyToRoot) { File.Copy(outFilename, Path.Combine(currentOutPath, Path.GetFileName(outFilename).Replace(suffixToRemove, "")), true); } File.Delete(outFilename); } else { if (copyMode == CopyMode.KeepStructure) { string combinedPath = currentOutPath + outFilename.Replace(Paths.imgOutPath, ""); Directory.CreateDirectory(combinedPath.GetParentDir()); File.Copy(outFilename, combinedPath, true); } if (copyMode == CopyMode.CopyToRoot) { File.Copy(outFilename, Path.Combine(currentOutPath, Path.GetFileName(outFilename)), true); } File.Delete(outFilename); } } catch (Exception e) { Logger.Log("Error trying to copy post-processed file back: " + e.Message + "\n" + e.StackTrace); } BatchUpscaleUI.upscaledImages++; } await Task.Delay(200); } }