2022-11-21|閱讀時間 ‧ 約 20 分鐘

圖形辨識~尋寶遊戲

系統架構
系統架構
構想上,前端簡單的使用Google Map 做定位,並寫入SQL做第一段比對經緯度。接著前端有一個php上傳圖片的功能(沒有 https 所以就不做網頁開相機的方式)。經過上傳至伺服器後,python 圖形辨識,比對上傳的圖片,若比對成功或相似度差異不大,則判定正確,寫入SQL,端頁面顯示奪寶成功。Firebase部分則為即時聊天(有空在搞...)

前端頁面 index.php

<!DOCTYPE html>
<html>
  <head>
    <title>尋寶遊戲</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }

#bg{
    position:absolute;
    left:0px;
    top:0px;
    z-index:9;
	 margin:0px auto;
	 width:200px;
	 height:140px;
	 display: flex;
    /* 水平置中 */
    justify-content: center;    
    /* 垂直置中 */
    align-items: center; 
	 background:rgba(0,255,204,0.2);
	 border-style:dotted;
	 border-color:#FF0000;
	 padding:1px;
}
#cc{
    z-index:99;
}

    </style>
  </head>
  <body>
  <?
  if (isset($_GET["a"]) && $_GET["a"]=="ok")
  {
  ?>
    <div id="bg">
		<div id="cc"><b>找到了~</b></div>
	 </div>
	<?
  }
  
  if (isset($_GET["a"]) && $_GET["a"]=="ng")
  {
	?>
    <div id="bg">
		<div id="cc"><b>沒找到唷~</b></div>
	 </div>
	<?
  }
	?>
    <div id="map"></div>
    <script>
      // Note: This example requires that you consent to location sharing when
      // prompted by your browser. If you see the error "The Geolocation service
      // failed.", it means you probably did not give permission for the browser to
      // locate you.
      var map, infoWindow;
	  var la,lo;
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: -34.397, lng: 150.644},
          zoom: 18
        });
		
		/*
		var contentString = 'lat: '+la+' , '+'lon: '+lo;
        //infoWindow = new google.maps.InfoWindow;
		
		  infowindow = new google.maps.InfoWindow({
          content: contentString
        });
		*/
		
        // Try HTML5 geolocation.
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function(position) {
            var pos = {
              lat: position.coords.latitude,
              lng: position.coords.longitude
            };
			
			la=position.coords.latitude;
			lo=position.coords.longitude;
			contentString = '<div>尋寶Game</div>'+
			'<form method="post" enctype="multipart/form-data" action="upload.php">'+
			'<input name="file" type="file"><input name="upload" type="submit" value="上傳">'+
			'</form>'+
			'lat: '+la+' , '+'lon: '+lo;
			
			infowindow = new google.maps.InfoWindow({
			 content: contentString
			});
			
			var marker = new google.maps.Marker({
                    position: pos,
                    //icon:'marker.png',
                    map: map
                });
				marker.addListener('click', function() {
				infowindow.open(map, marker);
				});
				map.setZoom(17);
                map.setCenter(pos);
				
            //infoWindow.setPosition(pos);
            //infoWindow.setContent('Location found.');
            //infoWindow.open(map);
            //map.setCenter(pos);
          }, function() {
            handleLocationError(true, infoWindow, map.getCenter());
          });
        } else {
          // Browser doesn't support Geolocation
          handleLocationError(false, infoWindow, map.getCenter());
        }
      }

      function handleLocationError(browserHasGeolocation, infoWindow, pos) {
        infoWindow.setPosition(pos);
        infoWindow.setContent(browserHasGeolocation ?
                              'Error: The Geolocation service failed.' :
                              'Error: Your browser doesn\'t support geolocation.');
        infoWindow.open(map);
      }
    </script>
     <script
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&v=weekly"
      defer
    ></script>
  </body>
</html>

圖檔上傳 upload.php

<?php
print_r($_POST);
print_r($_FILES);//或使用var_dump

//試著理解以下內容與差異

echo $_FILES["file"]["name"]."<br/>";	//原檔案名稱
echo $_FILES["file"]["tmp_name"]."<br/>";//暫存路徑
echo $_FILES["file"]["size"]."<br/>";//檔案byte, max 2mb,除非要改php上傳限制
echo $_FILES["file"]["type"]."<br/>";//檔案類型

//將檔案儲存到伺服器位置的方式為
//copy($_FILES["file"]["tmp_name"],"./".$_FILES["file"]["name"]); // copy(from,to)

//上傳檔案時也可以改名
//$newname=date("YmdHis")."_".$_FILES["file"]["name"];
//copy($_FILES["file"]["tmp_name"],"./".$newname); // copy(from,to)
copy($_FILES["file"]["tmp_name"],"1.jpg"); // copy(from,to)

