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

wj8zmpe1  于 2022-12-27  发布在  Matlab
关注(0)|答案(1)|浏览(165)

我尝试使用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');
sulc1iza

sulc1iza1#

下面是使用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");
?>

相关问题