我想根据某些像素值创建一个 mask 。例如:B > 200 的每个像素
Image.load() 方法似乎正是我用这些值识别像素所需要的方法,但我似乎无法弄清楚如何获取所有这些像素并从中创建蒙版图像。
R, G, B = 0, 1, 2
pixels = self.input_image.get_value().load()
width, height = self.input_image.get_value().size
for y in range(0, height):
for x in range(0, width):
if pixels[x, y][B] > 200:
print("%s - %s's blue is more than 200" % (x, y))
``
最佳答案
我的意思是让你避免 for
循环而只使用 Numpy。因此,从这张图片开始:
from PIL import Image
import numpy as np
# Open image
im = Image.open('colorwheel.png')
# Make Numpy array
ni = np.array(im)
# Mask pixels where Blue > 200
blues = ni[:,:,2]>200
# Save logical mask as PNG
Image.fromarray((blues*255).astype(np.uint8)).save('result.png')
如果你想让蒙版像素变黑,使用:
ni[blues] = 0
Image.fromarray(ni).save('result.png')
您可以针对这样的范围进行更复杂的复合测试:
#!/usr/bin/env python3
from PIL import Image
import numpy as np
# Open image
im = Image.open('colorwheel.png')
# Make Numpy array
ni = np.array(im)
# Mask pixels where 100 < Blue < 200
blues = ( ni[:,:,2]>100 ) & (ni[:,:,2]<200)
# Save logical mask as PNG
Image.fromarray((blues*255).astype(np.uint8)).save('result.png')
您还可以对红色、绿色和蓝色设置条件,然后使用 Numpy 的 np.logical_and()
和 np.logical_or()
设置复合条件,例如:
bluesHi = ni[:,:,2] > 200
redsLo = ni[:,:,0] < 50
mask = np.logical_and(bluesHi,redsLo)
关于python - 如何使用 Pillow 的 Image.load() 函数生成蒙版,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56942102/