3

I have a video with a green background. I want to remove this green section (Chroma key), making it transparent, and then display the video over the website background.

I can only find complex code that uses images.

ashleedawg
  • 20,365
  • 9
  • 72
  • 105
Programmer123
  • 31
  • 1
  • 2
  • It is possible. You can draw a video in a canvas and manipulate the pixels you drawing to its. Here is the tutorial (video rendering inside canvas, per-pixel image manipulation) -> http://html5doctor.com/video-canvas-magic/ – Tomasz Kajtoch Dec 13 '15 at 16:51

1 Answers1

2

Starting information: The video element can be an image source for html5 canvas. That means a frame of video can be drawn onto (and manipulated by) the canvas.

Overview: The context.getImageData method will get the canvas' RGBA pixel data in an array. After modifying the array's pixel data, context.putImageData will put the modified pixels back onto the canvas.

A Plan Use CSS to position an html5 canvas over the site background. Use that canvas to draw video frames over the site (with greenish video pixels made transparent so the site background shows through).

(some assembly & learning required on your part):

Position an html5 canvas element covering the website background.

Inside a time loop (requestAnimationFrame):

  1. Clear the canvas: context.clearRect,
  2. Draw a video frame onto the canvas: context.drawImage(video,0,0),
  3. Get the pixel data from the canvas: context.getImageData,
  4. Check each pixel for "green-ish-ness": if(green>220 && red<20 && blue<20),
  5. If a pixel is greenish, make it transparent: (alpha=0),
  6. Put the modified pixels back onto the canvas: context.putImageData,
  7. Repeat at #1 until the video finishes.

References to help with your learning

Stackoverflow prior post regarding #2: Put the video tag on the Canvas tag

Stackoverflow prior post regarding #3-6: Looping through pixels in an image

Community
  • 1
  • 1
markE
  • 102,905
  • 11
  • 164
  • 176
  • @markeE but how to define color range eg. for background with blue color, I tried to google it , but without success :) – Motoo Nov 02 '16 at 11:46
  • @Motoo Just adjust step#4 to check for your own form of "blue-ish-ness". While I have no idea what your use-case is, you might start with `rec<20 && green<20 && blue>220`. :-) – markE Nov 02 '16 at 12:28
  • Personally, the following method with bigger/smaller values didn't work for me at all and it's very dangerous to use. Since a relatively good green value can occur even at very lower values, but other types of hues can occur as well. This method `green > red + reverse_tolerance && green > blue + tolerance` for me worked better, but still very badly. Isn't there a more accurate one? I think HSL format may help more. – Eksapsy Mar 06 '18 at 18:25
  • . . . dangerous? – ashleedawg Nov 21 '20 at 08:48