gpt4 book ai didi

python - 如何将 OpenCV 直方图保存到 Python 文件中?

转载 作者:太空宇宙 更新时间:2023-11-03 22:21:07 24 4
gpt4 key购买 nike

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

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 返回一维数组,而不是图像,因此您不能使用 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 channel 的所有三个直方图:

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

关于python - 如何将 OpenCV 直方图保存到 Python 文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49310466/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com