title: How to find the centroid of pixels with same color in a 360° video?
body: <p>Let <strong>I</strong> be a <code>w x h</code> frame from a 360° video stream.
  Let <strong>R</strong> be a red rectangle on that frame. <strong>R</strong> is smaller than the width of the image.</p>
  
  <p>To compute the centroid of this rectangle we need to distinguish two cases:</p>
  
  <ul>
  <li>case 1 where <strong>R</strong> is on the edges</li>
  <li>case 2 where <strong>R</strong> is fully inside the frame</li>
  </ul>
  
  <p><a href="https://i.stack.imgur.com/FIR58.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FIR58.png" alt="Case 1 and 2 illustrated"></a></p>
  
  <p>As you can see there will be a problem to compute the centroid with classical methods in case 1. Please note that I only care about horizontal overlapping.</p>
  
  <p>For the moment I am doing like this. First we detect the first point we find and use it as a reference, then we normalize <code>dx</code> which is the difference between a point and the reference and then we accumulate:</p>
  
  <pre><code>width = frame.width
  rectangle_pixel = (255,0,0)
  first_found_coord = (-1,-1)
  centroid = (0,0)
  centroid_count = 0
  
  for pixel, coordinates in image:
    if(pixel != rectangle_pixel): 
      continue
    if(first_found_coord == (-1,-1)):
      first_found_coord = coordinates 
      centroid = coordinates
      continue
  
    dx = coordinates.x - first_found_coord.x
    if(dx &gt; width/2):
      dx -= width
    else if(dx &lt; - width/2):
      dx -= width
  
    centroid += (dx, coordinates.y)
    centroid_count++
  
  
  final_centroid = centroid / centroid_count 
  </code></pre>
  
  <p>But it doesn't work as expected. Where is the problem, is there a faster solution ?</p>