face_detect.jl 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using OpenCV
  2. function detect(img::OpenCV.InputArray, cascade)
  3. rects = OpenCV.detectMultiScale(cascade, img, scaleFactor=1.3, minNeighbors=Int32(4), minSize=OpenCV.Size{Int32}(30, 30), flags=OpenCV.CASCADE_SCALE_IMAGE)
  4. processed_rects = []
  5. for rect in rects
  6. push!(processed_rects, (rect.x, rect.y, rect.width+rect.x, rect.height+rect.y))
  7. end
  8. return processed_rects
  9. end
  10. function draw_rects(img, rects, color)
  11. for x in rects
  12. OpenCV.rectangle(img, OpenCV.Point{Int32}(x[1], x[2]), OpenCV.Point{Int32}(x[3], x[4]), color, thickness = Int32(2))
  13. end
  14. end
  15. cap = OpenCV.VideoCapture(Int32(0))
  16. # Replace the paths for the classifiers before running
  17. cascade = OpenCV.CascadeClassifier("haarcascade_frontalface_alt.xml")
  18. nested = OpenCV.CascadeClassifier("haarcascade_eye.xml")
  19. OpenCV.namedWindow("facedetect")
  20. while true
  21. ret, img = OpenCV.read(cap)
  22. if ret==false
  23. print("Webcam stopped")
  24. break
  25. end
  26. gray = OpenCV.cvtColor(img, OpenCV.COLOR_BGR2GRAY)
  27. gray = OpenCV.equalizeHist(gray)
  28. rects = detect(gray, cascade)
  29. vis = copy(img)
  30. draw_rects(vis, rects, (0.0, 255.0, 0.0))
  31. if ~OpenCV.empty(nested)
  32. for x in rects
  33. roi = view(gray, :, Int(x[1]):Int(x[3]), Int(x[2]):Int(x[4]))
  34. subrects = detect(roi, nested)
  35. draw_view = view(vis, :, Int(x[1]):Int(x[3]), Int(x[2]):Int(x[4]))
  36. draw_rects(draw_view, subrects, (255.0, 0.0, 0.0))
  37. end
  38. end
  39. OpenCV.imshow("facedetect", vis)
  40. if OpenCV.waitKey(Int32(5))==27
  41. break
  42. end
  43. end
  44. OpenCV.release(cap)
  45. OpenCV.destroyAllWindows()
  46. print("Stopped")