Home Backend Development PHP Tutorial PHP image recognition technology principle and implementation

PHP image recognition technology principle and implementation

Jun 08, 2018 pm 03:36 PM
php image number identify

This article mainly introduces the principle and implementation of PHP image recognition technology. This password verification that is usually done has the same purpose. If you need it, you can learn more.

In fact, image recognition technology is no different from the password verification we usually do. The data to be verified is put into the database in advance, and then the entered (recognized) data is compared with the data in the database when used. Data comparison, but image recognition technology has some fault tolerance, and our usual password verification must match 100%.

A few days ago, a friend talked about making a game to click on the lottery and identify the text in the picture. At that time, what immediately came to mind was js control or flash as a mask layer. I feel that this method is the most convenient, quick and effective. And it saves server resources, but the request there is to recognize the text in the image through PHP.

By coincidence, the news in those two days included: 1. Jack Ma’s face recognition payment; 2. 12306 used a new verification code, saying that no domestic ticket grabbing software can be used now, and it was banned within a day of its release. Crack. Then it happened that I read an article on Java image recognition technology that morning. So I thought about taking a look at PHP's image recognition technology.

In fact, the so-called image recognition is no longer a new technology. At least the information I found was from a long time ago. It's just that I have never been involved in this aspect of work, so I have never seen it.

Let’s first talk about the requirements of this experiment: There is a picture with three numbers in three positions, and it is required to extract the value of the number in the corresponding position. (Sharp-eyed students may see that the code below is someone else’s that I took. Yes, I copied it directly from others and deleted it. After all, I have only scratched the surface of this, and I will eventually post the original author’s initial code)

class gjPhone
{

  protected $imgPath; // 图片路径
  protected $imgSize; // 图片大小
  protected $hecData; // 分离后数组
  protected $horData; // 横向整理的数据
  protected $verData; // 纵向整理的数据
  function __construct ($path)
  {
    $this->imgPath = $path;
  }

