title: Python - Get average RGB Components of Image Regions
body: <p>I need to calculate the average Red, Green &amp; Blue color component values for an image. The image is not necessarily square. It could be rectangular as well.</p>
  
  <p>The image is divided into 4 quadrants and each quadrant is further divided into 2 triangular regions, giving total of 8 regions in the image (P1 - P8) as such</p>
  
  <pre><code># -------------------------
  # - Q1        +        Q2 -   
  # -        P8 + P1        -
  # -      P7   +    P2     -
  # -+++++++++++++++++++++++-
  # -      P6   +    P3     -
  # -        P5 + P4        -
  # - Q4        +        Q3 -
  # -------------------------
  </code></pre>
  
  <p>So far I have managed to get the image (primary monitor screenshot) and convert the rgb values to a numpy array. </p>
  
  <p>From there I am not sure of the best way to get the triangular regions as I need this operation to be done atleast 3 times a second.</p>
  
  <p>Any ideas?</p>
  
  <pre><code>import subprocess
  import numpy
  import pyscreenshot as ImageGrab
  
  #GET THE PRIMARY MONITOR RESOLUTION
  output = subprocess.Popen('xrandr | grep "\*" | cut -d" " -f4',shell=True, stdout=subprocess.PIPE).communicate()[0]
  primary_monitor_x = output.split("\n")[0].split("x")[0].strip()
  primary_monitor_y = output.split("\n")[0].split("x")[1].strip()
  print "primary monitor X = " + primary_monitor_x + "px"
  print "primary monitor Y = " + primary_monitor_y + "px"
  
  print ""
  print ""
  
  x_max = int(primary_monitor_x)
  y_max = int(primary_monitor_y)
  
  #GET SCREEN IMAGE IN A PIL IMAGE
  im = ImageGrab.grab(bbox=(0,0,x_max,  y_max))
  #CONVERT IMAGE TO RGB MODE
  rgb_im = im.convert('RGB')
  
  #CONVERT IMAGE TO NUMPY 2D ARRAY WITH EACH ELEMENT AS PIXEL RGB TUPLE
  img_rgb_array = numpy.array(rgb_im);
  
  #THE SCREEN IS DIVIDED INTO 8 PARTS. FOR EACH PART, THE AVERAGE VALUE
  #OF RED, GREEN, BLUE COLOR COMPONENT WILL BE CALCULATED
  # -------------------------
  # - Q1        +        Q2 -   
  # -        P8 + P1        -
  # -      P7   +    P2     -
  # -+++++++++++++++++++++++-
  # -      P6   +    P3     -
  # -        P5 + P4        -
  # - Q4        +        Q3 -
  # -------------------------
  
  #SLICE THE IMAGE RGB ARRAY INTO 4 SMALLER QUADRANT ARRAYS
  img_rgb_arraq_q1 = img_rgb_array[0:(y_max/2), 0:(x_max/2)]
  img_rgb_arraq_q2 = img_rgb_array[0:(y_max/2), (x_max/2):x_max]
  img_rgb_arraq_q3 = img_rgb_array[(y_max/2):y_max, (x_max/2):x_max]
  img_rgb_arraq_q4 = img_rgb_array[(y_max/2):y_max, 0:(x_max/2)]
  </code></pre>