//unlink("upload/".$newname);  //刪除網路空間內的檔案
sleep(2);
$txt_file = fopen('output.txt','r');
$line = fgets($txt_file);
fclose($txt_file);
echo $line;
header("Location: index.php?a=".$line);
?>
<!--
<form method="post" enctype="multipart/form-data">
<input type="file" name="mypic">
<input type="submit" value="上傳">
</form>-->

Python 檔案是否存在

import os

# 要檢查的檔案路徑
filepath = "0.jpg"

# 檢查檔案是否存在
if os.path.isfile(filepath):
  print("檔案存在。")
else:
  print("檔案不存在。")

安裝 Pillow

pip install Pillow

Python 圖形辨識 相似度

# -*- coding:utf-8 -*-

from functools import reduce
from PIL import Image

# 計算圖片的局部哈希值--pHash
def phash(img):
    """
    :param img: 圖片
    :return: 返回圖片的局部hash值
    """
    img = img.resize((8, 8), Image.ANTIALIAS).convert('L')
    avg = reduce(lambda x, y: x + y, img.getdata()) / 64.
    hash_value=reduce(lambda x, y: x | (y[1] << y[0]), enumerate(map(lambda i: 0 if i < avg else 1, img.getdata())), 0)
    print(hash_value)
    return hash_value

# 計算漢明距離:
def hamming_distance(a, b):
    """
    :param a: 圖片1的hash值
    :param b: 圖片2的hash值
    :return: 返回兩個圖片hash值的漢明距離
    """
    hm_distance=bin(a ^ b).count('1')
    print(hm_distance)
    return hm_distance


# 計算兩個圖片是否相似:
def is_imgs_similar(img1,img2):
    """
    :param img1: 圖片1
    :param img2: 圖片2
    :return:  True 圖片相似  False 圖片不相似
    """
    return True if hamming_distance(phash(img1),phash(img2)) <= 5 else False

if __name__ == '__main__':

    # 讀取圖片
    sensitive_pic = Image.open("0.jpg")
    target_pic = Image.open("2.jpg")

    # 比較圖片相似度
    result=is_imgs_similar(target_pic, sensitive_pic)

    print(result)

Python 偵測檔案 + 比對相似度

# -*- coding:utf-8 -*-

from functools import reduce
from PIL import Image
import os
import pymysql


# 計算圖片的局部哈希值--pHash
def phash(img):
    """
    :param img: 圖片
    :return: 返回圖片的局部hash值
    """
    img = img.resize((8, 8), Image.ANTIALIAS).convert('L')
    avg = reduce(lambda x, y: x + y, img.getdata()) / 64.
    hash_value=reduce(lambda x, y: x | (y[1] << y[0]), enumerate(map(lambda i: 0 if i < avg else 1, img.getdata())), 0)
    #print(hash_value)
    return hash_value

# 計算漢明距離:
def hamming_distance(a, b):
    """
    :param a: 圖片1的hash值
    :param b: 圖片2的hash值
    :return: 返回兩個圖片hash值的漢明距離
    """
    hm_distance=bin(a ^ b).count('1')
    #print(hm_distance)
    return hm_distance


# 計算兩個圖片是否相似:
def is_imgs_similar(img1,img2):
    """
    :param img1: 圖片1
    :param img2: 圖片2
    :return:  True 圖片相似  False 圖片不相似
    """
    return True if hamming_distance(phash(img1),phash(img2)) <= 5 else False


# 資料庫設定
db_settings = {
    "host": "127.0.0.1",
    "port": 3306,
    "user": "root",
    "password": "資料庫管理員密碼",
    "db": "test2022",
    "charset": "utf8"
}


if __name__ == '__main__':

    while True:

# 要檢查的檔案路徑
        filepath = "1.jpg"

# 檢查檔案是否存在
        if os.path.isfile(filepath):
         #print("檔案存在。")
     # 讀取圖片
         #fp = open(filepath,'rb')
         sensitive_pic = Image.open("0.jpg")
         target_pic = Image.open(filepath)
         
     # 比較圖片相似度
         result=is_imgs_similar(target_pic, sensitive_pic)
         a=result
         print(a)

         path = 'output.txt'
          
         if a==True:
          #print("ok")
          f = open(path, 'w')
          f.write('ok')
          f.close()
 
         else:
          #print("ng")
          f = open(path, 'w')
          f.write('ng')
          f.close()

          
        else:
         print("檔案不存在。")

原本打算用SQL處理,不過有點懶...所以就用文字檔的方式處理...以後有空在搞囉~
分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.