圖形辨識~尋寶遊戲

更新 發佈閱讀 21 分鐘
raw-image

構想上,前端簡單的使用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("檔案不存在。")
raw-image

原本打算用SQL處理,不過有點懶...所以就用文字檔的方式處理...以後有空在搞囉~




留言
avatar-img
MJ的沙龍
43會員
136內容數
獨立遊戲開發紀錄
MJ的沙龍的其他內容
2025/04/12
🗓 Steam 上市日期:2025/4/28 | 🖤 加入願望清單:https://store.steampowered.com/app/3634400/Elara/ 「他們說我太敏感,說我不合群。 但我只是——不想學會沉默。」 —Elara Quinn 你是否曾經在工作時,感
Thumbnail
2025/04/12
🗓 Steam 上市日期:2025/4/28 | 🖤 加入願望清單:https://store.steampowered.com/app/3634400/Elara/ 「他們說我太敏感,說我不合群。 但我只是——不想學會沉默。」 —Elara Quinn 你是否曾經在工作時,感
Thumbnail
2025/03/05
在靈異頻發的醫院夜班,小護士林筱筱意外發現她的冷酷上司——蘇醫生,竟然早已死亡五年,從此她與這位神秘的「鬼醫生」攜手處理靈異事件,並在驚魂不斷的夜班中逐漸建立起一段超越生死的羈絆。
Thumbnail
2025/03/05
在靈異頻發的醫院夜班,小護士林筱筱意外發現她的冷酷上司——蘇醫生,竟然早已死亡五年,從此她與這位神秘的「鬼醫生」攜手處理靈異事件,並在驚魂不斷的夜班中逐漸建立起一段超越生死的羈絆。
Thumbnail
2025/02/24
這是一篇懸疑驚悚小說,描述女主角江語珊調查一起離奇命案的故事。死者林曦是一位心理學教授,死於自家公寓,現場佈滿鏡子,死者嘴角帶著詭異的微笑。語珊在調查過程中發現,此案與一種名為「鏡像侵蝕」的心理現象有關,並逐漸被捲入其中。
Thumbnail
2025/02/24
這是一篇懸疑驚悚小說,描述女主角江語珊調查一起離奇命案的故事。死者林曦是一位心理學教授,死於自家公寓,現場佈滿鏡子,死者嘴角帶著詭異的微笑。語珊在調查過程中發現,此案與一種名為「鏡像侵蝕」的心理現象有關,並逐漸被捲入其中。
Thumbnail
看更多
你可能也想看
Thumbnail
在 vocus 與你一起探索內容、發掘靈感的路上,我們又將啟動新的冒險——vocus App 正式推出! 現在起,你可以在 iOS App Store 下載全新上架的 vocus App。 無論是在通勤路上、日常空檔,或一天結束後的放鬆時刻,都能自在沈浸在內容宇宙中。
Thumbnail
在 vocus 與你一起探索內容、發掘靈感的路上,我們又將啟動新的冒險——vocus App 正式推出! 現在起,你可以在 iOS App Store 下載全新上架的 vocus App。 無論是在通勤路上、日常空檔,或一天結束後的放鬆時刻,都能自在沈浸在內容宇宙中。
Thumbnail
vocus 慶祝推出 App,舉辦 2026 全站慶。推出精選內容與數位商品折扣,訂單免費與紅包抽獎、新註冊會員專屬活動、Boba Boost 贊助抽紅包,以及全站徵文,並邀請你一起來回顧過去的一年, vocus 與創作者共同留下了哪些精彩創作。
Thumbnail
vocus 慶祝推出 App,舉辦 2026 全站慶。推出精選內容與數位商品折扣,訂單免費與紅包抽獎、新註冊會員專屬活動、Boba Boost 贊助抽紅包,以及全站徵文,並邀請你一起來回顧過去的一年, vocus 與創作者共同留下了哪些精彩創作。
Thumbnail
這篇文章介紹了網站的整體架構以及開發時所使用的工具和套件,包括 Next.js、Tailwind CSS 和 socket.io 等。文章回顧了程式碼的重構與優化,幫助開發者提高工作效率,適合希望深入瞭解前端開發和網站架構的讀者。
Thumbnail
這篇文章介紹了網站的整體架構以及開發時所使用的工具和套件,包括 Next.js、Tailwind CSS 和 socket.io 等。文章回顧了程式碼的重構與優化,幫助開發者提高工作效率,適合希望深入瞭解前端開發和網站架構的讀者。
Thumbnail
最近有專案需求要在 Web 上進行一個掃描條碼辨識的動作,做了一些功課,有 Open Source 方案跟商業解決方案,整理起來分享給大家。
Thumbnail
最近有專案需求要在 Web 上進行一個掃描條碼辨識的動作,做了一些功課,有 Open Source 方案跟商業解決方案,整理起來分享給大家。
Thumbnail
這個教學是關於探索地圖的教學 教學包含了 使用 imagemap 出現提示 建立可互動式地圖 解謎系統 設定 / 使用變量 根據成功或失敗出現對應的畫面 這篇會稍微比較長也比較複雜ㄧ點如果中間有甚麼不懂的歡迎私訊我!
Thumbnail
這個教學是關於探索地圖的教學 教學包含了 使用 imagemap 出現提示 建立可互動式地圖 解謎系統 設定 / 使用變量 根據成功或失敗出現對應的畫面 這篇會稍微比較長也比較複雜ㄧ點如果中間有甚麼不懂的歡迎私訊我!
Thumbnail
構想上,前端簡單的使用Google Map 做定位,並寫入SQL做第一段比對經緯度。接著前端有一個php上傳圖片的功能(沒有 https 所以就不做網頁開相機的方式)。經過上傳至伺服器後,python 圖形辨識,比對上傳的圖片,若比對成功或相似度差異不大,則判定正確,寫入SQL,端頁面顯示奪寶成功。
Thumbnail
構想上,前端簡單的使用Google Map 做定位,並寫入SQL做第一段比對經緯度。接著前端有一個php上傳圖片的功能(沒有 https 所以就不做網頁開相機的方式)。經過上傳至伺服器後,python 圖形辨識,比對上傳的圖片,若比對成功或相似度差異不大,則判定正確,寫入SQL,端頁面顯示奪寶成功。
Thumbnail
一個網頁只會有一個h1 標籤(h1.p.img)裡面可以放多個屬性(src.background.color) 建立 HTML 環境 告訴大家這是html5的語法 關於整個專案的資訊放這裡面 頁籤標題 寫給別人看的要放這裡面 Emmet 預設安裝 /*語意使用英文*/ /*使
Thumbnail
一個網頁只會有一個h1 標籤(h1.p.img)裡面可以放多個屬性(src.background.color) 建立 HTML 環境 告訴大家這是html5的語法 關於整個專案的資訊放這裡面 頁籤標題 寫給別人看的要放這裡面 Emmet 預設安裝 /*語意使用英文*/ /*使
Thumbnail
GCP: API和服務 -> 資訊主頁 -> +啟用API和服務 搜尋google+ 啟用: 設定 OAuth 同意畫面: 選擇外部後,開始填寫資料: 建立憑證: 假如有多個應用程式平台,如網頁、app,都要各自建立OAuth用戶。 已授權的重新導向URI: 使用者透過 G
Thumbnail
GCP: API和服務 -> 資訊主頁 -> +啟用API和服務 搜尋google+ 啟用: 設定 OAuth 同意畫面: 選擇外部後,開始填寫資料: 建立憑證: 假如有多個應用程式平台,如網頁、app,都要各自建立OAuth用戶。 已授權的重新導向URI: 使用者透過 G
Thumbnail
JavaScript 能做許多事,尤其透過瀏覽器的 API 或套件,我們得以悠游於巨量資料中,將資料轉換為與使用者溝通的介面,以下就來分享 15 個實用的 Vanilla JS 程式碼...
Thumbnail
JavaScript 能做許多事,尤其透過瀏覽器的 API 或套件,我們得以悠游於巨量資料中,將資料轉換為與使用者溝通的介面,以下就來分享 15 個實用的 Vanilla JS 程式碼...
Thumbnail
轉移自 LogDown 原文日期 June 10, 2016 14:33  Firebase 自從被 Google 收購後,從原本的即時資料庫,擴展更多的功能。 筆者這次研究的是架站功能,雖然玩過 Google App Engine 架站,但還是想體驗一下新技術。 目前 Firebase 官方支
Thumbnail
轉移自 LogDown 原文日期 June 10, 2016 14:33  Firebase 自從被 Google 收購後,從原本的即時資料庫,擴展更多的功能。 筆者這次研究的是架站功能,雖然玩過 Google App Engine 架站,但還是想體驗一下新技術。 目前 Firebase 官方支
追蹤感興趣的內容從 Google News 追蹤更多 vocus 的最新精選內容追蹤 Google News