Попробуйте:
from PIL import Image
# Takes the input image
img = Image.open(r"Arrow.png")
# Getting the dimensions of the image
x, y = img.size
# Obtaining values of Red, Green, Blue for each opaque pixel
red = int(input("Enter the red value you want in each pixel = "))
green = int(input("Enter the green value you want in each pixel = "))
blue = int(input("Enter the blue value you want in each pixel = "))
i = j = 0
# This loop makes sure that alpha only has two discrete values (0 , 255)
# This is to ensure that constant color is obtained, at pixels where transparence may not be 255
# (prevents color escapes at pixels where total transparency is not achieved)
while i < x:
while j < y:
r, g, b, a = img.getpixel((i,j))
if a > 200 and a < 256:
a = 255
else:
a = 0
img.putpixel((i,j),(r,g,b,a))
j += 1
j = 0
i += 1
i = j = 0
# Two nested loops
# Outer one goes through rows of image
# Inner one (nested one) goes through columns of image
while i < x:
while j < y:
# This condition checks, if the value of alpha for that individual pixel is 255 (~opaque),
# if true then change its RGB values to user defined values
if img.getpixel((i,j))[-1] == 255:
img.putpixel((i,j), (red, green, blue, 255))
j += 1
j = 0
i += 1
img.save("Arrow.png")
ВХОД: -
Enter the red value you want in each pixel = 0
Enter the green value you want in each pixel = 0
Enter the blue value you want in each pixel = 255
ВЫВОД: -
![](https://i.stack.imgur.com/RzCZN.png)
ОБЪЯСНЕНИЕ ДЛЯ ПЕРВОГО ПЕТЛЯ: -
Если первый цикл не выровняется, значения alpha
определяются пороговым значением, то в выходном изображении возникает много ошибок. то есть значения пикселей около края объекта имеют тенденцию иметь alpha
значения пикселей немного меньше, чем 255
(общая непрозрачность), чтобы включить плавное сглаживание . Если эти пиксели отбрасываются, выходное изображение может выглядеть примерно так: -
![Notice the unwanted color's in the edge of the arrow](https://i.stack.imgur.com/U9ccI.png)
PS: - Несмотря на то, что OpenCV был бы предпочтительным выбором для большинства аналитиков / экспертов по изображениям, я бы определенно посоветовал вам придерживаться PIL / Pillow в начале, так как это позволяет вам понять основы визуализации в действительно дружественной форме. Нет никаких сомнений в том, что OpenCV намного превосходит PIL практически во всех аспектах, но, тем не менее, если вы изучите PIL в начале, переход от PIL к OpenCV будет гораздо проще выполнить позже.