顯示具有 Python 標籤的文章。 顯示所有文章
顯示具有 Python 標籤的文章。 顯示所有文章

2022年4月15日 星期五

Python-Face Recognition-人臉辨識-使用 NB Webcam

 2022-4-15 撰寫文章 

  • (其實累積了Tibame 2021年的OpenCV 物流檢測課程 + 網路IThome + 市場上書本)

A.環境: (相關資訊 進入python 用help( ) 函數查)

  • 硬體:ASUS VivoBook Core i5 10th GEN ,NB 型號:X413FA(MGF:Y2020)
  • Python 版本 3.7.9  64
    •  (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] on win32
  • face_recongition VERSION 
    •    1.2.3 PACKAGE CONTENTS
    •     api
    •     face_detection_cli
    •     face_recognition_cli
  • Visual Studio 2022 C++ (選項)
  • Cmake VERSION  3.22.3

  • dlib
  • OpenCV (cv2) opencv_version = '4.5.1.48'
help 使用說明文件:I
f this is your first time using Python, you should definitely check out
the tutorial on the Internet at 
https://docs.python.org/3.7/tutorial/

B.注意事項:

  • Python 請安裝合適的版本與位元(目前NB應該都是64位元)
  • 必須安裝 Cmake,Visual C++,OpenCV
  • 圖片檔案名稱大小寫,包含主檔名跟副檔名(ex: biden.jpg 跟biden.JPG可能會有錯誤)
  • 圖片存放路徑可以直接放在與 撰寫的python 程式檔(ex: Test.py)同一個folder路徑下
  • 程式有兩個python檔 =>每次新增圖片先用encoding訓練完,然後再用主程式測試
  •  建議有兩三張圖片,其中一張可以用來做測試,最好不同時期拍的照片或情境差距的照片

圖片資料:

  • 準備obama.jpg ,biden.jpg....等等可以先選三個人然後下載圖片.
  • 拿一張盡量臉部較明顯且解析好的拿來當訓練資料的圖.
  • 要增加圖,也要增加大括號裡面的圖名資料(如黃底)如下新增一個Tony.jpg:

 }, # 這個接在前面大括號的逗點別忘了.

    {

        "name": "Tony",

        "filename": "Tony.jpg",

        "face_encoding": None      

    }

主程式Code: findfaces_webcam.py

------------------------------------------------------------------------將以下拷貝

# Step 1 

# 需要先安装cmake

# CMake must be installed to build the following extensions: dlib


# 否則安裝 face_recognition 出現以下的 問題

#   × Running setup.py install for dlib did not run successfully.

#   │ exit code: 1

#   ╰─> [8 lines of output]

#       running install

#       running build

#       running build_py

#       package init file 'tools\python\dlib\__init__.py' not found (or not a regular file)

#       running build_ext

#       ERROR: CMake must be installed to build dlib

#       [end of output]


# Step2:

# 裝完 cmake 還得裝 Visual C++ 

# 否則 出現以下訊息.

# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!



# You must use Visual Studio to build a python extension on windows.  If you

# are getting this error it means you have not installed Visual C++.  Note

# that there are many flavors of Visual Studio, like Visual Studio for C#

# development.  You need to install Visual Studio for C++.



# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!


# 然後裝完 Visual C++ 重新開機

# 最後安裝 face_recognition


# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

# Using legacy 'setup.py install' for dlib, since package 'wheel' is not installed.

# Installing collected packages: dlib, face_recognition

#   Running setup.py install for dlib ... done

# Successfully installed dlib-19.23.1 face_recognition-1.3.0

# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!



import face_recognition  

import cv2

import numpy as np

import pickle


with open("faces_encoding.dat", "rb") as f:

    known_face_list = pickle.load(f)    

known_face_encodings = [data["face_encoding"] for data in known_face_list]


cap = cv2.VideoCapture(0)

while True:

    ret, frame = cap.read()

    rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

    face_locations = face_recognition.face_locations(rgb_frame)

    face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)

    for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):

        face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)

        best_match_index = np.argmin(face_distances)

        if face_distances[best_match_index] < 0.5:  ### 準確度距離改這段

            name = known_face_list[best_match_index]["name"]

        else:

            name = "Unknown"


        #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!畫框框標示

        #畫一個boarder=2 紅方框(0,0,255)    

        cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)

        # 畫一個填滿的實框

        cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED) 

        # 填入文字

        cv2.putText(frame, name, (left + 6, bottom - 6), cv2.FONT_HERSHEY_DUPLEX, 1.0, (255, 255, 255), 1)

    #顯示出來 辨識結果    

    cv2.imshow('Video', frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):

        break


cap.release()

cv2.destroyAllWindows()



# !!!!!!!!!!!!!!      Tip 技巧:

# !!!!!!!!!!!!!!(1) 测试tolerance=0.5或0.4比较合适==> Tony 實測,覺得 distacne 0.5 真的好點

# !!!!!!!!!!!!!!(2) 可以用臉部大圖做訓練圖

