title: FFMPEG Determine average color of an area of a video
body: <p>I have a use case where I'd want to insert one of two watermarks - one designed for a dark-ish background, the other for a light background into a video. Let's say that I'd want to do this on the top right corner of the video. </p>
  
  <p>How do I determine the average color of the top right section of the video? Post this, how do I determine which watermark to use by looking at the average color? </p>
  
  <p>I have a solution right now where I am taking equally spaced screenshots and then measuring the average color, but it's excruciatingly slow, especially for longer videos. </p>
  
  <pre><code># Calculate average color
      black_distances = []
      white_distances = []
  
      movie = FFMPEG::Movie.new(video_file)
      (0..movie.duration / 10).each do |second|
  
        # extract a frame
        filename = "tmp/watermark/#{SecureRandom.uuid}.jpg"
        movie.screenshot filename.to_s, seek_time: second
  
        # analyse frame for color distance
        frame = MiniMagick::Image.open(filename)
        frame.crop('20%x20%+80%+0')
        frame.resize('1x1')
        pixel = frame.get_pixels.flatten
  
        distance_from_black = Math.sqrt(((black[0] - pixel[0])**2 + (black[1] - pixel[1])**2 + (black[2] - pixel[2])**2))
        distance_from_white = Math.sqrt(((white[0] - pixel[0])**2 + (white[1] - pixel[1])**2 + (white[2] - pixel[2])**2))
  
        black_distances.push distance_from_black
        white_distances.push distance_from_white
  
        File.delete(filename) if File.exist?(filename)
      end
  
      average_black_distance = black_distances.reduce(:+).to_f / black_distances.size
      average_white_distance = white_distances.reduce(:+).to_f / white_distances.size
  </code></pre>
  
  <p>I am also confused about how to use the resulting <code>average_black_distance</code> and <code>average_white_distance</code> to determine which watermark to use. </p>