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

时间:2018-03-15 22:48:13

标签: python python-2.7 opencv cv2

我想从文件中保存一个计算出的直方图,这样我就可以重新打开它,而不必重新计算它,但我不知道如何保存然后再读它。

.iloc

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

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?

编辑2:

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 个答案:

答案 0 :(得分:2)

请注意,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可能是最简单的工具。此代码段绘制了图像的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()

答案 1 :(得分:0)

即使您希望保存图形,matplotlib也是一种很好的方法。如果要将直方图保存为您要查找的图像,matplotlib.pyplot.savefig(‘my_cv2hist.png’)将对您有用。

imread如果您尝试按照尝试在示例代码中执行此操作的方式阅读它,则可以正常工作。