简体   繁体   中英

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])

xxxx
xxxx
xxxx
xxxx

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

xxxx
xaax
xaax
xxxx

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]

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)

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM