【问题标题】:How can I save a cv2 histogram to a file in Python?如何将 cv2 直方图保存到 Python 中的文件中?
【发布时间】:2018-08-24 21:56:24
【问题描述】:

我想从文件中保存计算得到的直方图,以便无需重新计算即可重新打开它,但我不确定如何保存然后再次读取它。

image_path = "/Users/..../test.jpg"
image = cv2.imread(image_path, 0)
if image is not None: 
    hist = cv2.calcHist([image], [0], None, [256], [0, 256])
    cv2.imwrite("/Users/.../hist.jpg", hist) # What should this be?

hist = cv2.imread("/Users/.../hist.jpg", 0) # And this?

编辑: 所以我想做这样的事情,但我不确定语法是什么。

with open('hist.txt', 'a') as fp:
    fp.write('%s %s %s', [hist_id, list(hist), color])
with open('hist.txt', 'r') as fp:
    lines = fp.readlines()
    for line in lines: 
        hist_id = line[0]
        hist = np.array(eval(line[1]))
        color = line[2]
        cv2.compare(hist.....) 

编辑 2:

new_entry = [image, list(hist1), list(hist2)]
for item in new_entry:
    fd.write("%s\t" % item)
fd.write("\n")

with open('hist.txt', 'r') as fd:
     lines = fd.readlines()
     for line in lines:
         line = line.split('\t')
         cv2.compareHist(numpy.array(line[1]), numpy.array(line[2]))

【问题讨论】:

    标签: python python-2.7 opencv cv2


    【解决方案1】:

    请注意,cv2.calcHist 返回一维数组,而不是图像,因此您不能使用cv2.imwrite 保存它,而是使用标准数据文件,例如 CSV(逗号分隔值)。如果您可以每个文件只存储一个直方图,最简单的解决方案是使用简单的文本文件:

    import cv2
    import numpy as np
    from matplotlib import pyplot as plt
    
    image = cv2.imread(image_path)
    hist = cv2.calcHist([image], [0], None, [256], [0,256])
    
    with open('histo.txt', 'w') as file:
       file.write(list(hist))  # save 'hist' as a list string in a text file
    

    然后:

    with open('histo.txt', 'r') as file:
       hist = np.array(eval(file.read()) # read list string and convert to array
    

    另一方面,如果您的目标不是保存,而是绘制直方图,matplotlib 可能是最简单的工具。此代码 sn-p 绘制图像的 R、G 和 B 通道的所有三个直方图:

    import cv2
    import numpy as np
    from matplotlib import pyplot as plt
    
    image = cv2.imread(image_path)
    colors = ('b','g','r')
    for n, color in enumerate(colors):
        hist = cv2.calcHist([image], [n], None, [256], [0,256])
        plt.plot(hist, color=color)
        plt.xlim([0, 256])
    plt.show()
    

    【讨论】:

    • 我只是想保存直方图,以便以后可以使用cv2.compareHist() 进行比较,而无需重新计算直方图。
    • 好的,所以我编辑答案以包含直方图数据的保存/恢复功能
    • 如何每行写入多个(例如,我想将 id 与直方图数据相关联)。 file.write((hist_id, list(hist))?然后lines = file.readlines(); for line in lines: id = line[0]; hist = np.array(eval(line[1]));
    • 我编辑了我的主要帖子以及我如何编写和阅读这些行,但是当我尝试比较直方图时出现错误:TypeError: H1 data type = 18 is not supported
    【解决方案2】:

    即使您想保存图,matplotlib 也是一个好方法。 matplotlib.pyplot.savefig(‘my_cv2hist.png’) 适合您,如果要将直方图保存为您正在寻找的图像。

    imread 如果您尝试像在示例代码中尝试那样读回它,那么它就可以正常工作。

    【讨论】:

    • 我只是想保存直方图,以便以后可以使用cv2.compareHist() 进行比较,而无需重新计算直方图。
    猜你喜欢
    • 1970-01-01
    • 2013-09-30
    • 2019-05-30
    • 2019-12-23
    • 1970-01-01
    • 2021-05-28
    • 1970-01-01
    • 2013-11-04
    相关资源
    最近更新 更多