I am attempting to plot array values obtained from summing individual columns of a 开发者_如何学Gonumpy array. Working on Win XP, Python 2.5, matplotlib-1.0.1, numpy-1.5.1, PIL-1.1.7 Here is the code:
import Image
import numpy as np
import matplotlib.pyplot as plt
im = Image.open("tish.pnm")
im = im.convert("1") # convert necessary to import into numpy array
pixels = im.getdata()
n = len(pixels)
data = np.reshape(pixels, im.size)
sums = {}
#sum the range of column values
for i in range(0, data.shape[0]):
sums[i] = data[:,i].sum()
#this is where I can't get pyplot to work
plt.plot(sums) # this crashes with a "ValueError: need more than 0 values to unpack"
plt.plot(i,sums) #crashes with the same error
When I do a "print sums" I get data like:
{0: 705330, 1: 667845, 2: 693855, 3: 663000, 4: 699210, 5: 660705, 6: 686970, 7: 662490, 8: 697425, 9: 660450, 10: 688500, 11: 663510,...2913:65295}
What am I doing wrong?
It should also be noted, that besides the fact that you are attempting to plot a dict rather than a numpy array (this is why your code is producing an error), that you could achieve the same results without using an explicit python loop by using
sums = np.sum(data,axis=0)
and then plot the data using
plt.plot(sums)
In general, should avoid placing this sort of data into a dict in the first place since your key values are only indicies, which are implicit in the numpy array.
You should also take note that in your original formulation of the sum, you are looping over a range of size data.shape[0]
(the number of rows in data), but then in the sum you are
taking the sum for each column. If data.shape[1] < data.shape[0]
, you would have gotten an index error before you even hit the plotting section of your script.
精彩评论