Tran Anh Minh
Tran Anh Minh

Reputation: 306

OpenCV Python - Placing one image on top of the other

I'm building a Sudoku Real Time solver.

I'm trying to place this image (warp):

enter image description here

On top of this image (original):

enter image description here

To make it become this image (result):

enter image description here

Here's what I got so far:

for i in range(original.shape[0]): # original and warp have the same size
    for j in range(original.shape[1]): 
        if numpy.sum(warp[i][j]) != 0: # If warp at (i,j) is not totally black
            original[i][j][0] = warp[i][j][0] # Replace original[i][j] with warp[i][j]
            original[i][j][1] = warp[i][j][1]
            original[i][j][2] = warp[i][j][2]

result = original

The code works but it's very slow. Can anybody suggests a better approach using opencv and python?

Thank you!

Upvotes: 0

Views: 319

Answers (1)

Julien
Julien

Reputation: 15071

What about this?

result = np.where(warp.sum(axis=-1,keepdims=True)!=0, warp, original)

.sum(axis=-1,keepdims=True) sums along the last axis, while retaining the last axis (necessary for later broadcasting), this effectively creates a mask for non black pixels. np.where then uses this mask to either use warp when mask true or original otherwise.

Upvotes: 1

Related Questions