Reputation: 5353
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:
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:
Removing the unnecessary background.
How can I do this and is it possible at all?
Upvotes: 1
Views: 622
Reputation: 3574
The general pipeline is as follows:
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
Upvotes: 2