Skip to content

Instantly share code, notes, and snippets.

@vivahiraj
Created May 4, 2014 14:40
Show Gist options
  • Save vivahiraj/c59ae69a2529906456df to your computer and use it in GitHub Desktop.
Save vivahiraj/c59ae69a2529906456df to your computer and use it in GitHub Desktop.
OpenCVで加工した画像をwebsocketでクライアントに送るためのソースです。
require 'opencv'
require 'em-websocket'
require 'base64'
EM::run do
cap = OpenCV::CvCapture.open
det_file = "/usr/local/share/OpenCV/haarcascades/haarcascade_frontalface_default.xml"
det = OpenCV::CvHaarClassifierCascade::load det_file
connections = Array.new
EM::WebSocket.start(:host => '0.0.0.0', :port => 51234) do |ws|
ws.onopen do |handshake|
puts 'connected'
connections.push(ws)
end
ws.onclose do |handshake|
puts 'closed'
connections.delete(ws)
end
end
EM::defer do
loop do
sleep 0.1
next if connections.size == 0
img = cap.query
img = img.resize OpenCV::CvSize.new 640, 360
det.detect_objects(img).each do |rect|
puts "detect!! : #{rect.top_left}, #{rect.top_right}, #{rect.bottom_left}, #{rect.bottom_right}"
img.rectangle! rect.top_left, rect.bottom_right, :color => OpenCV::CvColor::Red
end
mat = img.to_CvMat
data = Base64.encode64(mat.encode('.jpg').pack('C*'))
connections.each do |con|
con.send(data);
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment