Created
December 14, 2018 21:19
-
-
Save pr3sidentspence/d06f439fbacdbba15a9c19fae325b4c6 to your computer and use it in GitHub Desktop.
Powershell script that runs photos (default jpg) in current folder through Microsoft's Cognitive Services Vision API and rotates the photo to match the orientation that MSCSVapi has the most confidence in its caption of.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
param( | |
[string]$ext = "jpg" | |
) | |
# Powershell script that runs photos (default jpg) in current folder through | |
# Microsoft's Cognitive Services Vision API and rotates the photo | |
# to match the orientation that MSCSVapi has the most confidence in its caption of. | |
New-Item -ItemType directory -Path $PSScriptRoot/temp -Force | |
function callMsAPI { | |
$imagePath = "$PSScriptRoot\temp\testimage-$i.jpg" | |
$Uri = 'https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze?visualFeatures=Description' # make sure your endpoint matches you key | |
$Headers = @{ | |
'Ocp-Apim-Subscription-Key' = '<Subscription-Key>' #replace with yours | |
} | |
$Response = Invoke-RestMethod -Uri $Uri -Method Post -InFile $imagePath -Headers $Headers -ContentType 'application/octet-stream' | |
return $Response.description.captions.confidence | |
} | |
Get-ChildItem $PSScriptRoot -Filter *.$ext | | |
ForEach-Object { | |
$i = 0 | |
$highScore = 0 | |
$testSCore = 0 | |
[int]$bestRot | |
for ($i = 0; $i -le 270; $i = $i + 90) { | |
$out = "$PSScriptRoot\temp\testimage-$i.jpg" | |
if ($i -eq 0) { | |
cmd /c "magick.exe $PSScriptRoot\$_ -resize 20% $out" | |
} | |
else { | |
cmd /c "magick.exe $PSScriptRoot\temp\testimage-0.jpg -rotate $i $out" | |
} | |
Write-Host -NoNewline "sending $_.BaseName rotated $i degrees as testimage-$i.jpg to callMsAPI for analysis..." | |
$testScore = callMsAPI($i) | |
Write-Host "score: $testScore" | |
if ($testScore -gt $highScore) { | |
$highScore = $testScore | |
$bestRot = $i | |
} | |
# Sleep for 3 seconds as to not breech Microsoft's Free Tier rate limit. 3 might be overkill. | |
# Allowed 20/min. | |
Start-Sleep 3 | |
} | |
if ($bestRot -eq 0) { | |
Write-Host -ForegroundColor Green "$_ is already rightside up" | |
} | |
else { | |
Write-Host -ForegroundColor Yellow " a rotation of $bestRot degrees scored highest for $_ - rotating..." | |
cmd /c "magick.exe $_ -rotate $bestRot $_" | |
} | |
Remove-Item temp -Recurse -Force | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment