我根本不明白你在试图对扁平和不连续的索引做什么,但纯粹从你的 comments 来看,我理解你想要影响图像中的一些特定 colored颜色 ,所以我将try 并演示这一点.
这是一个中心为rgb(20, 50, 140)
,边缘为rgb(40, 70, 160)
的径向渐变图像,所以我碰巧知道有4,884个像素(如果这很重要的话,是非直线相邻的),值为rgb(25,55,145)
现在,让我们打开它并将其变成一个Numy数组:
from PIL import Image
import numpy as np
# Open image and make into Numpy array
im = Image.open('a.png').convert('RGB')
na = np.array(im)
# Make Boolean (True/False) mask of interesting pixels
mask = np.all(na==[25,55,145], axis=-1)
# Briefly save the mask so we can see what it selects
Image.fromarray(mask).save('DEBUG-mask.png')
# Let's also count the number of pixels selected by the mask
print(np.count_nonzero(mask)) # prints 4,884
现在,我们可以使用蒙版来更改选定的像素.让我们将原始图像中的遮罩像素设置为红色:
na[mask] = [255,0,0]
Image.fromarray(na).save('DEBUG-1.png')
现在使用蒙版的inverse来影响unselected个像素.让我们把它们变成灰色:
na[~mask] = [128,128,128]
Image.fromarray(na).save('DEBUG-2.png')
如果您想遮罩多个 colored颜色 ,使用可以使用逻辑运算将遮罩组合在一起.所以,假设你想额外屏蔽 colored颜色 rgb(28,58148),你可以在上面的代码末尾添加以下内容:
# Mask for second colour
mask2 = np.all(na==[28,58,148], axis=-1)
# Combine the two masks into new, bigger mask
both = mask | mask2
# Make masked pixels yellow and display
na[both] = [255,255,0]
Image.fromarray(na).show()
如果你想要遮罩range%的 colored颜色 ,我建议你用OpenCVinRange()
来设置R、G和B的下限和上限,然后 Select 介于两者之间的所有 colored颜色 .
import cv2
# Mask range 25>R>35, 55>G>65, 145<B<160
colRange = cv2.inRange(na,np.array([25,55,145]) ,np.array([35,65,160]))
# Make range of colours lime green
na[colRange>0] = [0,255,0]
如果有人对我一开始是如何制作径向渐变感兴趣的,我在终端中使用了ImageMagick,并使用了以下命令:
magick -size 500x500 radial-gradient:"rgb(20, 50, 140)-rgb(40, 70, 160)" -depth 8 a.png
一个更简单、更清晰的版本可能是:
magick -size 500x500 radial-gradient:lime-magenta -depth 8 a.png