0

I have a code which takes images from a folder, crops the region of interest around it using the ROI function, and then removes the background using the rembg library. But I want a border around that image, around that specific object itself, like the one we get in segmentation, except keeping the colours and the object intact. [NOT A RECTANGULAR BORDER]. Can anyone help and tell me how to do it?

Here is my code for reference:

import cv2
import numpy as np
import os
from os.path import join
from os import listdir
from PIL import Image
from rembg import remove


path = 'Some path'
folder = 'Some other path'
count = 1

def image_resize(image, width = None, height = None, inter = cv2.INTER_AREA):
    dim = None
    (h, w) = image.shape[:2]

    if width is None and height is None:
        return image
    if width is None:
        r = height / float(h)
        dim = (int(w * r), height)
    else:
        r = width / float(w)
        dim = (width, int(h * r))

    resized = cv2.resize(image, dim, interpolation = inter)

    return resized


for filename in os.listdir(folder):
       img = cv2.imread(os.path.join(folder,filename))
       if img is not None: 
           img = image_resize(img, height = 600)
           roi = cv2.selectROI(img)
           print(roi)
           im_cropped = img[int(roi[1]):int(roi[1]+roi[3]),int(roi[0]):int(roi[0]+roi[2])]
           rs = str(count)
           rem = remove(im_cropped)
           cv2.imshow("Removed Image", rem)
           
           cv2.imwrite(os.path.join(path, rs + '.jpg'), rem)
           count = count + 1
           cv2.waitKey(0)

1 Answers1

1

As i assume you mean a simple outline, i would suggest the following:

import cv2
import numpy as np

# Threshold the image
thresh = img > threshold
# Use binary dilation to widen the area
thresh_dil = cv2.dilate(thresh, np.ones((3, 3)) , iterations=1)
# Get the outlines by substracting the dilated image with the original area
outlines = thresh_dil - thresh
# Superimpose the outlines on your original image
img_with_outlines = img.copy()
img_with_outlines[outlines > 0] = 255

This should draw a white line around your detected object.

Note: This approach works grayscale images. For full colour images you can apply it for each channel individually.

SilverMonkey
  • 1,003
  • 7
  • 16