-1

我想读取一个 .tif 文件并计算图像中的像素数并确定对象的密度,但是当我尝试这样做时y, x = np.indices(image.shape),它给了我

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

2 回答 2

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]

希望这可以帮助

于 2014-03-12T17:55:27.353 回答
0

np.indices返回一个表示网格索引的数组。indices报错基本说明调用方法获取的值多于2个。由于它返回一个网格,您可以将它分配给一个变量grid,然后相应地访问索引。

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

例如。

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

上面的代码给你一个值错误,因为通过调用获得了 5 个字符串split(),而我试图将它们容纳到只有 2 个变量中。

于 2014-03-12T17:56:07.873 回答