Numpy.putmask with images

匿名 (未验证) 提交于 2019-12-03 03:03:02

问题:

I have an image converted to a ndarray with RGBA values. Suppose it's 50 x 50 x 4.

I want to replace all the pixels with values array([255, 255, 255, 255]) for array([0, 0, 0, 0]). So:

from numpy import * from PIL import Image def test(mask):         mask = array(mask)         find = array([255, 255, 255, 255])         replace = array([0, 0, 0, 0])         return putmask(mask, mask != find, replace)  mask = Image.open('test.png') test(mask)

What am I doing wrong? That gives me a ValueError: putmask: mask and data must be the same size. Yet if I change the arrays to numbers (find = 255, replace = 0) it works.

回答1:

One way to do this kind of channel masking is to split the array into r,g,b,a channels, then define the index using numpy logical bit operations:

import numpy as np import Image  def blackout(img):     arr = np.array(img)     r,g,b,a=arr.T     idx = ((r==255) & (g==255) & (b==255) & (a==255)).T     arr[idx]=0     return arr  img = Image.open('test.png') mask=blackout(img)  
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!