从文件夹中的所有图片创建图像直方图

Creating image histograms from all pictures in a folder

我正在尝试为文件夹中的每个图像创建直方图,并将它们的绘图保存到 CSV 文件中。用户将进入保存图像的文件夹,然后文件将被创建并相应地命名

files = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"] #loop to get all files from folder
for x in files:
    image = "x + 1"
    img2 = cv2.imread('similarImages/' + directory + '/' + image + '.png', cv2.IMREAD_COLOR)
    histSim = cv2.calcHist([img2], [1], None, [256], [0, 256])  # create histo of each image
    np.savetxt('Test/similarImage' + x + '.csv', histSim, delimiter=',')  # save save plots to csv

根据我以前对 python 的了解,我理论上编写了上述代码,但以经典方式,它不起作用(令人震惊)

我走的路对吗?如果不能,我能否得到正确方向的推动,如果可以,为什么它不起作用?

好久没接这样的东西了,有点生疏了,谢谢Ben

您可以使用 pandas 完成此任务。如果您想将所有直方图存储在一个 csv 文件中,您可以使用一个列表并使用此

将所有直方图值附加到它
df = []
df.append(cv2.calcHist(img, [1], None, [256], [0, 256])[:, 0]) # check if you want like this or transpose.

然后使用 pd.DataFrame 将其转换为数据帧并使用 df.to_csv

将其存储为 csv 文件

如果您想将每个直方图保存到其独立的 csv 文件中,您可以:

histSim = pd.DataFrame(cv2.calcHist(img, [1], None, [256], [0, 256]))
histSim.to_csv('histogram.csv', index=False)

我遇到的问题是图像变量是一个字符串,因此,当我向它添加 1 时,它是连接的,而不是添加值,所以使用整数,然后在我转换为字符串时在文件路径中需要它有效

image = 0
files = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  # loop to get all files from folder
for x in files:

    image = x + 1
    image = str(image)
    img2 = cv2.imread('similarImages/' + directory + '/' + image + '.png', cv2.IMREAD_COLOR)
    histSim = pd.DataFrame(cv2.calcHist([img2], [1], None, [256], [0, 256]))  # create histo of each image
    histSim.to_csv('Test/histogram' + image + '.csv', index=False)