J'ai créé un programme python qui supprime simplement le fond vert des images.
Maintenant je veux implémenter ma fonction remove_green_background () définie comme point d'entrée. J'ai cherché sur de nombreux sites Web et également sur stackoverflow, mais je ne comprends pas comment fonctionnent les points d'entrée.
Donc n'importe qui peut m'expliquer en utilisant ce code en détail où mettre ces points d'entrée?
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()
3 Réponses :
Dans l'autre sens:
if __name__ == '__main__':
remove_green_background()
Cela devrait fonctionner:
if __name__ == '__main__':
remove_green_background()
Dans la plupart des cas, le point d'entrée est défini comme le nom de la fonction. Alors changez simplement le nom de votre fonction en remove_green_background () et ce serait votre point d'entrée.
@Obaid_Ur_Rehman que vouliez-vous faire ici:
if __name__ == '__ remove_green_background __':Désolé, c'était une erreur lors de la copie du code. Je l'ai édité.