Skip to content

Instantly share code, notes, and snippets.

@wiledal
Last active August 29, 2015 14:05
Show Gist options
  • Save wiledal/0f7b406133cb87d990a8 to your computer and use it in GitHub Desktop.
Save wiledal/0f7b406133cb87d990a8 to your computer and use it in GitHub Desktop.
Webcam Motion Detection
class MotionDetection
@getDataPositionFromCoordinates = (width, x, y) ->
return x * 4 + y * (width * 4)
getCoordinatesFromPosition: (position) ->
return {
x: (position % @camCanvas.width) / @camCanvas.width
y: (Math.floor(position / @camCanvas.width)) / @camCanvas.height
}
constructor: ->
@prevImage = null
@currImage = null
@cam = document.createElement "video"
@camCanvas = document.createElement "canvas"
@camCtx = @camCanvas.getContext "2d"
@mediaStream = null
@camCanvas.width = 160 * 1
@camCanvas.height = 120 * 1
@camCtx.translate @camCanvas.width, 0
@camCtx.scale -1, 1
@cam.play()
calcDifference: (target, data1, data2) =>
if data1.length != data2.length then return null
i = 0
while i < data1.length / 4
average1 = (data1[4*i] + data1[4*i+1] + data1[4*i+2]) / 3
average2 = (data2[4*i] + data2[4*i+1] + data2[4*i+2]) / 3
diff = @threshold(@bitAbs(average1 - average2))
target[4*i] = 0
target[4*i+1] = 0
target[4*i+2] = 0
target[4*i+3] = diff
i++
onTick: (data, imageData) -> true
bitAbs: (value) =>
return (value ^ (value >> 31)) - (value >> 31);
threshold: (value) =>
return (if value > 0x15 then 0xFF else 0)
requestWebcam: ->
navigator.getUserMedia = navigator.getUserMedia || navigator.mozGetUserMedia || navigator.webkitGetUserMedia || navigator.msGetUserMedia
navigator.getUserMedia {
video: true
}, (stream) =>
@mediaStream = stream
@cam.src = URL.createObjectURL(@mediaStream)
@onWebcamStart @mediaStream
, (error) =>
@onWebcamError
stopWebcamStream: =>
if @mediaStream then @mediaStream.stop()
onWebcamStart: (stream) ->
onWebcamError: ->
tick: =>
@camCtx.drawImage @cam, 0, 0, @camCanvas.width, @camCanvas.height
@currImage = @camCtx.getImageData 0, 0, @camCanvas.width, @camCanvas.height
if @prevImage
targetImage = @camCtx.createImageData @camCanvas.width, @camCanvas.height
@calcDifference targetImage.data, @currImage.data, @prevImage.data
@onTick targetImage.data, @currImage
@prevImage = @currImage
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment