-1

I have two images ( of the same size): A and B

A is the mask, it contains regions that have zero value and others that have RGB values.

B is the RGB image that i want to change the values of some of its pixels to their correspondent A's pixels (pixels that have the same position and that are different from zero).

I think it would be something like this:

if A(i,j) <>0 then B(i,j)=A(i,j)

except that i don't know how to write it in python... can anyone help?

Jav_Rock
  • 22,059
  • 20
  • 123
  • 164

2 Answers2

1

If you read the images with opencv:

h = b.shape[0]
w = b.shape[1]
for y in range(0, h):
        for x in range(0, w):
            if a[y,x] > 0:
                b[y,x] = a[y,x]

Or better, as points @Dan Mašek in the comment

import numpy as np

def apply_mask(img, mask):
    img = np.where(mask > 0, mask, img)
    return img

Notice that in numpy arrays, the height comes first in shape. Opencv loads the image into numpy arrays.

Jav_Rock
  • 22,059
  • 20
  • 123
  • 164
  • Thank you for your response. I'm a newbie in opencv, what does h = b.shape[0] stand for? – Black_panther Sep 23 '18 at 15:11
  • 2
    Better choice would be [`np.where(a > 0, a, b)`](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.where.html) instead of all that code. Most likely at least order of magniture faster too. – Dan Mašek Sep 23 '18 at 15:11
  • so after loading the images, i write this line and it's all set? – Black_panther Sep 23 '18 at 15:18
  • @Black_panther you can find a detailed answer [here](https://stackoverflow.com/a/19098258/744859) – Jav_Rock Sep 23 '18 at 15:18
  • I tried to type the code but it gave me this error: AttributeError: module 'cv2.cv2' has no attribute 'imread_COLOR' – Black_panther Sep 23 '18 at 15:35
1

To apply the mask for src, you can use cv2.bitwise_and:

cv2.bitwise_and(src, src, mask=mask)
Kinght 金
  • 17,681
  • 4
  • 60
  • 74