我创建了一个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()

最佳答案

相反:

if __name__ == '__main__':
    remove_green_background()

关于python - 实现定义为入口点的功能,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54150492/

10-12 18:32