Sunday, 23 December 2018

Create a word cloud on selected pixels

I am trying to create a word cloud of a person's face. Similar to this

To achieve this I got a black & white image of a person and turned the darkest pixel to black and lightest pixel to white. And here is my result

enter image description here

Now I have got the area where I would like to place word clouds. Now I can't figure out how do I place words inside the face keeping margin/angle between words.

Here's the code what i have done so far

<?php
set_time_limit(0);
$src = 'person.jpeg';

$im = imagecreatefromjpeg($src);
$size = getimagesize($src);
$width = $size[0];
$height = $size[1];

$image_p = imagecreatetruecolor($width, $height);
imagecopyresampled($image_p, $im, 0, 0, 0, 0, $width, $height, $width, $height);

$white_color = imagecolorallocate($im, 255, 255, 255);
$black_color = imagecolorallocate($im, 0, 0, 0);

$font = __DIR__ . "/testfont.ttf";
$font_size = 16;
$text = "Test text";

$skip = true;
for ($x = 0; $x < $width; $x++) {
    for ($y = 0; $y < $height; $y++) {
        $rgb = imagecolorat($im, $x, $y);
        $r = ($rgb >> 16) & 0xFF;
        $g = ($rgb >> 8) & 0xFF;
        $b = $rgb & 0xFF;


        if ($r >= 126) {
            imagesetpixel($image_p, $x, $y, $white_color);
        } else {
            imagesetpixel($image_p, $x, $y, $black_color);

            if ($x % 20 == 1) {
                imagestring($image_p, 5, $x, $y, 'T', $black_color);
                //imagettftext($image_p, 16, 0, $x, $y, $black_color, $font, $text);
            }
        }
        //var_dump($r, $g, $b);
        //echo "<br/>";
    }
}
imagestring($image_p, 5, 0, 0, 'Hello world!', $black_color);

header('Content-Type: image/jpeg');
imagejpeg($image_p, null, 100);

I tried using imagestring & imagettftext

if ($x % 20 == 1) {
                imagestring($image_p, 5, $x, $y, 'T', $black_color);
                //imagettftext($image_p, 16, 0, $x, $y, $black_color, $font, $text);
            }

And got weird output. With imagettftext it takes too long to render and with imagestring this is what I got

enter image description here



from Create a word cloud on selected pixels

No comments:

Post a Comment