2014-03-12 68 views
0

我想读取.tif文件并计算图像中像素的数量并确定对象的密度,但是当我尝试这个y, x = np.indices(image.shape)时,它会给我在python中读取像素:“ValueError太多值来解压缩”

Value Error (ValueError: too many values to unpack, File "<stdin>", line 1, in <module>). 

我的代码如下:

import sys 
import os 
import numpy as np 
from pylab import * 
import scipy 
import matplotlib.pyplot as plt 
import math 

#Function 
def radial_plot(image): 
    y, x = np.indices(image.shape) # <----- Problem here??? 
    center = np.array([(x.max()-x.min())/2.0, (x.max()-x.min())/2.0]) 
    r = np.hypot(x - center[0], y - center[1]) 
    ind = np.argsort(r.flat)- center[1]) 
    r_sorted = r.flat[ind] 
    i_sorted = image.flat[ind] 
    r_int = r_sorted.astype(int) 
    deltar = r_int[1:] - r_int[:-1] 
    rind = np.where(deltar)[0] 
    nr = rind[1:] - rind[:-1] 
    csim = np.cumsum(i_sorted, dtype=float) 
    tbin = csim[rind[1:]] - csim[rind[:-1]] 
    radial_prof = tbin/nr 
    return rad 
#Main 
img = plt.imread('dat.tif') 
radial_plot(img) 
+0

您使用的是什么版本的Python? – wnnmaw

+0

嗨wnnmaw:我正在使用Python 2.7.5 –

回答

1

的问题是,你正试图超过两个值赋给只有两个可变因素:

>>> a, b = range(2) #Assign two values to two variables 
>>> a 
0 
>>> b 
1 
>>> a, b = range(3) #Attempt to assign three values to two variables 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
ValueError: too many values to unpack 

在Python 2.x中,你可以做到以下几点:

>>> a, b = range(3)[0], range(3)[1:] 
>>> a 
0 
>>> b 
[1, 2] 

只是为了保持完整性,如果你有Python的3.x中,你可以做Extended Iterable Unpacking

>>> a, *b, c = range(5) 
>>> a 
0 
>>> c 
4 
>>> b 
[1, 2, 3] 

希望这有助于

+0

谢谢!它做了! –

+0

如果这解决了您的问题,请将其标记为“已接受的答案”,以便其他与您具有相同问题的人员可以快速找到解决方案 – wnnmaw

0

np.indices返回表示网格索引的数组。该错误基本上表示通过调用indices方法获得的值超过2个。由于它正在返回一个网格,因此可以将其分配给一个变量,例如grid,然后相应地访问索引。

错误的症结在于函数调用返回的不仅仅是2个值,并且在您的代码中,您试图将它们“挤”到2个变量中。

例如,

s = "this is a random string" 
x, y = s.split() 

上面的代码给你一个错误值,因为有通过调用split()获得5串,而我想他们适应逼到了2个变量。

+0

谢谢!它正在工作! –

相关问题