您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

图片灰度和二值化处理

2024/2/20 18:53:42发布23次查看
图片灰度和二值化处理
<?php function adaptivethreshold($file){ if(!$ex = getimagesize($file)){ return false; } // 打开图片 switch($ex[2]){ case imagetype_jpeg: case imagetype_jpeg2000: if(!$im = imagecreatefromjpeg($file)){ return false; } break; case imagetype_png: $im = imagecreatefrompng($file); break; case imagetype_gif: $im = imagecreatefromgif($file); break; case imagetype_bmp: $im = imagecreatefrombmp($file); break; default : return false; } $gray = array_fill(0, $ex[1], array_fill(0, $ex[0], 0) ); // 转为灰阶图像 foreach($gray as $y => &$row){ foreach($row as $x => &$y){ $rgb = imagecolorat($im, $x, $y); // 根据颜色求亮度 $b = $rgb & 255; $g = ($rgb >> 8) & 255; $r = ($rgb >> 16) & 255; $y = ($r * 19595 + $g * 38469 + $b * 7472) >> 16; } } unset($row, $y); // 自动求域值 $back = 127; do{ $crux = $back; $s = $b = $l = $i = 0; foreach($gray as $row){ foreach($row as $y){ if($y < $crux){ $s += $y; $l++; }else{ $b += $y; $i++; } } } $s = $l ? floor($s / $l) : 0; $b = $i ? floor($b / $i) : 0; $back = ($s + $b) >> 1; }while($crux != $back); // 二值化 $bin = $gray; foreach($bin as &$row){ foreach($row as &$y){ $y = $y < $crux ? 0 : 1; } } return array( $gray, $bin, ); } if(empty($_get["img"])){ exit("please use $_server[script_name]?img=local/image/path"); } if(!$im = adaptivethreshold($_get["img"])){ exit("error!"); } $img = imagecreate(count($im[0][0]), count($im[0]) * 2); $rgb = array( imagecolorallocate($img, 0, 0, 0), imagecolorallocate($img, 255, 255, 255), ); $x = $y = 0; $colors = array( 0 => $rgb[0], 255 => $rgb[1] ); foreach($im[0] as $row){ do{ if(isset($colors[$row[$x]])){ $c = $colors[$row[$x]]; }else{ $c = $colors[$row[$x]] = imagecolorallocate($img, $row[$x], $row[$x], $row[$x]); } // imagesetpixel($img, $x, $y, $rgb[$row[$x] < 128 ? 0 : 1]); imagesetpixel($img, $x, $y, $c); }while(isset($row[++$x])); $x = 0; $y++; } foreach($im[1] as $row){ do{ imagesetpixel($img, $x, $y, $rgb[$row[$x]]); }while(isset($row[++$x])); $x = 0; $y++; } header("content-type: image/gif"); imagegif($img);
以上就是图片灰度和二值化处理的内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product