如何在 php 中将灰度图像转换为纯黑白图像?

How to convert a grayscale image to pure black and white in php?

我正在尝试使用 GD 库在 PHP 中将灰度图像转换为纯黑白图像。

目的是检测图像中的宫颈细胞。

我将留下 PHP 代码和一个 MatLab 代码(我在 MatLab 中编写了这段代码,我试图在 PHP 中获得相同的结果)。基本上,我无法访问每个像素的颜色并对其进行修改。 sample image

PHP:

<?php
 $im = imagecreatefromjpeg("celule.jpg");

function imagetograyscale($im)
{
    if (imageistruecolor($im)) {
        imagetruecolortopalette($im, false, 256);
    }

    for ($c = 0; $c < imagecolorstotal($im); $c++) {
        $col = imagecolorsforindex($im, $c);
        $gray = round(0.299 * $col['red'] + 0.587 * $col['green'] + 0.114 * $col['blue']);
        imagecolorset($im, $c, $gray, $gray, $gray);
    }
}

imagetograyscale($im);

//imagefilter($im, IMG_FILTER_CONTRAST, -255);  //i'm not looking for this effect 

header('Content-type: image/jpeg');
imagejpeg($im);

$C = imagesx($im); //width
 $L = imagesy($im); //height

 echo "Dimensiuni imagine: latime $C, inaltime $L <br>";

 //scanning through the image
 for($x = 0; $x < $L; $x++) {  //each line
    for($y = 0; $y < $C; $y++) {  //each column
        // pixel color at (x, y)
        $color = imagecolorat($im, $y, $x);
        $color = imagecolorsforindex($im, $color); //getting rgb values
        $RED[$x][$y] = $color["red"];  //each rgb component
        $GREEN[$x][$y] = $color["green"];
        $BLUE[$x][$y] = $color["blue"];

    }
 } 

?>

MATLAB:

clear all, clc, close all;


I = imread('celule.jpg');
imshow(I)
title('original');

a=rgb2gray(I);

figure;
imshow(a)
title('grayscale');

s=size(a);


for i=1:s(1)
    for j=1:s(2)

        if a(i,j)>190
            a(i,j)=0;
        else a(i,j)=255;
            end
        end
end

 figure;
 imshow(a)
 title('pure black and white');

你试过 Imagick charcoalImage 吗? https://phpimagick.com/Imagick/charcoalImage

也许 PHPImagick 库更适合您的工作。

这是一种使用 gd 来做到这一点的方法:

#!/usr/bin/php -f
<?php

   // Open image and get dimensions
   $im = imagecreatefromjpeg("cellule.jpg");
   $w = imagesx($im);
   $h = imagesy($im);

   // Convert to greyscale
   imagefilter($im,IMG_FILTER_GRAYSCALE);
   imagepng($im, "grey.png");              // DEBUG only

   // Allocate a new palette image to hold the b&w output
   $out = imagecreate($w,$h);
   // Allocate b&w palette entries
   $black = imagecolorallocate($out,0,0,0);
   $white = imagecolorallocate($out,255,255,255);

   // Iterate over all pixels, thresholding to pure b&w
   for ($x = 0; $x < $w; $x++) {
      for ($y = 0; $y < $h; $y++) {
         // Get current color
         $index  = imagecolorat($im, $x, $y);
         $grey   = imagecolorsforindex($im, $index)['red'];
         // Set pixel white if below threshold - don't bother settting black as image is initially black anyway
         if ($grey <= 190) {
            imagesetpixel($out,$x,$y,$white);
         }
      }
   }
   imagepng($out, "result.png");
?>

关键字:PHP,图像处理,灰度,灰度,阈值,调色板,PNG,gd,GD,imagecreate,imagepng,imagecreatefromjpeg,imagecolorallocate。