将多个裁剪图像的 RGB 值保存在一个 csv 文件中

Save RGB values from multple cropped images in a csv file

我正在尝试使用单个图像从多个裁剪图像中提取 RGB 值。我想将这些 RGB 值保存到一个 csv 文件中。同样,我编写了下面提到的代码,下面还附上了图片 (color.jpg)。但此代码仅保存最后裁剪图像的 RGB 值。我想保存所有裁剪图像的 RGB 值。谁能建议我必须对此代码进行哪些更改?

提前致谢

Python代码:

from __future__ import with_statement
import cv2
import numpy as np
import csv

 #image_path
img_path="gr.jpg"

#read image
img_raw = cv2.imread(img_path)

#select ROIs function
ROIs = cv2.selectROIs("Select Rois",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 "ROIs"
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("crop"+str(crop_number),img_crop)
    #save cropped image
    cv2.imwrite("crop"+str(crop_number)+".jpg",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(["img_name", "R", "G", "B"])  
        csv_output.writerow(["crop"+str(crop_number), R, G, B])
      
    crop_number+=1
  
#hold window
cv2.waitKey(0)
cv2.destroyAllWindows()

[color.jpg][1] [1]: https://i.stack.imgur.com/DpJD5.jpg

我想你只想打开 "append":

with open('output_file.csv', 'a', newline='') as f_output: