title: Save RGB values from multple cropped images in a csv file
body: <p>I am trying to extract RGB values from multiple cropped images using a single image. I want to save these RGB values into a csv file. For the same I have written the code mentioned below and the image is also attached below (color.jpg). But this code saves only the last cropped image RGB values. I want to save the RGB values for all cropped images. Could anyone suggest to me what changes I have to make for this code?</p>
  <p>Thank you in advance</p>
  <p>Python code:</p>
  <pre><code>from __future__ import with_statement
  import cv2
  import numpy as np
  import csv
  
   #image_path
  img_path=&quot;gr.jpg&quot;
  
  #read image
  img_raw = cv2.imread(img_path)
  
  #select ROIs function
  ROIs = cv2.selectROIs(&quot;Select Rois&quot;,img_raw)
  
  #print rectangle points of selected roi
  print(ROIs)
  
  #Crop selected roi ffrom raw image
  #roi_cropped = img_raw[int(roi[1]):int(roi[1]+roi[3]), int(roi[0]):int(roi[0]+roi[2])]
  
  #counter to save image with different name
  crop_number=0 
  
  #loop over every bounding box save in array &quot;ROIs&quot;
  for rect in ROIs:
      x1=rect[0]
      y1=rect[1]
      x2=rect[2]
      y2=rect[3]
  
      #crop roi from original image
      img_crop=img_raw[y1:y1+y2,x1:x1+x2]
      b,g,r = cv2.split(img_crop)
  
      #Average RGB of the cropped image  
      B = b.mean()
      G = g.mean()
      R = r.mean()
          
      #show cropped image
      cv2.imshow(&quot;crop&quot;+str(crop_number),img_crop)
      #save cropped image
      cv2.imwrite(&quot;crop&quot;+str(crop_number)+&quot;.jpg&quot;,img_crop)
      
      #Open a file to write the pixel data
      with open('output_file.csv', 'w', newline='') as f_output:
          csv_output = csv.writer(f_output)
          csv_output.writerow([&quot;img_name&quot;, &quot;R&quot;, &quot;G&quot;, &quot;B&quot;])  
          csv_output.writerow([&quot;crop&quot;+str(crop_number), R, G, B])
        
      crop_number+=1
    
  #hold window
  cv2.waitKey(0)
  cv2.destroyAllWindows()
  </code></pre>
  <p>[color.jpg][1]
  [1]: https://i.stack.imgur.com/DpJD5.jpg</p>