Files

123 lines
5.1 KiB
PowerShell
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 用 Windows 自带的 OCR(Windows.Media.Ocr)识别一张图,输出 JSON。
# 参数:-Path 图片路径 -Out 结果 json 路径
# 为什么要走内存流:StorageFile.GetFileFromPathAsync 在非打包环境下常被拒绝访问,
# 用 InMemoryRandomAccessStream + DataWriter 读字节再解码,绕开文件权限。
param(
[Parameter(Mandatory = $true)][string]$Path,
[Parameter(Mandatory = $true)][string]$Out
)
$ErrorActionPreference = "Stop"
$ProgressPreference = "SilentlyContinue"
Add-Type -AssemblyName System.Runtime.WindowsRuntime
$asTaskGeneric = ([System.WindowsRuntimeSystemExtensions].GetMethods() | Where-Object {
$_.Name -eq "AsTask" -and
$_.GetParameters().Count -eq 1 -and
$_.GetParameters()[0].ParameterType.Name -eq "IAsyncOperation``1"
})[0]
function Await($op, $type) {
$task = $asTaskGeneric.MakeGenericMethod($type).Invoke($null, @($op))
$task.Wait(-1) | Out-Null
return $task.Result
}
function Fail($code, $msg) {
$o = [ordered]@{ ok = $false; error = [ordered]@{ code = $code; message = $msg }; lines = @() }
[System.IO.File]::WriteAllText($Out, ($o | ConvertTo-Json -Depth 6 -Compress), (New-Object System.Text.UTF8Encoding($false)))
exit 0
}
try {
$null = [Windows.Media.Ocr.OcrEngine, Windows.Foundation, ContentType = WindowsRuntime]
$null = [Windows.Graphics.Imaging.BitmapDecoder, Windows.Graphics.Imaging, ContentType = WindowsRuntime]
$null = [Windows.Storage.Streams.InMemoryRandomAccessStream, Windows.Storage.Streams, ContentType = WindowsRuntime]
$engine = [Windows.Media.Ocr.OcrEngine]::TryCreateFromUserProfileLanguages()
if ($null -eq $engine) {
$lang = New-Object Windows.Globalization.Language "zh-Hans-CN"
$engine = [Windows.Media.Ocr.OcrEngine]::TryCreateFromLanguage($lang)
}
if ($null -eq $engine) { Fail "NO_ENGINE" "这台机器没有可用的 OCR 语言包(装一个中文语言包即可)" }
$bytes = [System.IO.File]::ReadAllBytes($Path)
if ($bytes.Length -eq 0) { Fail "EMPTY_FILE" "图片是空的" }
# 小图先放大:微信转发/截图常把长边压到 400px 左右,OCR 直接认会变成乱码。
Add-Type -AssemblyName System.Drawing
$origW = 0; $origH = 0; $scale = 1.0
try {
$src = [System.Drawing.Image]::FromStream((New-Object System.IO.MemoryStream(, $bytes)))
$origW = $src.Width; $origH = $src.Height
$longSide = [Math]::Max($origW, $origH)
if ($longSide -gt 0 -and $longSide -lt 1000) {
$scale = [Math]::Min(3.0, 1000.0 / $longSide)
$nw = [int][Math]::Round($origW * $scale); $nh = [int][Math]::Round($origH * $scale)
$dst = New-Object System.Drawing.Bitmap($nw, $nh)
$g = [System.Drawing.Graphics]::FromImage($dst)
$g.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
$g.PixelOffsetMode = [System.Drawing.Drawing2D.PixelOffsetMode]::HighQuality
$g.DrawImage($src, 0, 0, $nw, $nh)
$g.Dispose()
$ms = New-Object System.IO.MemoryStream
$dst.Save($ms, [System.Drawing.Imaging.ImageFormat]::Jpeg)
$bytes = $ms.ToArray()
$ms.Dispose(); $dst.Dispose()
}
$src.Dispose()
} catch {
$scale = 1.0 # 缩放失败就用原图,别因为预处理把整件事搞挂
}
$stream = New-Object Windows.Storage.Streams.InMemoryRandomAccessStream
$writer = New-Object Windows.Storage.Streams.DataWriter($stream)
$writer.WriteBytes($bytes)
$null = Await ($writer.StoreAsync()) ([uint32])
$null = Await ($writer.FlushAsync()) ([bool])
$writer.DetachStream() | Out-Null
$stream.Seek(0) | Out-Null
$decoder = Await ([Windows.Graphics.Imaging.BitmapDecoder]::CreateAsync($stream)) ([Windows.Graphics.Imaging.BitmapDecoder])
$bitmap = Await ($decoder.GetSoftwareBitmapAsync()) ([Windows.Graphics.Imaging.SoftwareBitmap])
$result = Await ($engine.RecognizeAsync($bitmap)) ([Windows.Media.Ocr.OcrResult])
$lines = New-Object System.Collections.ArrayList
foreach ($line in $result.Lines) {
$minX = [double]::MaxValue; $minY = [double]::MaxValue; $maxX = 0.0; $maxY = 0.0
foreach ($w in $line.Words) {
$r = $w.BoundingRect
if ($r.X -lt $minX) { $minX = $r.X }
if ($r.Y -lt $minY) { $minY = $r.Y }
if (($r.X + $r.Width) -gt $maxX) { $maxX = $r.X + $r.Width }
if (($r.Y + $r.Height) -gt $maxY) { $maxY = $r.Y + $r.Height }
}
if ($minX -eq [double]::MaxValue) { $minX = 0; $minY = 0 }
[void]$lines.Add([ordered]@{
text = $line.Text
x = [int]$minX
y = [int]$minY
w = [int]($maxX - $minX)
h = [int]($maxY - $minY)
})
}
$o = [ordered]@{
ok = $true
lang = $engine.RecognizerLanguage.LanguageTag
width = [int]($decoder.PixelWidth)
height = [int]($decoder.PixelHeight)
orig_width = $origW
orig_height = $origH
scale = [math]::Round($scale, 2)
lines = $lines
}
[System.IO.File]::WriteAllText($Out, ($o | ConvertTo-Json -Depth 6 -Compress), (New-Object System.Text.UTF8Encoding($false)))
}
catch {
$e = $_.Exception
while ($e.InnerException) { $e = $e.InnerException }
Fail "OCR_FAILED" ($e.GetType().Name + ": " + $e.Message)
}