Last active
March 31, 2020 13:39
-
-
Save Y-Koji/a44685e6a73b89f4069bce661a727ad8 to your computer and use it in GitHub Desktop.
PowerShell で画像比較
This file contains hidden or 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
using assembly System.Drawing | |
using namespace System.Drawing | |
using namespace System.Drawing.Imaging | |
using namespace System.Runtime.InteropServices | |
# 画像比較関数 | |
# $img1 : 比較元画像 | |
# $img2 : 比較先画像 | |
# 備考 | |
# $img1, $img2 には同じサイズの画像を指定すること | |
function Compare-Bitmap { | |
param([Bitmap] $img1, [Bitmap] $img2); | |
$img1Data = | |
$img1.LockBits( | |
[Rectangle]::new(0, 0, $img1.Width, $img1.Height), | |
[ImageLockMode]::ReadOnly, | |
$img1.PixelFormat) | |
$img2Data = | |
$img2.LockBits( | |
[Rectangle]::new(0, 0, $img2.Width, $img2.Height), | |
[ImageLockMode]::ReadOnly, | |
$img2.PixelFormat) | |
$bitsWidth = $img1Data.Stride / $img1.Width | |
$pixelDataSize = $img1Data.Width * $img1.Height | |
$matchCount = 0.0 | |
$unMatchCount = 0.0 | |
for ($y = 0;$y -lt $img1.Height;$y++) { | |
for ($x = 0;$x -lt $img1.Width;$x++) { | |
$i = $img1Data.Stride * $y + $bitsWidth * $x | |
$img1Pixel = [Marshal]::ReadInt32($img1Data.Scan0, $i) | |
$img2Pixel = [Marshal]::ReadInt32($img2Data.Scan0, $i) | |
# 【比較処理】 | |
# $img1Pixel, $img2Pixel にRGBAデータがあるので、 | |
# それらを用いて任意の処理を書いてもよい。 | |
# RGBA完全一致で比較 | |
if ($img1Pixel -eq $img2Pixel) { | |
$matchCount += 1.0 | |
} else { | |
$unMatchCount += 1.0 | |
} | |
} | |
} | |
$img1.UnlockBits($img1Data) | |
$img2.UnlockBits($img2Data) | |
# 80% 以上同じピクセルがあれば同じ画像と判定する | |
$percent = ($matchCount / ($matchCount + $unMatchCount)) * 100.0 | |
if (80.0 -lt $percent) { | |
return $true | |
} else { | |
return $false | |
} | |
} | |
# テストプログラム | |
# テストしない場合は「&{」を「{」にする。 | |
$null = &{ | |
$img1Path = "C:\Users\PC user\Source\Repos\NoxMacro\NoxMacro\bin\Debug\capture\20200331\SPLIT\20200331_205330.png" | |
$img2Path = "C:\Users\PC user\Source\Repos\NoxMacro\NoxMacro\bin\Debug\capture\20200331\SPLIT\20200331_205553.png" | |
$img1 = [Bitmap] [Image]::FromFile($img1Path) | |
$img2 = [Bitmap] [Image]::FromFile($img2Path) | |
if (Compare-Bitmap -img1 $img1 -img2 $img2) { | |
Write-Host '$img1 と $img2 は同じです' | |
} else { | |
Write-Host '$img1 と $img2 は違います' | |
} | |
$img1.Dispose() | |
$img2.Dispose() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment