Victor
Victor

Reputation: 5353

Remove object's background & resize object to its content in fabric js

Not sure if I put the right title in the question.

In my project user drops a clothing item to the canvas. Usually the clothing item has some white background and looks like this:

enter image description here

I apply RemoveColor filter and remove white background. But still the object has the same size as it had before. What I wan to is clip image like this:

enter image description here

Removing the unnecessary background.

How can I do this and is it possible at all?

Upvotes: 1

Views: 622

Answers (1)

Asterisk
Asterisk

Reputation: 3574

The general pipeline is as follows:

  1. Load the image and convert to gray scale
  2. Threshold image and get a binary image
  3. Apply morphological operation, in your case closing should do it. Invert the image to get black background and white foreground.
  4. Find connected regions and select largest as you region of interest
  5. Crop it out.

EDIT Here is some sample code in Python (using opencv and skimage libraries).

img = cv2.imread('test2.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

t, bw_img = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

closing = cv2.morphologyEx(bw_img, cv2.MORPH_CLOSE, np.ones((3, 3)))
closing = cv2.bitwise_not(closing)

labels, num = measure.label(closing, background=0, connectivity=2, return_num=True)
max_size, max_blob = 0, None
for l in range(1, num+1):
    blob = np.zeros_like(labels)
    blob[labels == l] = 1
    nz = np.count_nonzero(blob)
    if nz > max_size:
        max_size = nz
        max_blob = blob
assert(max_blob is not None)

x, y = np.nonzero(max_blob)
xmin, xmax = min(x), max(x)
ymin, ymax = min(y), max(y)
max_blob = max_blob[xmin: xmax, ymin:ymax]
# Resized color image
img = img[xmin: xmax, ymin:ymax]

EDIT2 Images corresponding to steps of the code enter image description here enter image description here enter image description here enter image description here enter image description here enter image description here enter image description here

Upvotes: 2

Related Questions