【问题标题】:How I can apply color threshold into an image created from `imagecreatefromstring`?如何将颜色阈值应用到从“imagecreatefromstring”创建的图像中?
【发布时间】:2022-07-19 20:18:37
【问题描述】:

我有以下代码:

define(RED_THESHOLD,100);
define(GREEN_THESHOLD,200);
define(BLUE_THESHOLD,100);

function thresholdImage(String $imgdata){
   $original_limit = ini_get('memory_limit');
   ini_set('memory_limit', '-1');
   $imageResource = imagecreatefromstring($imgData);

   // Limit red green and blue color channels here
}

但我不知道如何将颜色应用于常量:

  • RED_THESHOLD
  • GREEN_THESHOLD
  • BLUE_THESHOLD

根据经典算法,我需要逐个像素地读取每个通道,并通过以下代码应用阈值(我以图像红色通道为例):

 $new_pixel_value = ($red_pixel_value>RED_THESHOLD)?RED_THESHOLD:$red_pixel_value;

你知道我该怎么做吗?

【问题讨论】:

  • 是的,你需要逐像素处理。
  • 好的,你知道@Olivier 是怎么做到的吗?我*的意思是如何逐像素处理图像?

标签: php image-processing gd


【解决方案1】:

这可以通过查找每个像素的颜色索引,将其转换为 RGBA,然后约束这些值,将其转换回颜色索引并设置像素来​​完成。

<?php

const RED_THESHOLD = 255;
const GREEN_THESHOLD = 10;
const BLUE_THESHOLD = 10;

$image = imagecreatefrompng('test.png');

$maxX = imagesx($image);
$maxY = imagesy($image);

for ($y = 0; $y < $maxY; ++$y) {
    for ($x = 0; $x < $maxX; ++$x) {
        $existing = imagecolorsforindex($image, imagecolorat($image, $x, $y));

        $red = ($existing['red'] > RED_THESHOLD) ? RED_THESHOLD : $existing['red'];
        $green = ($existing['green'] > GREEN_THESHOLD) ? GREEN_THESHOLD : $existing['green'];
        $blue = ($existing['blue'] > BLUE_THESHOLD) ? BLUE_THESHOLD : $existing['blue'];

        $new = imagecolorexact($image, $red, $green, $blue);

        imagesetpixel($image, $x, $y, $new);
    }
}

imagepng($image, 'test2.png');

这是一张对比图:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-27
    • 2020-02-13
    • 2021-06-03
    • 2011-10-21
    • 2010-12-30
    • 1970-01-01
    • 2019-11-06
    • 2021-09-20
    相关资源
    最近更新 更多