0

I have 3 nested loops: one that goes through 5 images, one that goes through the 3 RGB channels of each image, and finally, one that creates a histogram of each image. I want to write the histogram of each image in a CSV file using the code below. However, instead of repeating 256 times for each channel, it only prints the first 256, then stops working. This method works fine with the print() function. Why doesn't it go through each with my CSV file then?

for image in images:
img = cv2.imread("%s%s" % (path, image))  # Load the image
channels = cv2.split(img)  # Set the image channels
colors = ("b", "g", "r")  # Initialize tuple
plt.figure()
plt.title("Color Histogram")
plt.xlabel("RGB Bins")
plt.ylabel("Number of Pixels")

for (i, col) in zip(channels, colors):  # Loop over the image channels
    hist = cv2.calcHist([i], [0], None, [256], [0, 256])  # Create a histogram for current channel
    plt.plot(hist, color=col)  # Plot the histogram
    plt.xlim([0, 256])
    hist = hist.astype(int)
    print(hist)
    with open('mycsv.csv', 'w', newline='') as f:
        thewriter = csv.writer(f)
        thewriter.writerows(hist)
  • Please fix the indentation. We can't tell what's included in the `for image in images:` loop. – Barmar Dec 21 '20 at 16:44
  • 2
    Every time you open `mycsv.csv` in `w` mode it removes the previous contents. You should either open the file once before all the loops, or open it in `a` mode to append. – Barmar Dec 21 '20 at 16:46
  • So you should be getting the *last* 256, not the first. – Barmar Dec 21 '20 at 16:46

2 Answers2

0

Opening a file with "w" mode erases it's contents. You should use "a" to append, or "a+" if you want to both append and read the file. The pointer will be in all cases put at the end of the file.

0

"Every time you open mycsv.csv in w mode it removes the previous contents. You should either open the file once before all the loops, or open it in a mode to append. – Barmar"

This worked thanks a lot. I'm new to SOF, so I don't know how to flag it as a working answer. Anyways, the fixed code is:

... with open('mycsv.csv', 'a', newline='') as f: ...