# !!!!!!!!!!!!!!(3) 如果只是要拍照做人臉辨識(打卡)可以先關掉持續偵測減少負載,用靜態擷取的再做比對(亮燈擷取)

# !!!!!!!!!!!!!!!!   =>輸出判斷是誰的時候,可以用三張或多張圖同時聯集相似, 然後判斷是哪個人

# !!!!!!!!!!!!!!(4) 鏡頭解析度可以增高

# !!!!!!!!!!!!!!(5) 對函數作調參

# !!!!!!!!!!!!!!(6) 對webcam capture 的影像作適當前處理 新增成另一張,多一張 不同層次的圖像 比對 

# !!!!!!!!!!!!!!(7) 更準確的識別,可以設定重新採樣的次數,face_encodings 傳入 num_jitters 來實作,預設 0,範圍可設定 0-100,越高越準,但速度越慢,等比例慢(差距100倍?)

2021年9月21日 星期二

Python抓取天氣資料+Line Notify 通知

參考範例知識庫:

1:天氣查詢API介面 :
https://opendata.cwb.gov.tw/devManual/insrtuction?fbclid=IwAR1zwO-DgQW9Ot0E9pyUaKkwCxRix1E4EJpueBN_9chxPpYXbSI4DTrLvyE

用的是第3:

3.資料擷取-使用說明及目前開放資料擷取之氣象資料 線上API使用說明


2:Line Notify 連動程式碼 & Token 申請與 網路設定
https://ithelp.ithome.com.tw/articles/10223413

3:Dict 字典取值
https://www.runoob.com/python/att-dictionary-get.html

4:日期操作:
https://ithelp.ithome.com.tw/articles/10235251

天氣查詢工作事項:
申請帳號,獲得token key,填入 Authorization= 的後面 ,把XXX-XXX 取代掉.
url="https://opendata.cwb.gov.tw/api/v1/rest/datastore/F-C0032-001?Authorization=XXX-XXX&limit=1&elementName=Wx&format=JSON&locationName="

字典取值工作事項:
必須知道自己要取那些值,字典跟JSON格式的 Dict 與list 交換穿插的解讀

日期操作工作事項:
把日期值簡化

程式碼 注意事項:
1.注意 locationName之查詢城市是要 用輸入的或是預定的
2.要查那些資料先從requests 回饋資訊,先讀一次再 拆解JSON,擷取自己要的,過多的話可以先取第一個,再適當放大資料數。
3.程式分成 兩個def 模組,一個是get_weather 進行Request 取值,一個是 LineNotifyMessage 通知LineBOT
4.有兩個Token key 要先獲得,一個是 氣象查詢的,一個是Line Notify.

程式碼:

import requests

import json

import time

def get_weather():


# cityname=input("輸入天氣查詢城市")

#   F-C0032-001 是要查詢的資料種類,分類請查裝央氣象局對照表

cityname="桃園市"

# url 是來自中央氣象局給的 wbe query 網址, authorization 後面xxxxx...填入氣象局給你的授權碼..後面參數格式請查中央氣象局資料網站有說明.

url="https://opendata.cwb.gov.tw/api/v1/rest/datastore/F-C0032-001?Authorization=XXX-XXX&limit=1&elementName=Wx&format=JSON&locationName="

city_url=url + cityname

res=requests.get(city_url).text

# print(res)

res=json.loads(res)

a=res["records"]["location"][0]["locationName"]

b=res["records"]["location"][0]["weatherElement"][0]['time'][0]

c=res["records"]["location"][0]["weatherElement"][0]['time'][1]

d=res["records"]["location"][0]["weatherElement"][0]['time'][2]

k=res["records"]["datasetDescription"]

l=b["parameter"]["parameterName"]

# print("res 是何種資料結構 : ",type(res))

# print("a=",a)

# print("b=",b)

# print("c=",c)

# print("d=",d)

# print("K=",k)

# print("b類別=:",type(b))

# print("天氣 :" ,l)

bmsg=b.get("startTime") + "至\n" + b.get("endTime") + ":\n" + l

cmsg=c.get("startTime") + "至\n" + c.get("endTime") + ":\n" + c["parameter"]["parameterName"]

dmsg=d.get("startTime") + "至\n" + d.get("endTime") + ":\n" + d["parameter"]["parameterName"]

Tmsg="\n"+a+"\n"+ k + "\n"+ bmsg+ "\n"+ "\n" +cmsg +"\n"+'\n'+dmsg

# print("Tmsg=",Tmsg)

return Tmsg  #回傳值給msg

#------------------------------------------line 通知 的模組

def lineNotifyMessage(token, msg):

    headers = {

        "Authorization": "Bearer " + token, 

        "Content-Type" : "application/x-www-form-urlencoded"

    }


    payload = {'message': msg}

    r = requests.post("https://notify-api.line.me/api/notify", headers = headers, params = payload)

    return r.status_code


msg = get_weather()

token = '填入line給你的token 一長串字碼'

print("傳給line的msg=\n",msg)

#get_weather()

lineNotifyMessage(token,msg)