  public function getHec ()
  {
    $size = getimagesize($this->imgPath);
    $res = imagecreatefrompng($this->imgPath);
    for ($i = 0; $i < $size[1]; ++ $i) {
      for ($j = 0; $j < $size[0]; ++ $j) {
        $rgb = imagecolorat($res, $j, $i);
        $rgbarray = imagecolorsforindex($res, $rgb);
        if ($rgbarray[&#39;red&#39;] < 125 || $rgbarray[&#39;green&#39;] < 125 ||
             $rgbarray[&#39;blue&#39;] < 125) {
          $data[$i][$j] = 1;
        } else {
          $data[$i][$j] = 0;
        }
      }
    }
    $this->imgSize = $size;
    $this->hecData = $data;
  }

  public function magHorData ()
  {
    $data = $this->hecData;
    $size = $this->imgSize;
    $z = 0;
    for ($i = 0; $i < $size[1]; ++ $i) {
      if (in_array(&#39;1&#39;, $data[$i])) {
        $z ++;
        for ($j = 0; $j < $size[0]; ++ $j) {
          if ($data[$i][$j] == &#39;1&#39;) {
            $newdata[$z][$j] = 1;
          } else {
            $newdata[$z][$j] = 0;
          }
        }
      }
    }
    return $this->horData = $newdata;
  }

  public function showPhone ($ndatas)
  {
    error_reporting(0);
    $phone = null;
    $d = 0;
    foreach ($ndatas as $key => $val) {
      if (in_array(1, $val)) {
        foreach ($val as $k => $v) {
          $ndArr[$d] .= $v;
        }
      }
      if (! in_array(1, $val)) {
        $d ++;
      }
    }
    foreach ($ndArr as $key01 => $val01) {
      $phone .= $this->initData($val01);
    }
    return $phone;
  }

  /**
   * 初始数据
   */
  public function initData ($numStr)
  {
    $result = null;
    $data = array(
        &#39;1&#39; => &#39;00000000111000000000000001110000000001001000100000000010100011000000000011000110000000000110000100000000010110011000000&#39;,
        &#39;5&#39; => &#39;00000000001000000000000000010000000000100100100000000000101001110000000000100000110000000011000000100000001101000010000&#39;,
        &#39;10&#39; => &#39;00000011100011100000000011001100100100100010010001000110000100100010001100001001000100011000010010001001001001100010100&#39;
    );
    foreach ($data as $key => $val) {
      similar_text($numStr, $val, $pre);
      if ($pre > 95) { // 相似度95%以上
        $result = $key;
        break;
      }
    }
    return $result;
  }
}

$imgurl = &#39;jd.png&#39;;
list ($width, $heght, $type, $attr) = getimagesize($imgurl);
$new_w = 17;
$new_h = 11;
$thisimage = imagecreatetruecolor($new_w, $new_h); // $new_w, $new_h 为裁剪后的图片宽高
$background = imagecolorallocate($thisimage, 255, 255, 255);
imagefilledrectangle($thisimage, 0, 0, $new_w, $new_h, $background);
$oldimg = imagecreatefrompng($imgurl); // 载入原始图片
                    
// 首先定位要取图的位置(这里可以通过前端js或者其他手段定位,由于我这是测试,所以就ps定位并写死了)
$weizhi = array(
    &#39;1&#39; => 165,
    &#39;5&#39; => 308,
    &#39;10&#39; => 456
);

foreach ($weizhi as $wwzz) {
  $src_y = 108;
  imagecopy($thisimage, $oldimg, 0, 0, $wwzz, $src_y, $new_w, $new_h); // $src_y,$new_w为原图中裁剪区域的左上角坐标拷贝图像的一部分将src_im图像中坐标从src_x,src_y开始,宽度为src_w,高度为src_h的一部分拷贝到dst_im图像中坐标为dst_x和dst_y的位置上。
  $tem_png = &#39;tem_1.png&#39;;
  imagepng($thisimage, __DIR__ . &#39;/&#39; . $tem_png); // 通过定位从原图中copy出想要识别的位置并生成新的缓存图,用以后面的图像识别类使用。
  
  $gjPhone = new gjPhone($tem_png); // 实例化类
  $gjPhone->getHec(); // 进行图像像素分离
  $horData = $gjPhone->magHorData(); // 将分离出是数据转成01表示的图像、这里可以根据自己喜好定
  $phone = $gjPhone->showPhone($horData); // 将转换好的01表示的数据与库中的数据进行匹配,匹配度95以上就算成功,库这里由于是做测试就直接写了数组
  echo &#39;| &#39; . $phone . &#39; | &#39;;
}
Copy after login

From this point of view, it is actually excusable and unnecessary for the 12306 verification code to be cracked That's enough verbal and written criticism. Just keep grabbing the verification code images and convert them into data readable by your own program and store them in the database, and then match them during verification. Then Alibaba’s face recognition payment principle can be considered understood, but they may be very sophisticated in what they do.

In front-end time, I saw a verification code form of Alibaba Cloud. I thought it might be better at first. But now it seems that as long as you are willing, it can actually be cracked.

#Okay, here is the original code.

/**
 * 电话号码识别.
 * @author by zsc for 2010.03.24
 */
class gjPhone
{

  protected $imgPath; // 图片路径
  protected $imgSize; // 图片大小
  protected $hecData; // 分离后数组
  protected $horData; // 横向整理的数据
  protected $verData; // 纵向整理的数据
  function __construct ($path)
  {
    $this->imgPath = $path;
  }

  /**
   * 颜色分离转换...
   *
   * @param unknown_type $path      
   * @return unknown
   */
  public function getHec ()
  {
    $size = getimagesize($this->imgPath);
    $res = imagecreatefrompng($this->imgPath);
    for ($i = 0; $i < $size[1]; ++ $i) {
      for ($j = 0; $j < $size[0]; ++ $j) {
        $rgb = imagecolorat($res, $j, $i);
        $rgbarray = imagecolorsforindex($res, $rgb);
        if ($rgbarray[&#39;red&#39;] < 125 || $rgbarray[&#39;green&#39;] < 125 ||
             $rgbarray[&#39;blue&#39;] < 125) {
          $data[$i][$j] = 1;
        } else {
          $data[$i][$j] = 0;
        }
      }
    }
    $this->imgSize = $size;
    $this->hecData = $data;
  }

  /**
   * 颜色分离后的数据横向整理...
   *
   * @return unknown
   */
  public function magHorData ()
  {
    $data = $this->hecData;
    $size = $this->imgSize;
    $z = 0;
    for ($i = 0; $i < $size[1]; ++ $i) {
      if (in_array(&#39;1&#39;, $data[$i])) {
        $z ++;
        for ($j = 0; $j < $size[0]; ++ $j) {
          if ($data[$i][$j] == &#39;1&#39;) {
            $newdata[$z][$j] = 1;
          } else {
            $newdata[$z][$j] = 0;
          }
        }
      }
    }
    return $this->horData = $newdata;
  }

  /**
   * 整理纵向数据...
   *
   * @return unknown
   */
  public function magVerData ($newdata)
  {
    for ($i = 0; $i < 132; ++ $i) {
      for ($j = 1; $j < 13; ++ $j) {
        $ndata[$i][$j] = $newdata[$j][$i];
      }
    }
    
    $sum = count($ndata);
    $c = 0;
    for ($a = 0; $a < $sum; $a ++) {
      $value = $ndata[$a];
      if (in_array(1, $value)) {
        $ndatas[$c] = $value;
        $c ++;
      } elseif (is_array($ndatas)) {
        $b = $c - 1;
        if (in_array(1, $ndatas[$b])) {
          $ndatas[$c] = $value;
          $c ++;
        }
      }
    }
    
    return $this->verData = $ndatas;
  }

  /**
   * 显示电话号码...
   *
   * @return unknown
   */
  public function showPhone ($ndatas)
  {
    $phone = null;
    $d = 0;
    foreach ($ndatas as $key => $val) {
      if (in_array(1, $val)) {
        foreach ($val as $k => $v) {
          $ndArr[$d] .= $v;
        }
      }
      if (! in_array(1, $val)) {
        $d ++;
      }
    }
    foreach ($ndArr as $key01 => $val01) {
      $phone .= $this->initData($val01);
    }
    return $phone;
  }

  /**
   * 分离显示...
   *
   * @param unknown_type $dataArr      
   */
  function drawWH ($dataArr)
  {
    if (is_array($dataArr)) {
      foreach ($dataArr as $key => $val) {
        foreach ($val as $k => $v) {
          if ($v == 0) {
            $c .= "<font color=&#39;#FFFFFF&#39;>" . $v . "</font>";
          } else {
            $c .= $v;
          }
        }
        $c .= "<br/>";
      }
    }
    echo $c;
  }

  /**
   * 初始数据...
   *
   * @param unknown_type $numStr      
   * @return unknown
   */
  public function initData ($numStr)
  {
    $result = null;
    $data = array(
        0 => &#39;000011111000001111111110011000000011110000000001110000000001110000000001110000000001011000000011011100000111000111111100000001110000&#39;,
        1 => &#39;011000000000011000000000111111111111111111111111&#39;,
        2 => &#39;001000000011011000000111110000001101110000011001110000011001110000110001111001100001011111100001000110000001&#39;,
        3 => &#39;001000000010011000000011110000000001110000000001110000110001110000110001011001110011011111011111000110001100&#39;,
        4 => &#39;000000001100000000111100000001111100000011101100000111001100001100001100011000001100111111111111111111111111000000001100000000000100&#39;,
        5 => &#39;111111000001111111000001110001000001110001000001110001100001110001100001110000110011110000111111000000001100&#39;,
        6 => &#39;000011111000001111111110011000110011110001100001110001100001110001100001110001100001010001110011010000111111000000001100&#39;,
        7 => &#39;110000000000110000000111110000111111110001110000110111000000111100000000111000000000111000000000&#39;,
        8 => &#39;000100011110011111111111110011100001110001100001110001100001110001100001110011100001011111111111000100011110&#39;,
        9 => &#39;001111000000011111100001110000110001110000110001110000110001110000110001011000100001011111100111000111111110000001110000&#39;
    );
    foreach ($data as $key => $val) {
      similar_text($numStr, $val, $pre);
      if ($pre > 95) { // 相似度95%以上
        $result = $key;
        break;
      }
    }
    return $result;
  }
}

$imgPath = "http://bj.ganji.com/tel/5463013757650d6c5e31093e563c51315b6c5c6c5237.png";
$gjPhone = new gjPhone($imgPath);
// 进行颜色分离
$gjPhone->getHec();
// 画出横向数据
$horData = $gjPhone->magHorData();
echo "===============横向数据==============<br/><br/><br/>";
$gjPhone->drawWH($horData);
// 画出纵向数据
$verData = $gjPhone->magVerData($horData);
echo "<br/><br/><br/>===============纵向数据==============< br/><br/><br/>";
$gjPhone->drawWH($verData);

// 输出电话
$phone = $gjPhone->showPhone($verData);
echo "<br/><br/><br/>===============电话==============<br /><br/><br/>" . $phone;
Copy after login

The above is the entire content of this article. I hope it will be helpful to everyone’s study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

Application of reflection in php

PHP uses SWOOLE extension to achieve timing synchronization

PHP simple implementation of single sign-on

The above is the detailed content of PHP image recognition technology principle and implementation. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles