首页 > 解决方案 > 如何将函数定义为包入口点?

问题描述

我创建了一个 python 程序,它只是从图像中删除绿色背景。

现在我想实现remove_green_background()定义为入口点的函数。我已经搜索了许多网站以及 stackoverflow,但无法理解入口点的工作原理。

所以任何人都可以使用这段代码向我详细解释这些入口点应该放在哪里?

from PIL import Image
import sys
import os


def rgb_to_hsv(r, g, b):
    maxc = max(r, g, b)
    minc = min(r, g, b)
    v = maxc
    if minc == maxc:
        return 0.0, 0.0, v
    s = (maxc-minc) / maxc
    rc = (maxc-r) / (maxc-minc)
    gc = (maxc-g) / (maxc-minc)
    bc = (maxc-b) / (maxc-minc)
    if r == maxc:
        h = bc-gc
    elif g == maxc:
        h = 2.0+rc-bc
    else:
        h = 4.0+gc-rc
    h = (h/6.0) % 1.0
    return h, s, v


GREEN_RANGE_MIN_HSV = (100, 80, 70)
GREEN_RANGE_MAX_HSV = (185, 255, 255)

def remove_green_background():
    # Load image and convert it to RGBA, so it contains alpha channel
    name, ext = os.path.splitext(Filepath)
    im = Image.open(Filepath)
    im = im.convert('RGBA')

    # Go through all pixels and turn each 'green' pixel to transparent
    pix = im.load()
    width, height = im.size
    for x in range(width):
        for y in range(height):
            r, g, b, a = pix[x, y]
            h_ratio, s_ratio, v_ratio = rgb_to_hsv(r / 255.0, g / 255.0, b / 255.0)
            h, s, v = (h_ratio * 360, s_ratio * 255, v_ratio * 255)

            min_h, min_s, min_v = GREEN_RANGE_MIN_HSV
            max_h, max_s, max_v = GREEN_RANGE_MAX_HSV
            if min_h <= h <= max_h and min_s <= s <= max_s and min_v <= v <= max_v:
                pix[x, y] = (0, 0, 0, 0)


    im.save(name + '.png')


if __name__ == '__main__':
    remove_green_background()

标签: pythonpython-3.xpython-imaging-libraryentry-point

解决方案


您可能知道,Python 是一种脚本语言,因此程序的执行将从源文件的最顶部开始,一直持续到最后。因此,如果您mycode.py使用命令执行文件,python mycode.py则执行将从源文件的最顶部开始mycode.py

然而,这种方法在大型应用程序中带来了一些问题。通常,您运行的第一个命令是导入,它基本上获取一些其他 Python 文件,并在其中执行代码。所以作为一个实际示例,假设您有 2 个文件first.pysecond.py. first.py开始如下:

    import second

second开始如下:

    def a_function():
      # do something

然后 Python 看到导入命令,运行second.py并初始化函数a_function(),以便它现在可以在first.py

然而second.py,也可能包含在解释器在文件上运行时立即执行的代码,如下所示:

    def a_function():
      # do something
    print("I am called upon execution")

现在我们有一个问题:print 语句会在first.pyimport时执行second.py

为了解决这个问题,以下措施特别用于未来导入的文件中:

    def a_function():
      # do something

    if __name__ == "__main__":
      print("I am executed")

这不像 C 入口点 ( int main(){...})。事实上,C 编译器会在代码中的给定点寻找一个入口点来开始执行。Pyhton 解释 insted 只需对预定义的全局 ( __name__) 执行检查。如果变量为 equals "__main__",这是一个很笼统的解释,表示正在执行文件,否则表示正在导入文件(因此检查失败,不执行代码)。

因此,在您的情况下,只需定义您的函数(def remove_green_background():),然后在源文件中首先调用它(基本上,第一个没有缩进的命令)


推荐阅读