【发布时间】:2015-04-20 03:26:23
【问题描述】:
说明
我有一张图片和它的面具。我正在使用 PIL 和 Numpy 应用以下规则:
- 掩码为红色
(255, 0, 0)的像素设置为(0, 0, 0)。 - 掩码为绿色的像素
(0, 255, 0),设置为(64, 64, 64) - 蒙版为蓝色的像素
(0, 0, 255),设置为(128, 128, 128) - 蒙版为黄色的像素
(255, 255, 0),设置为(255, 255, 255) - 否则,保持像素不变。
我尝试过的
利用数组掩码的思想,我尝试了以下方法:
import numpy as np
import Image
# (R G B)
red = [255, 0, 0]
green = [0, 255, 0]
blue = [0, 0, 255]
yellow = [255, 255, 0]
def execute():
im = Image.open('input.png')
data = np.array(im)
print "Original = ", data.shape
mask = Image.open('mask2.png')
data_mask = np.array(mask)
print "Mask = ", data_mask.shape
red_mask = data_mask == red
green_mask = data_mask == green
blue_mask = data_mask == blue
yellow_mask = data_mask == yellow
data[red_mask] = [0, 0, 0]
data[green_mask] = [64, 64, 64]
data[blue_mask] = [128, 128, 128]
data[yellow_mask] = [255, 255, 255]
im = Image.fromarray(data)
im.save('output.png')
if __name__ == "__main__":
execute()
问题
上面的代码输出:
Original = (64, 64, 3)
Mask = (64, 64, 3)
ValueError: NumPy boolean array indexing assignment cannot assign 3 input values to the 5012 output values where the mask is true
我错过了什么吗?如何使用数组掩码的思想来改变像素值?
【问题讨论】:
-
这不是你的问题,但如果你使用的是
import Image而不是from PIL import Image,这意味着你使用的是 PIL 而不是它的现代 fork Pillow。除非你真的需要与非常旧版本的 Python 向后兼容,或者由于某种原因不能与 Pillow 一起使用的代码(不应该有这样的东西,但总会有错误,对吧?),不要这样做那个。 -
供将来参考:PIL 的东西在这里根本不相关;您可以使用源代码中硬编码的一对 5x5x3 数组来演示相同的问题。对于这个问题,这将是一个更好的minimal, complete, verifiable example。如果你不能这样做,至少将 64x64x3 PNG 文件上传到某个地方,以便人们可以调试你的示例——但最好让它们变得不必要。 (我认为这是一个很好的问题,只是它可能是一个更好的问题。)
标签: python image-processing numpy