【发布时间】:2019-05-30 02:07:04
【问题描述】:
从下面的 python 代码中,我可以绘制颜色image 的三个颜色分量的直方图。但我想将此直方图数据保存到 CSV 文件中,以便将来获取此直方图。我该怎么做?
from PIL import Image
import matplotlib.pyplot as plt
def getRed(redVal):
return '#%02x%02x%02x' % (redVal, 0, 0)
def getGreen(greenVal):
return '#%02x%02x%02x' % (0, greenVal, 0)
def getBlue(blueVal):
return '#%02x%02x%02x' % (0, 0, blueVal)
# Create an Image with specific RGB value
image = Image.open("baboon.ppm")
# Modify the color of two pixels
image.putpixel((0,1), (1,1,5))
image.putpixel((0,2), (2,1,5))
# Display the image
#image.show()
# Get the color histogram of the image
histogram = image.histogram()
# Take only the Red counts
l1 = histogram[0:256]
# Take only the Blue counts
l2 = histogram[256:512]
# Take only the Green counts
l3 = histogram[512:768]
plt.figure(0)
# R histogram
for i in range(0, 256):
plt.bar(i, l1[i], color = getRed(i), edgecolor=getRed(i), alpha=0.3)
# G histogram
plt.figure(1)
for i in range(0, 256):
plt.bar(i, l2[i], color = getGreen(i), edgecolor=getGreen(i),alpha=0.3)
# B histogram
plt.figure(2)
for i in range(0, 256):
plt.bar(i, l3[i], color = getBlue(i), edgecolor=getBlue(i),alpha=0.3)
plt.show()
这是红色通道histogram的输出
【问题讨论】:
-
使用
numpy.savetxt? -
@ImportanceOfBeingErnest 我不清楚如何使用它。可以举个例子吗?
-
numpy.savetxt("filename.txt", histogram)
标签: python csv matplotlib histogram