pythonnumpyopencvroi

Fill the center of ROI


How can I fill ROI, so that the image is placed in the centre of the ROI?

The ROI is found with (x, y, w, h) = cv2.boundingRect(contour) and I insert the input image with

                       image = cv2.resize(input_image, (w, h))
                       img2gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
                       _, image_mask = cv2.threshold(img2gray, 1, 255, cv2.THRESH_BINARY)
                       roi = frame[y:y+h, x:x+w]
                       roi[np.where(image_mask)] = 0
                       roi += image

The h and w are the dimensions of my input image.

How can I add the offsets so that the ROI += image will result like shown in the image? This is the outcome I want


Solution

  • As per my understanding, you want to place the resized image within the center of the ROI.

    You have already obtained the ROI roi = frame[y:y+h, x:x+w].

    # using this as background, hence making it white
    roi[:] = (255, 255, 255)
    
    # Obtain the spatial dimensions of ROI and image
    roi_h, roi_w = roi.shape[:2]
    image_h, image_w = image.shape[:2]
    
    # Calculate height and width offsets
    height_off = int((roi_h - image_h)/2)
    width_off = int((roi_w - image_w)/2)
    
    # With Numpy slicing, place the image in the center of the ROI
    roi[height_off:height_off+image_h, width_off:width_off+image_w] = image
    

    I hope this gives you an idea on how to proceed further