函数的返回值到另一个函数python

时间:2017-03-02 14:35:22

标签: python scikit-learn return

免责声明:我是编程新手。 以下代码不起作用,因为似乎函数1的输出未传递给函数2.

def img_to_color(path_file):

# takes an image and calculates avg red / green / blue value
color_avg = [red, green, blue]
return color_avg        

def extract_RGB(path_folder):

j = 0
RGB = []
file_count = len(os.listdir(path_folder))
files = os.listdir(path_folder)
while j < file_count:
    img_to_color(path_folder + "/" + files[j])
    RGB.append(color_avg)
    j = j+1
X_training.append(trainingDataFolder(pfad, RGB))

函数img_to_color有效,但即使我调用函数,RGB也会保持[]。

2 个答案:

答案 0 :(得分:0)

变量color_avgimg_to_color函数的本地变量。它不存在于extract_RGB内。 img_to_color返回一个值,因此您必须为其分配一个变量,如:

color_avg = img_to_color(...)

或直接将返回值传递给类似函数:

RGB.append(img_to_color(...)

答案 1 :(得分:0)

缩进有问题。您应该先阅读this

BTW,变量X_training似乎没有在任何地方声明,所以我不确定它是否属于更全局的背景。

代码应该这样写:

def img_to_color(path_file):
    # takes an image and calculates avg red / green / blue value
    color_avg = [red, green, blue]
    return color_avg        

def extract_RGB(path_folder):
    j = 0
    RGB = []
    file_count = len(os.listdir(path_folder))
    files = os.listdir(path_folder)
    while j < file_count:
        color_avg = img_to_color(path_folder + "/" + files[j])
        RGB.append(color_avg)
        j = j+1
    X_training.append(trainingDataFolder(pfad, RGB))