Xun Yang
Xun Yang

Reputation: 4419

Filling a blank image with another with opencv

I'm using python with cv2 library. I have a small image that I want to fill some blank space around. Say the blank image is as following: (each x means a pixel, [255,255,255])

x x x x
x x x x
x x x x
x x x x

I want to exchange some parts of it to the data from another image (each a means a pixel from another image)

x x x x
x a a x
x a a x
x x x x

What would be the quickest way of doing it? I tried looping through each pixel and do the job, but it seems to be highly inefficient.

import cv2
import numpy as np
tmp=np.zeros((1024,768,3),np.uint_8)
image= .. #image captured from camera
for(i in range(480)):
  for(j in range(640)):
    tmp[i+144][j+197]=image[i][j]

Upvotes: 1

Views: 4478

Answers (4)

biquette
biquette

Reputation: 226

In short you can do like that :

Size taille = new_image.size();   // New_image is the image to be inserted
Mat  white_roi( white_image, Rect( x, y, taille.width, taille.height ) );
                                  // white_roi is a subimage of white_image
                                  //          that start from the point (x,y)
                                  // and have the same dimension as a new_image
new_image.copyTo( white_roi );    // You copy the new_image into the white_roi,
                                  //          this in the original image

This is c++ code, you have to adapt to python.

Upvotes: 0

Froyo
Froyo

Reputation: 18477

Use numpy slicing.

tmp = np.zeros((1024,768,3),np.uint_8)

img[y1:y2, x1:x2] = tmp[y3:y4, x3:x4] # given that (y2-y1) = (y4 - y3) and same for x

Or fill it with some color

img[y1:y2, x1:x2] = (255, 255, 255)

Upvotes: 2

Pervez Alam
Pervez Alam

Reputation: 1256

If you want to replace some big parts like rectangles, then use ROI to replace (as other answers already explained). But if you are dealing with randomly distributed pixels or complex shapes then you can try this.

1) Create a mask binary image, MaskImage, for the part to be replaced as true rest is set as false.

2) Result = MasterImage AND (NOT(MaskImage)) + PickerImage AND MaskImage.

PS: I haven't used python as I don't know Python and it pretty easy expression. Good Luck

Upvotes: 1

Stephen Lin
Stephen Lin

Reputation: 4912

Change image to an array first and then do replacing.

Try this:

import cv2
import numpy as np
tmp=np.zeros((1024,768,3),np.uint_8)
image= .. #image captured from camera
src = np.array(image)

tmp[144:, 197:] = src

Make sure number of elements are right first.

Upvotes: 0

Related Questions