Eddy Unruh
Eddy Unruh

Reputation: 616

Remove white background from the image and make it transparent using PHP

I got this code to do that:

$im = new Imagick("test.jpg");
$im->paintTransparentImage($im->getImageBackgroundColor(), 0, 500);
$im->setImageFormat('png');
$im->writeImage('finish.png');

And this is the result (I added manually pink background to see the problems better):

enter image description here

When I increase the fuzz then more white pixels disappear next to the object but then more white pixels also disappear inside the object.

I tried the same image on a website and the result there is:

enter image description here

Which is pretty perfect. Does someone know how to do that?

In case someone need the original image for testing:

enter image description here

UPDATE:

Adding $im->despeckleimage(); before $im->paintTransparentImage makes a better result:

enter image description here

The only thing needs to be done is fill fill the small empty areas with white pixels. Is there any way to do that?

Upvotes: 0

Views: 5739

Answers (1)

Jeru Luke
Jeru Luke

Reputation: 21203

I obtained an instant solution using the GrabCut Algorithm. I used OpenCV 3 with python to get your desired output. Unfortunately I do not know php nor do I know imagik.

CODE:

import numpy as np
import cv2

img = cv2.imread('Dress.jpg',1)
cv2..imshow('Original image',img)
mask = np.zeros(img.shape[:2],np.uint8)

bgdModel = np.zeros((1,65),np.float64)
fgdModel = np.zeros((1,65),np.float64)

rect = (60,20,325,503)

cv2.grabCut(img,mask,rect,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_RECT)
mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8')
nimg = img*mask2[:,:,np.newaxis]

cv2.imshow("Extracted image",nimg)

cv2.waitKey()
cv2.destroyAllWindows()

I first created a black background using the mask variable.

This is what I obtained.

enter image description here

Visit THIS PAGE for details of this algorithm and the parameters used. You can work this out for masking on a colored background also.

I beleive the same can be tried out with imagik also. Hope this helps :)

EDIT:

This is in response to the edit you made to the question.

The following was the image uploaded by you:

enter image description here

I applied threshold and obtained the following image:

enter image description here

Now I performed 'morphological closing' operation and obtained this:

enter image description here

Finally I masked the image above with the original image you uploaded in the beginning to obtain this:

enter image description here

Upvotes: 1

Related Questions