公司業務上需要對圖片顯示優化。比如獲取到本地應用ICON,8K分辨率下有些logo顯示不清晰。
我們可以通過圖片超分,提高顯示質量。這裏整理下最優的圖片超分操作
這裏用到的是騰訊Real-Esrgan,經過驗證realesrgan-x4plus-anime對圖片優化情況最好。
圖片超分處理
1 /// <summary> 2 /// 轉化 3 /// </summary> 4 /// <param name="sourceImage">源圖片/圖片文件夾</param> 5 /// <param name="outputImage">輸出圖片/圖片文件夾</param> 6 public async Task ConvertAsync(string sourceImage, string outputImage) 7 { 8 //工作線程運行,避免UI卡住 9 await Task.Run(() => 10 { 11 string args = $"-n realesrgan-x4plus-anime -i \"{sourceImage}\" -o \"{outputImage}\""; 12 using var process = new Process(); 13 process.StartInfo.FileName = _esrganExePath; 14 process.StartInfo.Arguments = args; 15 16 process.StartInfo.UseShellExecute = false; 17 process.StartInfo.CreateNoWindow = true; 18 process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; 19 20 process.StartInfo.RedirectStandardOutput = true; 21 process.StartInfo.RedirectStandardError = true; 22 process.StartInfo.RedirectStandardInput = true; 23 process.StartInfo.StandardOutputEncoding = Encoding.UTF8; 24 process.StartInfo.StandardErrorEncoding = Encoding.UTF8; 25 process.EnableRaisingEvents = true; 26 process.Start(); 27 28 //開始異步讀取輸出 29 process.BeginOutputReadLine(); 30 //異步讀取錯誤 31 process.BeginErrorReadLine(); 32 //設置回調函數 33 process.OutputDataReceived += Process_OutputDataReceived; 34 process.ErrorDataReceived += OnErrorDataReceived; 35 //等待程序執行完退出進程 36 process.WaitForExit(); 37 }); 38 }
使用參數:
Usage: realesrgan-ncnn-vulkan.exe -i infile -o outfile [options]... -h show this help" -i input-path input image path (jpg/png/webp) or directory" -o output-path output image path (jpg/png/webp) or directory" -s scale upscale ratio (can be 2, 3, 4. default=4)" -t tile-size tile size (>=32/0=auto, default=0) can be 0,0,0 for multi-gpu" -m model-path folder path to the pre-trained models. default=models" -n model-name model name (default=realesr-animevideov3, can be realesr-animevideov3 | realesrgan-x4plus | realesrgan-x4plus-anime | realesrnet-x4plus)" -g gpu-id gpu device to use (default=auto) can be 0,1,2 for multi-gpu" -j load:proc:save thread count for load/proc/save (default=1:2:2) can be 1:2,2,2:2 for multi-gpu" -x enable tta mode" -f format output image format (jpg/png/webp, default=ext/png)" -v verbose output"
顯示超分進度
超分很耗時,一張244K的圖片超分後3.66M需要耗時143219ms。所以業務可能需要進度,下面是我整理的,直接複製就行:
1 private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e) 2 { 3 //超分完成 4 ProgressChanged?.Invoke(this, 100d); 5 } 6 7 private void OnErrorDataReceived(object sender, DataReceivedEventArgs e) 8 { 9 if (string.IsNullOrEmpty(e.Data)) 10 { 11 return; 12 } 13 //獲取超分進度值 14 var match = Regex.Match(e.Data, @"^[0-9.]+%$"); 15 if (match.Success) 16 { 17 var progress = Convert.ToDouble(e.Data.Trim('%')); 18 ProgressChanged?.Invoke(this, progress); 19 } 20 } 21 /// <summary> 22 /// 轉化進度(百分比 0-100) 23 /// </summary> 24 public event EventHandler<double> ProgressChanged;
超分工具資源文件,可以點擊下載,放在VS工程內設置內容編譯輸出。
參考列表: