图片灰度和二值化处理
图片灰度和二值化处理
<?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);
登入後複製
以上就是图片灰度和二值化处理的内容,更多相关内容请关注PHP中文网(www.php.cn)!
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章
如何修復KB5055518無法在Windows 10中安裝?
1 個月前
By DDD
如何修復KB5055523無法在Windows 11中安裝?
1 個月前
By DDD
<🎜>:種植花園 - 完整的突變指南
3 週前
By DDD
<🎜>:泡泡膠模擬器無窮大 - 如何獲取和使用皇家鑰匙
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
如何修復KB5055612無法在Windows 10中安裝?
3 週前
By DDD

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)