如何将cv2直方图保存到Python文件中?

如何将cv2直方图保存到Python文件中?,python,python-2.7,opencv,cv2,Python,Python 2.7,Opencv,Cv2,我想从一个文件中保存一个计算出的直方图,这样我就可以在不必重新计算的情况下重新打开它,但我不确定如何保存并再次读取它 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"

我想从一个文件中保存一个计算出的直方图,这样我就可以在不必重新计算的情况下重新打开它,但我不确定如何保存并再次读取它

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]))

请注意,
cv2.calcHist
返回的是1D数组,而不是图像,因此不能使用
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可能是最简单的工具。此代码段为图像的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()

即使您希望保存图形,
matplotlib
也是一种很好的方法
matplotlib.pyplot.savefig('my_cv2hist.png')
适用于您,前提是将直方图保存为您要查找的图像


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

我只是想保存柱状图,以便将来可以使用
cv2.compareHist()进行比较
无需重新计算直方图。我只是想保存直方图,以便将来可以使用
cv2.compareHist()
进行比较,而无需重新计算直方图。好的,因此我编辑答案以包含直方图数据的保存/还原功能。我如何每行写入多个(例如,我想将一个id与直方图数据关联)。
file.write((hist_id,list(hist))
?然后
lines=file.readlines();对于行中的行:id=line[0];hist=np.array(eval(line[1])
我编辑了我的主要帖子,介绍了我如何写和读这些行,但是当我尝试比较直方图时,发现一个错误:
TypeError:H1数据类型=18不受支持