Skip to content

Instantly share code, notes, and snippets.

@zaheeraws
Created May 1, 2020 08:12
Show Gist options
  • Save zaheeraws/d0901ee95a9505114aa48012952a4456 to your computer and use it in GitHub Desktop.
Save zaheeraws/d0901ee95a9505114aa48012952a4456 to your computer and use it in GitHub Desktop.
<?php
//sudo apt install php
//sudo apt-get install php-imagick
function backgroundMasking($path)
{
$imagick = new \Imagick(realpath($path));
$backgroundColor = "rgb(255, 255, 255)";
$fuzzFactor = 0.6;
$outlineImagick = clone $imagick;
$outlineImagick->transparentPaintImage(
$backgroundColor, 0, $fuzzFactor * \Imagick::getQuantum(), false);
$mask = clone $imagick;
$mask->setImageAlphaChannel(\Imagick::ALPHACHANNEL_DEACTIVATE);
$mask->transformImageColorSpace(\Imagick::COLORSPACE_GRAY);
$mask->compositeImage(
$outlineImagick,
\Imagick::COMPOSITE_DSTOUT,
0, 0
);
$mask->negateImage(false);
$fillPixelHoles = false;
if ($fillPixelHoles == true) {
$mask->blurimage(2, 1);
$mask->whiteThresholdImage("rgb(10, 10, 10)");
$mask->blurimage(2, 1);
$mask->blackThresholdImage("rgb(255, 255, 255)");
}
$mask->blurimage(2, 2);
$contrast = 15;
$midpoint = 0.7 * \Imagick::getQuantum();
$mask->sigmoidalContrastImage(true, $contrast, $midpoint);
$imagick->compositeimage(
$mask,
\Imagick::COMPOSITE_COPYOPACITY,
0, 0
);
$canvas = new \Imagick();
$canvas->newPseudoImage(
$imagick->getImageWidth(),
$imagick->getImageHeight(),
"pattern:checkerboard"
);
$canvas->compositeimage($imagick, \Imagick::COMPOSITE_ATOP, -60, -220);
$canvas->setImageFormat('png');
$to = 'result.png';
file_put_contents($to,$canvas->getImageBlob());
return $to;
}
$dir = "./";
if( isset($argv[1]) ) {
$dir = trim($argv[1]);
echo "Processing on {$dir}" . PHP_EOL;
}else{
echo "Processing on {$dir}" . PHP_EOL;
echo "You can use first parameter to provide custom direcoty." . PHP_EOL;
echo "Example: " . basename(__FILE__, '.php') . " '/var/www/raw_images/'".PHP_EOL;
}
$cdir = scandir($dir);
foreach ($cdir as $key => $value)
{
if (!in_array($value,array(".","..", basename(__FILE__, '.php'))))
{
echo "{$key}: Processing: $value" . PHP_EOL;
backgroundMasking($value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment