php - 如何在php中将灰度图像转换为纯黑白?
问题描述
我正在尝试使用 GD 库在 PHP 中将灰度图像转换为纯黑白。
目的是检测图像中的宫颈细胞。
我将留下 PHP 代码和一个 MatLab 代码(我在 MatLab 中编写了这段代码,我试图在 PHP 中获得相同的结果)。基本上,我无法访问每个像素的颜色并对其进行修改。示例图像
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');
解决方案
这是一种方法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。
推荐阅读
- c# - 通过 Web API 从 Excel 表(共享点)中获取价值
- amazon-ec2 - 地形。如何使用 for_each 识别元素(键)
- oracle-sqldeveloper - 退格键不适用于空格 Oracle SQL Developer 20.4.1
- scala - 如何确保一个方法在每个工作节点上只执行一次?
- java - 使用 log4j2 压缩超过 5 天的日志文件
- python - Http流,它是如何工作的?
- r - 无响应的用户界面
- css - CSS Bootstrap row col 尽可能向左浮动
- jspdf - html2canvas / pdf 页面超过 20 页时会截断一半
- wordpress - 使用 Argo CD 将 git 与 bitnami/wordpress 同步