繁体   English   中英

CSV 文件在嵌套循环中仅写入 256 行

[英]CSV file only writes 256 lines in a nested loop

我有 3 个嵌套循环:一个遍历 5 个图像,一个遍历每个图像的 3 个 RGB 通道,最后一个创建每个图像的直方图。 我想使用下面的代码在 CSV 文件中写入每个图像的直方图。 但是,它不是为每个通道重复 256 次,而是只打印前 256 次,然后停止工作。 此方法适用于print() function。 那么为什么不通过我的 CSV 文件 go 呢?

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)

以“w”模式打开文件会删除其内容 如果您想同时使用 append 并读取文件,则应使用“a”到 append 或“a+”。 在所有情况下,指针都将放在文件的末尾。

“每次在 w 模式下打开 mycsv.csv 时,它都会删除以前的内容。您应该在所有循环之前打开文件一次,或者以 append 的模式打开它。 – Barmar”

这非常感谢。 我是 SOF 的新手,所以我不知道如何将其标记为有效答案。 无论如何,固定代码是:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM