Search code examples
phpimagemagickimagemagick-convert

convert whiteboard cleaner script to php


I'm trying to convert this Imagemagick whiteboard cleaning script to pure PHP using the imagick extension to avoid having to resort to spawning processes with exec or the like.

Original bash script:

#!/bin/bash
convert $1 -morphology Convolve DoG:15,100,0 -negate -normalize -blur 0x1 -channel RBG -level 60%,91%,0.1 $2

I'm struggling with the initial Convolve morphology kernel matrix, everything else seems to work I think:

<?php

$channel = null;

$convolveKernel = array(15, 100, 0);
$negateGreys = false;

$blurRadius = 0;
$blurSigma = 1;

$levelBlack = 60; // 60%
$levelGamma = 0.1;
$levelWhite = 91; // 91%

$image = new Imagick($file);

try {
    $image->convolveImage($convolveKernel, $channel);
    $image->negateImage($negateGreys, $channel);
    $image->normalizeImage($channel);
    $image->blurImage($blurRadius, $blurSigma, $channel);
    $image->levelImage($levelBlack, $levelGamma, $levelWhite, $channel);

    header('Content-type: image/jpeg');
    echo $image;
} catch (ImagickException $e) {
    echo $e->getMessage();
}

I'm getting an exception "The kernel must contain a square number of elements" but I'm also wondering about the scale of the black and white level values — are these 0-100, 0-255 or 0-65535?


Solution

  • The PECL Imagick extension doesn't implement (or use) MagickWand's MagickMorphologyImage, which is the interface for the -morphology Convolve DoG:15,100,0 flag in the original command.

    To use convolveImage, you'll likely need to use an odd-numbered matrix:

    The kernel is a matrix specified as a comma-separated list of integers (with no spaces), ordered left-to right, starting with the top row. Presently, only odd-dimensioned kernels are supported, and therefore the number of entries in the specified kernel must be 32=9, 52=25, 72=49, etc.

    But I don't think you'll be able to recreate it as such (at least not as high-quality as the original), since the original flag uses the computed convolution Difference of Gaussians (DoG), which you won't be able to recreate using the simpler, more primitive convolve.