Skip to content Skip to sidebar Skip to footer

Opencv : Python Equivalent Of `setto` In C++

What is the python equivalent of Mat::setTo in C++ ? What I'm trying to do is to set value by mask: Mat img; ... img.setTo(0, mask); Update: Here is possible solution: #set by mas

Solution 1:

You can simply use img[mask > 0] = 0 which is the python equivalent of img.setTo(0, mask);

Solution 2:

opencv in python uses numpy as backend (more specifically numpy.ndarray) for images. This means you can do the following:

import numpy
img = numpy.zeros((256, 256, 3))  # This initializes a color image as an array full of zeros

Then if i wish to set the third channel as 1 all I have to do is:

img[:, :, 2:3] = 1

Therefore if Mask has the same dimensions as my third channel i can use it to set the third channel:

img[:, :, 2:3] = mask

edited after comment: in case you simply wish to set pixels of image to zeros using a mask a simple image * mask should suffice. make sure mask has same number of dimensions as image.

edit #2: Yeah that might work, but if the shape of your mask is the only issue, i would use mask[:, :, numpy.newaxis] to add a dimension and then multiply with image.

btw numpy.newaxis is same as using mask[:,:,None].

Post a Comment for "Opencv : Python Equivalent Of `setto` In C++"