PowerShellで動画の顔検出をしてみる

| 2009年10月29日木曜日
OpenCvSharpを使用して、Webカメラでキャプチャーしながら顔検出をしてみる。
基本的には静止画の時と同じで、その部分のコードを動画のキャプチャーに埋め込んだだけ。
  1. [void][System.Reflection.Assembly]::LoadFrom((Join-Path $pwd OpenCvSharp.dll))
  2. #顔を検出するためにHaar分類器のカスケードを用いる
  3. $color = [OpenCvSharp.CvColor]::Red
  4. $scale = 1.04;
  5. $scaleFactor = 1.139;
  6. $minNeighbors = 2;
  7. $camera = [OpenCvSharp.CvCapture]::FromCamera(0)
  8. $window = New-Object OpenCvSharp.CvWindow("SampleCapture")
  9. $srcWidth = $camera.FrameWidth
  10. $srcHeight = $camera.FrameHeight
  11. $srcSize = New-Object OpenCvSharp.CvSize([int]$srcWidth, [int]$srcHeight)
  12. $srcIplImage = New-Object OpenCvSharp.IplImage( $srcSize, [OpenCvSharp.BitDepth]::U8, 1)
  13. $dstWidth = $camera.FrameWidth / $scale
  14. $dstHeight = $camera.FrameHeight / $scale
  15. $dstSize = New-Object OpenCvSharp.CvSize([int]$dstWidth, [int]$dstHeight)
  16. $dstIplImage = New-Object OpenCvSharp.IplImage( $dstSize, [OpenCvSharp.BitDepth]::U8, 1)
  17. while ( [OpenCvSharp.CvWindow]::WaitKey(10) -lt 0 ) {
  18. $iplImage = $camera.QueryFrame()
  19. #顔検出用の画像の生成
  20. [OpenCvSharp.Cv]::CvtColor($iplImage,$srcIplImage, [OpenCvSharp.ColorConversion]::BgraToGray)
  21. [OpenCvSharp.Cv]::Resize($srcIplImage, $dstIplImage, [OpenCvSharp.Interpolation]::Linear)
  22. [OpenCvSharp.Cv]::EqualizeHist($dstIplImage,$dstIplImage)
  23. $cascade = [OpenCvSharp.CvHaarClassifierCascade]::FromFile((Join-Path $pwd "haarcascade_frontalface_alt.xml"))
  24. $storage = New-Object OpenCvSharp.CvMemStorage
  25. $storage.Clear()
  26. # 顔の検出
  27. $faces = [OpenCvSharp.Cv]::HaarDetectObjects($dstIplImage, $cascade, $storage, $scaleFactor, $minNeighbors, 0, (New-Object OpenCvSharp.CvSize(30, 30)));
  28. Write-Host $faces.Total
  29. # 検出された全ての顔位置に四角い枠を描画する
  30. for ($i = 0; $i -lt $faces.Total; $i++) {
  31. $r = $faces[$i].Rect
  32. $pt1 = New-Object OpenCvSharp.CvPoint($r.x, $r.y)
  33. $pt2 = new-object OpenCvSharp.CvPoint(($r.x + $r.Width),($r.y + $r.Height ))
  34. $iplImage.Rectangle($pt1, $pt2, $color, 3, 8, 0)
  35. }
  36. # 丸で囲む
  37. # for ($i = 0; $i -lt $faces.Total; $i++) {
  38. # $r = $faces[$i].Rect
  39. # $X = [OpenCvSharp.Cv]::Round(($r.X + $r.Width * 0.5) * $Scale)
  40. # $Y = [OpenCvSharp.Cv]::Round(($r.Y + $r.Height * 0.5) * $Scale)
  41. # $center = New-Object OpenCvSharp.CvPoint($X, $Y)
  42. # $radius = [OpenCvSharp.Cv]::Round(($r.Width + $r.Height) * 0.25 * $Scale)
  43. # $iplImage.Circle($center, $radius, $color, 3, [OpenCvSharp.LineType]::AntiAlias, 0)
  44. # }
  45. # ウィンドウに表示
  46. $window.Image = $iplImage
  47. }
  48. $srcIplImage.Dispose()
  49. $dstIplImage.Dispose()
  50. $iplImage.Dispose()
  51. $window.Dispose()
  52. $camera.Dispose()

0 コメント: