search
HomeBackend DevelopmentPHP Tutorial[PHP] Identify the main color of the picture_PHP tutorial

[PHP] Identify the main color of the picture_PHP tutorial

Jul 13, 2016 pm 05:53 PM
apiphponehosttwolistpictureexplainidentifyBe applicablecolor

1. Applicable scenarios: List the corresponding pictures according to color.

[PHP] Identify the main color of the picture_PHP tutorial
2. Main program and API explanation:
[php]

class MajorColor
{
//Reference color
protected $_colors = null;
       
//Tolerance
protected $_tolerance = 80;
       
//Ignored colors
protected $_ignoreColors = array();
       
//Supported image types
protected $_funcs = array('image/png' => 'imagecreatefrompng', 'image/jpeg' => 'imagecreatefromjpeg', 'image/gif' => 'imagecreatefromgif');
       
Public function __construct(array $colors = null) {
If(null !== $colors) {
$this->_colors = $colors;
         } 
}  
       
Public function setColors(array $colors) {
          $this->_colors = $colors;
}  
       
Public function setTolerance($tolerance) {
          $this->_tolerance = $tolerance;
}  
       
Public function setIgnoreColors($colors) {
          $this->_ignoreColors = $colors;
}  
       
Public function _isValidColor($confVal, $val) {
If(is_array($confVal)) {
                 return $val >= $confVal[0] && $val          } else {
                   return $val >= $confVal - $this->_tolerance && $val _tolerance;
         } 
}  
       
Public function getOrderedColors($pic) {
$size = getimagesize($pic);
If(!$size) {
              return false;
         } 
                                   
         $width = $size[0];
         $height = $size[1];
         $mime = $size['mime'];
$func = isset($this->_funcs[$mime]) ? $this->_funcs[$mime] : null;
If(!$func) {
              return false;
         } 
                                   
          $im = $func($pic);
If(!$im) {
              return false;
         } 

          $total = $width * $height;
         $nums = array();
for($i = 0; $i for($m = 0; $m $color_index = imagecolorat($im, $i, $m);
                     $color_tran = imagecolorsforindex($im, $color_index);
                   $alpha = $color_tran['alpha'];
                unset($color_tran['alpha']); 
                if(100 _ignoreColors)) { 
                    continue; 
                } 
 
                foreach ($this->_colors as $colorid => $color) { 
                    if($this->_isValidColor($color['red'], $color_tran['red']) 
                        && $this->_isValidColor($color['green'], $color_tran['green']) 
                        && $this->_isValidColor($color['blue'], $color_tran['blue']) 
                    ) { 
                        $nums[$colorid] = isset($nums[$colorid]) ? $nums[$colorid] + 1 : 1; 
                    } 
                } 
            } 
        } 
         
        imagedestroy($im); 
        arsort($nums); 
        return $nums; 
    } 
     
    public function getMajorColor($pic) { 
        $nums = $this->getOrderedColors($pic); 
        $keys = array_keys($nums); 
        return $keys[0]; 
    } 

1.void setColors(array $colors)
设置可选颜色,即上图中“全部颜色”下的所有颜色(白、灰、黑...)

2.void setTolerance(int $tolerance)
设置容差,比如绿色的RGB值为(0,255,0),如果设置容差为40,那么-40 此方法用于大致区别各颜色。

3.void setIgnoreColors(array $colors)
设置不需考虑的颜色。如大多图片的背景是白色,而我们显然不希望结果是白色,此时可调用此方法简略白色。

4.array getOrderedColors($pic)
根据$pic获取各种颜色(用setColors设置的颜色)的匹配数量,按匹配量由高到低排列
参数$pic是待检测图片的路径

5.mix getMajorColor($pic)
内部调用getOrderedColors,返回匹配量最高的颜色的key

三、$colors的格式及范围确定
1.如果$colors中的各种颜色差别很明显,我们只需简单的传入颜色值,内部会根据setTolerance设置的容差来区别各颜色。
[php] 
$colors = array( 
    1 => array('red' => 0xff, 'green' => 0xff, 'blue' => 0xff), 
    2 => array('red' => 0xc0, 'green' => 0xc0, 'blue' => 0xc0), 
    2 => array('red' => 0x00, 'green' => 0x00, 'blue' => 0x00), 
); 


2. The setTolerance method of setting tolerance can only roughly distinguish various colors. If you need more precise control, you need to set the R, G, and B ranges of a certain color respectively www.2cto.com
[php]
$colors = array(
1 => array('red' => array(189, 230), 'green' => array(189, 230), 'blue' => array(189, 230)),
2 => array('red' => array(0, 37), 'green' => array(0, 37), 'blue' => array(0, 37)),
3 => array('red' => array(128, 255), 'green' => array(0, 76), 'blue' => array(0, 100)),
);
A series of fine-tuning is required until the various colors are clearly distinguishable.
Author: xiaodao1986

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/478033.htmlTechArticle1. Applicable scenarios: List the corresponding pictures according to color. 2. Main program and API explanation: [php] ?php class MajorColor { //Reference colors protected $_colors = null; //Tolerance protected...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Atom editor mac version download

Atom editor mac version download

The most popular open source editor