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

南笙酒味 提交于 2019-12-31 05:15:33

问题


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):

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:

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

In case someone need the original image for testing:

UPDATE:

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

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


回答1:


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.

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:

I applied threshold and obtained the following image:

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

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



来源:https://stackoverflow.com/questions/41526023/remove-white-background-from-the-image-and-make-it-transparent-using-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!