如何在图像中找到最暗的像素,图像中出现的最大?因此,要找到我可以比其他像素看到更多的最暗像素.
在这里,我发现了我的图像噪点,并用白色对其进行了着色,但是如何找到最暗的像素呢?我尝试在rgb数组元素中找到巫婆的出现次数是最大的,但是我发现白色像素到了.这是我的代码的一部分:
<?php
function components($color) {
return array(($color >> 16) & 0xFF, ($color >> 8) & 0xFF, $color & 0xFF);
}
// Performs "similarity test" of 2 colors
function isSimilar($color1, $color2) {
$c1 = components($color1);
$c2 = components($color2);
for ($i = 0; $i < 3; $i++) {
$k = ($c1[$i] > $c2[$i]) ? ($c1[$i] - $c2[$i]) / $c2[$i] : ($c2[$i] - $c1[$i]) / $c1[$i];
if ($k > 0.35) return false;
}
return true;
}
function LoadJpeg($imgname)
{
$count = 0;
/* Attempt to open */
$im = @imagecreatefrompng($imgname);
$imagedata = getimagesize($imgname);
$n = $imagedata[0];
$m = $imagedata[1];
for($i=0; $i<$imagedata[0]; $i++){
for($j=0; $j<$imagedata[1]; $j++){
$rgb[$i][$j] = imagecolorat($im, $i, $j);
//echo $rgb[$i][$j];
//echo "<br>";
}
}
/* for ($k = 0; $k < $n; $k++)
{
for ($l = 0; $l < $m; $l++)
{
for ($i = 0; $i < $n; $i++)
{
for ($j = 0; $j < $m; $j++)
{
if (($i+1 == $n) && ($j+1 == $m))
{
continue;
}
else
{
if ($j+1 == $m and $rgb[$i][$j] > $rgb[$i+1][0])
{
$t = $rgb[$i][$j];
$rgb[$i][$j] = $rgb[$i+1][0];
$rgb[$i+1][0] = $t;
}
else
{
if ($rgb[$i][$j] > $rgb[$i][$j+1])
{
$t = $rgb[$i][$j];
$rgb[$i][$j] = $rgb[$i][$j+1];
$rgb[$i][$j+1] = $t;
}
}
}
}
}
}
}*/
for($i=0; $i<$imagedata[0]-3; $i++){
for($j=0; $j<$imagedata[1]-3; $j++){
if (isSimilar($rgb[$i][$j], $rgb[$i][$j + 3]) or isSimilar($rgb[$i][$j], $rgb[$i + 3][$j]))
{
#echo "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAa";
$count = $count + 1;
//echo "<br> <br>";
//echo $count;
//$red = imagecolorallocate($im, 255, 255, 255);
imagesetpixel($im, $i, $j, 16777215);
cropCentered($im,20,20);
}
}
}
return $im;
}
function cropCentered($img, $w, $h)
{
$cx = $img->getWidth() / 2;
$cy = $img->getHeight() / 2;
$x = $cx - $w / 2;
$y = $cy - $h / 2;
if ($x < 0) $x = 0;
if ($y < 0) $y = 0;
return $img->crop(0, 0, $w, $h);
}
header('Content-Type: image/jpeg');
$img = LoadJpeg('1.png');
imagejpeg($img,null, 100);
?>
解决方法:
您需要使用不同于RGB的颜色模型-在这种情况下,HSL非常有用,因为它包含“亮度”成分.基于此组件,我们可以判断某种颜色是比另一种颜色浅还是深.有几种将RGB转换为HSL的方法,我使用了Wikipedia article中描述的方法(请参阅HSL“ bi-hexcone”模型):
<?php
// Returns whether c2 is darker than c1
function isDarker($c1, $c2) {
// Find L (lightness) component in a HSL model
$max1 = max($c1);
$min1 = min($c1);
$l1 = ($max1 + $min1) / 2;
$max2 = max($c2);
$min2 = min($c2);
$l2 = ($max2 + $min2) / 2;
// Compare colors based on L component (lower means darker)
return $l2 < $l1;
}
// Assuming colors are stored in a 2-dimensional $rgb array
$rowCount = count($rgb);
$colCount = count($rgb[0]);
$darkest = $rgb[0][0];
for ($i = 0; $i < $rowCount; $i++) {
for ($j = 0; $j < $colCount; $j++) {
if (isDarker($darkest, $rgb[$i][$j])) {
$darkest = $rgb[$i][$j];
// Optionally you can save the indices $i and $j
}
}
}