【问题标题】:Creating image histograms from all pictures in a folder从文件夹中的所有图片创建图像直方图
【发布时间】:2020-02-14 13:57:25
【问题描述】:

我正在尝试为文件夹中的每个图像创建一个直方图,并将它们的图保存到 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

【问题讨论】:

  • 小心image = "x + 1" --> image = x + "1"

标签: python-3.x opencv histogram


【解决方案1】:

您可以使用 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)

【讨论】:

  • 要单独保存每个直方图,我是否必须将该代码放入 for 循环中,另外,我是否仍使用 image 变量来创建顺序文件名?
  • 这样做会给我这个错误:cv2.error: OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\imgproc\src\histogram.cpp:160: error: (-215:Assertion failed) j < nimages in function 'cv::histPrepareImages'
  • 你能确保 image 的值不是 none。您将在cv2.calcHist 中使用 img2 而不是 img,就像您在问题中所写的那样。
【解决方案2】:

我遇到的问题是图像变量是一个字符串,因此,当我向它添加 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)

【讨论】:

    猜你喜欢
    • 2012-06-15
    • 1970-01-01
    • 2013-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-01
    • 1970-01-01
    • 2016-05-28
    相关资源
    最近更新 更多