title: Extracting pixel values by overlaying polygons
body: <p>I am trying to extract pixel values by overlaying polygons. I use a code from Patrick Grey (<a href="http://patrickgray.me/open-geo-tutorial/chapter_5_classification.html" rel="nofollow noreferrer">http://patrickgray.me/open-geo-tutorial/chapter_5_classification.html</a>). When I masked the image with the shape features, I wanted, I got <code>out_image</code>. Then the next step would be to remove 0, which totally mess up the array as values are not present according bands.<br>
  I tried many different ways as to remove 0 and keep the order of band values according to the class. In <code>R</code> I can do it without any problem and when I export the data as <code>CSV</code> and train the algorithm everything works fine in a <code>Python</code> environment.</p>
  
  <p>How can I extract pixel values and keep the numbers band and class-wise?</p>
  
  <pre><code> X = np.array([], dtype=np.int8).reshape(0,8) # pixels for training
   y = np.array([], dtype=np.string_) # labels for training
  
  with rasterio.open(img_fp) as src:
      band_count = src.count
      for index, geom in enumerate(geoms):
          feature = [mapping(geom)]
  
  # the mask function returns an array of the raster pixels within this feature
  out_image, out_transform = mask(src, feature, crop=True) 
  # eliminate all the pixels with 0 values for all 8 bands - AKA not actually part of the shapefile
  out_image_trimmed = out_image[:,~np.all(out_image == 0, axis=0)]
  # eliminate all the pixels with 255 values for all 8 bands - AKA not actually part of the shapefile
  out_image_trimmed = out_image_trimmed[:,~np.all(out_image_trimmed == 255, axis=0)]
  # reshape the array to [pixel count, bands]
  out_image_reshaped = out_image_trimmed.reshape(-1, band_count)
  # append the labels to the y array
  y = np.append(y,[shapefile["Classname"][index]] * out_image_reshaped.shape[0]) 
  # stack the pizels onto the pixel array
  X = np.vstack((X,out_image_reshaped))        
  </code></pre>
  
  <p>Many thanks for any hints!</p>