[Python趣味應用]總有人想偷看你電腦?留下證據後辦他~~

**最新文章會在我的個人網站發佈:http://www.xiaokai1999.cn/
**
這個項目在寒假前就做了,因爲當時在學校,不管是來竄宿舍的同學或者是自己宿舍裏的同學,總會有人對我的電腦產生興趣,然後偷看我的電腦。於是我就想了個辦法,記錄那些偷看過我電腦的人。

嘿嘿,接下來就是男生之間的交易了。

大概想法:
在這裏插入圖片描述

實現效果:
郵件接受效果郵件接受效果
檢測效果
語音視頻文件展示–>因爲視頻太短,上傳到bilibili並不好,可以移步我的個人博客查看

涉及到的知識點:

1.十行Python代碼實現人臉識別

2.調用百度api實現語音合成

3.如何操作email庫

1.十行Python代碼實現人臉識別

  • 使用基於Haar特徵的Cascade級聯分類器進行人臉識別(聽起來好高大上,但其實原理很簡單)

  • 用人臉識別同樣的道理,擴展到人眼識別上

  • 用opencv自帶的Harr級聯分類器進行人臉、人眼與微笑識別

啥是Harr特徵

Haar特徵包含三種:邊緣特徵、線性特徵、中心特徵和對角線特徵。每種分類器都從圖片中提取出對應的特徵。

img

Harr特徵

img

搜索人臉上的指定特徵

比如上圖中,橫的黑道將人臉中較暗的雙眼提取了出來,而豎的白道將人臉中較亮的鼻樑提取了出來。

具體想了解的同學可一曲看看這個大老講得卷積核,很細

啥是Cascade級聯分類器

基於Haar特徵的cascade級聯分類器是Paul Viola和 Michael Jone在2001年的論文”Rapid Object Detection using a Boosted Cascade of Simple Features”中提出的一種有效的物體檢測方法。

Cascade級聯分類器的訓練方法:Adaboost

級聯分類器的函數是通過大量帶人臉不帶人臉的圖片通過機器學習得到的。對於人臉識別來說,需要幾萬個特徵,通過機器學習找出人臉分類效果最好、錯誤率最小的特徵。訓練開始時,所有訓練集中的圖片具有相同的權重,對於被分類錯誤的圖片,提升權重,重新計算出新的錯誤率和新的權重。直到錯誤率或迭代次數達到要求。這種方法叫做Adaboost

在Opencv中可以直接調用級聯分類器函數。

將弱分類器聚合成強分類器

最終的分類器是這些弱分類器的加權和。之所以稱之爲弱分類器是因爲每個分類器不能單獨分類圖片,但是將他們聚集起來就形成了強分類器。論文表明,只需要200個特徵的分類器在檢測中的精確度達到了95%。最終的分類器大約有6000個特徵。(將超過160000個特徵減小到6000個,這是非常大的進步了) 。

級聯的含義:需過五關斬六將才能被提取出來

事實上,一張圖片絕大部分的區域都不是人臉。如果對一張圖片的每個角落都提取6000個特徵,將會浪費巨量的計算資源。

如果能找到一個簡單的方法能夠檢測某個窗口是不是人臉區域,如果該窗口不是人臉區域,那麼就只看一眼便直接跳過,也就不用進行後續處理了,這樣就能集中精力判別那些可能是人臉的區域。
爲此,有人引入了Cascade 分類器。它不是將6000個特徵都用在一個窗口,而是將特徵分爲不同的階段,然後一個階段一個階段的應用這些特徵(通常情況下,前幾個階段只有很少量的特徵)。如果窗口在第一個階段就檢測失敗了,那麼就直接捨棄它,無需考慮剩下的特徵。如果檢測通過,則考慮第二階段的特徵並繼續處理。如果所有階段的都通過了,那麼這個窗口就是人臉區域。
作者的檢測器將6000+的特徵分爲了38個階段,前五個階段分別有1,10,25,25,50個特徵(前文圖中提到的識別眼睛和鼻樑的兩個特徵實際上是Adaboost中得到的最好的兩個特徵)。根據作者所述,平均每個子窗口只需要使用6000+個特徵中的10個左右。

OpenCV中的Haar-cascade檢測

OpenCV 既可以作爲檢測器也可以進行機器學習訓練。如果你打算訓練自己的分類器識別任意的物品,比如車,飛機,咖啡杯等。你可以用OpenCV 創造一個。完整的細節在:Cascade Classifier Training¶中。

下面給出調用OpenCV進行基於Haar特徵的人臉和人眼Cascade級聯分類器的源代碼。

十行代碼完成人臉識別(代碼)

# 導入opencv-python
import cv2

# 讀入一張圖片,引號裏爲圖片的路徑,需要你自己手動設置
img = cv2.imread('image1.jpg',1)

# 導入人臉級聯分類器引擎,'.xml'文件裏包含訓練出來的人臉特徵
face_engine = cv2.CascadeClassifier(cv2.data.haarcascades+'haarcascade_frontalface_default.xml')
# 用人臉級聯分類器引擎進行人臉識別,返回的faces爲人臉座標列表,1.3是放大比例,5是重複識別次數
faces = face_engine.detectMultiScale(img,scaleFactor=1.3,minNeighbors=5)

# 對每一張臉,進行如下操作
for (x,y,w,h) in faces:
    # 畫出人臉框,藍色(BGR色彩體系),畫筆寬度爲2
    img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)

# 在"img2"窗口中展示效果圖
cv2.imshow('img2',img)
# 監聽鍵盤上任何按鍵,如有按鍵即退出並關閉窗口,並將圖片保存爲output.jpg
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imwrite('output.jpg',img)

img
上文引用自:https://www.jianshu.com/p/ea3c57b6c5e1

2.調用百度api實現語音合成

有些人可能會問,爲什麼不自己寫一個,而去用百度api呢?
我的回答:免費的幹嘛不用,非要去自己造輪子,
\color{red}{效率太低}

  • 目前百度api的語音合成是免費的,每天也沒有限制,想怎麼用怎麼用。
    在這裏插入圖片描述

2.1添加自己的機器人

沒有百度帳號的可以先創建一個帳號(話說現在還有誰沒有無良商家的帳號呢,狗頭保命)
我可是 \color{red}{超級會員},可是下載速度依舊只有100k/s,100M的網速被瘋狂壓榨
在這裏插入圖片描述好,迴歸正題。

2.1.1 創建

在這裏插入圖片描述

2.1.2填寫

在這裏插入圖片描述

2.1.3 得到APPID,AK,SK

在這裏插入圖片描述

2.1.4 下載官方api

支持Python版本:2.7.+ ,3.+

安裝使用Python SDK有如下方式:

如果已安裝pip,執行pip install baidu-aip即可。
如果已安裝setuptools,執行python setup.py install即可。

2.2 代碼實現語音識別

'''baidu.py'''
from aip import AipSpeech
import os
import playsound
""" 你的 APPID AK SK """
"""填入上面獲取到的3個字符串"""
APP_ID = ''
API_KEY = ''
SECRET_KEY = ''
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)

# 語音播報 我這邊用到了 vlc播放器,大家也可以嘗試別的方法
def play_audio():
    path = os.getcwd()
    commend = "cvlc " + path +"/myGetAudio.wav vlc://quit" 
    os.system(commend)
    # playsound("ffmpeg myGetAudio.wav")
    print("語音播放完成")

# 合成音頻
def hecheng_audio(msg):
    result = client.synthesis(msg, 'zh', 1, {
        'vol': 5,
        'per': 3
    })
    print("完成")
    # 識別正確返回語音二進制 錯誤則返回dict 參照下面錯誤碼
    if not isinstance(result, dict):
        with open('myGetAudio.wav', 'wb') as f:
            f.write(result)
        f.close()
        print("語音接受完成")
        play_audio()

3.email庫的操作方法(主要可以去https://docs.python.org/zh-cn/3/library/email.html查看詳細資料)以下給出具體的操作方法

   '''
    @author:JackyMao
    '''
    #------------------------------------------------------------------------------------------------
    import smtplib
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    from email.header import Header
    import os,time,re
     
    def send_Test_email(mail_to):
        '''本模塊實現獲取最新的測試報告html文件,讀取部分報告內容作爲郵件正文,將報告作爲附件,併發送到指定的郵箱,
            參數mail_to代表的是接收郵箱,例如:'[email protected]' '''
        
        #發送郵箱
        mail_from = '[email protected]'
        #發送郵件主題
        mail_subject = 'Automation Test Report'
        #發送郵箱服務器
        mail_smtpserver = 'smtp.163.com'
        #發送郵箱用戶/密碼
        mail_username = '[email protected]'
        mail_password = 'yyyyyy'
     
        #定義郵件內容,中文需參數‘utf-8’,單字節字符不需要
        '''
        #發送文件形式的郵件
        msg = MIMEText('你好!','text','utf-8')
        '''
        '''
        #發送html形式以正常文本顯示在郵件內容中的郵件
        msg = MIMEText('<html><h1>你好!</h1></html>','html','utf-8')
        '''
        '''
        #讀取html文件內容併發送
        f=open(file_new,'rb')
        mail_body=f.read()
        f.close()
        print mail_body
        msg=MIMEText(mail_body,_subtype='html',_charset='utf-8')
        '''
        
        #創建一個帶附件的郵件實例(內容)
        msg = MIMEMultipart()
        #找到report目錄下最新生成的報告文件供後續使用
        result_dir = 'D:\\report'
        lists=os.listdir(result_dir)
        lists.sort(key=lambda fn: os.path.getmtime(result_dir+"\\"+fn) if not
                   os.path.isdir(result_dir+"\\"+fn) else 0)
        print (u'The Latest Test Report is: '+lists[-1])
        file_new = os.path.join(result_dir,lists[-1])
        #讀取最新的測試報告文件獲取部分信息來定義郵件的內容
        Regex_Theme=re.compile(r'Automation Test Report')
        Regex_Content=re.compile(r'<strong>(.*:)</strong>(.*)<')
        Report_File=open(file_new,'r')
        Mail_Content=[]
        for line in Report_File.readlines():
            if '<title>Automation Test Report</title>' in line or "<p class='attribute'>" in line:
                i=Regex_Theme.findall(line)
                j=Regex_Content.findall(line)
                if i != []:
                    Mail_Content.append(i)
                if j != []:
                    Mail_Content.append(j)
        Report_File.close()
        #將讀取到的測試報告的數據以html形式顯示爲郵件的中文
        msgTest=MIMEText('''<html><h1>Test completed,Test results are as follows:</h1></html>'''
                         '''<hr />'''
                         '''<p><strong>'''+Mail_Content[0][0]+'''</strong></p>'''
                         '''<p><strong>'''+Mail_Content[1][0][0]+'''</strong>'''+Mail_Content[1][0][1]+'''</p>'''
                         '''<p><strong>'''+Mail_Content[2][0][0]+'''</strong>'''+Mail_Content[2][0][1]+'''</p>'''
                         '''<p><strong>'''+Mail_Content[3][0][0]+'''</strong>'''+Mail_Content[3][0][1]+'''</p>'''
                         '''<hr />'''
                         '''<p>PS: Detailed test results please refer to the attachment</p>'''
                         ,'html','utf-8')
        msg.attach(msgTest)
        #定義郵件的附件
        att1 = MIMEText(open(file_new, 'rb').read(), 'base64', 'utf-8')
        att1["Content-Type"] = 'application/octet-stream'
        att1["Content-Disposition"] ='attachment; filename="Automation test report.html"'#這裏的filename指的是附件的名稱及類型
        msg.attach(att1)
        #將郵件的主題等相關信息添加到郵件實例
        msg['Subject'] = Header(mail_subject)
        msg['From'] = mail_from
        msg['To'] = mail_to
        msg['date']=time.strftime('%a, %d %b %Y %H:%M:%S %z') 
        #創建發送服務器實例並將發送服務器添加到實例中
        smtp = smtplib.SMTP()
        smtp.connect(mail_smtpserver)
        '''
        #採用ssl加密傳輸
        smtp.ehlo()
        smtp.starttls()
        smtp.ehlo()
        '''
        '''
        #打印交互的日誌信息
        #smtp.set_debuglevel(1)
        '''
        #登錄發送郵件服務器並進行郵件的發送
        smtp.login(mail_username, mail_password)
        smtp.sendmail(mail_from, mail_to, msg.as_string())
        print u'Test report sent successfully,Please go to the following email to check the test report :%s' %mail_to
        smtp.quit()
        
    #----------------------------------------------------------------------------------------------------
    if __name__ == "__main__":
        send_Test_email('[email protected]')


當然,如果要使用email模塊的其他功能,可以參考網上的以下7個列子:

一,文件形式的郵件

    #!/usr/bin/env python3
    #coding: utf-8
    import smtplib
    from email.mime.text import MIMEText
    from email.header import Header
     
    sender = '***'
    receiver = '***'
    subject = 'python email test'
    smtpserver = 'smtp.163.com'
    username = '***'
    password = '***'
     
    msg = MIMEText('你好','text','utf-8')#中文需參數‘utf-8',單字節字符不需要
    msg['Subject'] = Header(subject, 'utf-8')
     
    smtp = smtplib.SMTP()
    smtp.connect('smtp.163.com')
    smtp.login(username, password)
    smtp.sendmail(sender, receiver, msg.as_string())
    smtp.quit()

二、html形式的郵件

    #!/usr/bin/env python3
    #coding: utf-8
    import smtplib
    from email.mime.text import MIMEText
     
    sender = '***'
    receiver = '***'
    subject = 'python email test'
    smtpserver = 'smtp.163.com'
    username = '***'
    password = '***'
     
    msg = MIMEText('</pre>
    <h1>你好</h1>
    <pre>','html','utf-8') 
     
    msg['Subject'] = subject 
     
    smtp = smtplib.SMTP()
    smtp.connect('smtp.163.com')
    smtp.login(username, password)
    smtp.sendmail(sender, receiver, msg.as_string())
    smtp.quit()

三、帶圖片的html郵件

    #!/usr/bin/env python3
    #coding: utf-8
    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    from email.mime.image import MIMEImage 
     
    sender = '***'
    receiver = '***'
    subject = 'python email test'
    smtpserver = 'smtp.163.com'
    username = '***'
    password = '***' 
     
    msgRoot = MIMEMultipart('related')
    msgRoot['Subject'] = 'test message' 
     
    msgText = MIMEText('<b>Some <i>HTML</i> text</b> and an image.
    <img alt="" src="cid:image1" />
    good!','html','utf-8')
    msgRoot.attach(msgText) 
     
    fp = open('h:\\python\\1.jpg', 'rb')
    msgImage = MIMEImage(fp.read())
    fp.close() 
     
    msgImage.add_header('Content-ID', '')
    msgRoot.attach(msgImage) 
     
    smtp = smtplib.SMTP()
    smtp.connect('smtp.163.com')
    smtp.login(username, password)
    smtp.sendmail(sender, receiver, msgRoot.as_string())
    smtp.quit()


四、帶附件的郵件

    #!/usr/bin/env python3
    #coding: utf-8
    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    from email.mime.image import MIMEImage 
     
    sender = '***'
    receiver = '***'
    subject = 'python email test'
    smtpserver = 'smtp.163.com'
    username = '***'
    password = '***' 
     
    msgRoot = MIMEMultipart('related')
    msgRoot['Subject'] = 'test message' 
     
    #構造附件
    att = MIMEText(open('h:\\python\\1.jpg', 'rb').read(), 'base64', 'utf-8')
    att["Content-Type"] = 'application/octet-stream'
    att["Content-Disposition"] = 'attachment; filename="1.jpg"'
    msgRoot.attach(att) 
     
    smtp = smtplib.SMTP()
    smtp.connect('smtp.163.com')
    smtp.login(username, password)
    smtp.sendmail(sender, receiver, msgRoot.as_string())
    smtp.quit()


五、羣郵件

    #!/usr/bin/env python3
    #coding: utf-8
    import smtplib
    from email.mime.text import MIMEText 
     
    sender = '***'
    receiver = ['***','****',……]
    subject = 'python email test'
    smtpserver = 'smtp.163.com'
    username = '***'
    password = '***' 
     
    msg = MIMEText('你好','text','utf-8') 
     
    msg['Subject'] = subject 
     
    smtp = smtplib.SMTP()
    smtp.connect('smtp.163.com')
    smtp.login(username, password)
    smtp.sendmail(sender, receiver, msg.as_string())
    smtp.quit()


六、包含各種元素的郵件

    #!/usr/bin/env python3
    #coding: utf-8
    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    from email.mime.image import MIMEImage 
     
    sender = '***'
    receiver = '***'
    subject = 'python email test'
    smtpserver = 'smtp.163.com'
    username = '***'
    password = '***' 
     
    # Create message container - the correct MIME type is multipart/alternative.
    msg = MIMEMultipart('alternative')
    msg['Subject'] = "Link" 
     
    # Create the body of the message (a plain-text and an HTML version).
    text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"
    html = """\
     
    Hi!
           How are you?
           Here is the <a href="http://www.python.org">link</a> you wanted.
     
    """ 
     
    # Record the MIME types of both parts - text/plain and text/html.
    part1 = MIMEText(text, 'plain')
    part2 = MIMEText(html, 'html') 
     
    # Attach parts into message container.
    # According to RFC 2046, the last part of a multipart message, in this case
    # the HTML message, is best and preferred.
    msg.attach(part1)
    msg.attach(part2)
    #構造附件
    att = MIMEText(open('h:\\python\\1.jpg', 'rb').read(), 'base64', 'utf-8')
    att["Content-Type"] = 'application/octet-stream'
    att["Content-Disposition"] = 'attachment; filename="1.jpg"'
    msg.attach(att) 
     
    smtp = smtplib.SMTP()
    smtp.connect('smtp.163.com')
    smtp.login(username, password)
    smtp.sendmail(sender, receiver, msg.as_string())
    smtp.quit()


7、基於ssl的郵件

    #!/usr/bin/env python3
    #coding: utf-8
    import smtplib
    from email.mime.text import MIMEText
    from email.header import Header
    sender = '***'
    receiver = '***'
    subject = 'python email test'
    smtpserver = 'smtp.163.com'
    username = '***'
    password = '***' 
     
    msg = MIMEText('你好','text','utf-8')#中文需參數‘utf-8',單字節字符不需要
    msg['Subject'] = Header(subject, 'utf-8') 
     
    smtp = smtplib.SMTP()
    smtp.connect('smtp.163.com')
    smtp.ehlo()
    smtp.starttls()
    smtp.ehlo()
    smtp.set_debuglevel(1)
    smtp.login(username, password)
    smtp.sendmail(sender, receiver, msg.as_string())
    smtp.quit()

接下來就是源代碼時刻(複製粘帖就能用的那種哦)

163qq\color{blue}{注意:博主用的是163和qq,其他郵箱還得看官方的介紹來引入}

Email_Received.py

'''Email_Received.py'''
# pop3
import poplib
# 郵箱標題文本
from email.header import decode_header
# 郵箱分析器
from email.parser import Parser
# 用來解析郵件來源
from email.utils import parseaddr

# 郵件接收類
class Email_Received:
    def __init__(self,usercount,password,pop3_url):
        self.usercount = usercount # 用戶的賬戶
        self.password = password # 用戶的密碼
        self.pop3_sever = poplib.POP3(pop3_url)# pop3服務器爲163
    def conect_pop(self):
        self.pop3_sever.user(self.usercount)# 驗證賬號
        self.pop3_sever.pass_(self.password)# 驗證密碼
    def get_length(self):
        rsp, msg_list, rsp_siz = self.pop3_sever.list()# 獲取當前郵箱郵件數,爲字節型
        return len(msg_list)
    def get_latest_email(self):
        self.pop3_sever.set_debuglevel(1)# set_debuglevel()參數爲1,後面的函數會輸出信息
        #print(self.pop3_sever.getwelcome().decode('utf8'))# 獲取郵箱歡迎語句

        rsp, msg_list, rsp_siz = self.pop3_sever.list()# 獲取當前郵件數
        self.nowcount = len(msg_list)
        rsp, msglines, msgsiz = self.pop3_sever.retr(len(msg_list))# 獲取郵件信息
        #print(msglines)
        msg_content = b'\r\n'.join(msglines).decode('gbk')
        #print(msg_content)
        msg = Parser().parsestr(text=msg_content)#分析郵件信息
        self.msg = msg

    def get_email_title(self):
        subject = self.msg['Subject']
        value, charset = decode_header(subject)[0]
        if charset:
            value = value.decode(charset)
        # print('郵件主題: {0}'.format(value))
        self.email_title = value
        #print(value)

    def get_sender_info(self):
        hdr, addr = parseaddr(self.msg['From'])
        # name 發送人郵箱名稱, addr 發送人郵箱地址
        name, charset = decode_header(hdr)[0]
        if charset:
            name = name.decode(charset)
        self.sender_name = name
        self.sender_email = addr
        #print('發送人郵箱名稱: {0}'.format(name))
        #print('發送人郵箱名稱: {0},發送人郵箱地址: {1}'.format(name, addr))

    def get_email(self):
        self.get_latest_email()
        self.get_email_title()
        self.get_sender_info()
        return self.email_title,self.sender_name,self.sender_email,self.nowcount
    def close(self):
        self.pop3_sever.quit()


Email_Send.py

'''Email_Send.py'''
# 郵箱標題文本
from email.header import Header
# 郵箱內容多項目
from email.mime.multipart import MIMEMultipart
# 郵箱內容文本
from email.mime.text import MIMEText
# 郵箱內容圖片
from email.mime.image import MIMEImage
# SMTP
import smtplib
# 郵件發送類
class Email_Send:
    # 用來初始化類的函數
    def __init__(self, from_addr, to_addr, password,smtp_url):
        self.from_addr = from_addr  # 寄郵件的郵箱地址
        self.to_addr = to_addr  # 收郵件的郵箱地址
        self.password = password  # 寄郵件的允許密碼,不是登陸密碼
        self.smtp = smtplib.SMTP(smtp_url)  # 確定SMTP的服務器是163

    def msg_stmp(self, sendname, minetext, subject):
        msg = MIMEMultipart('mixed')  # 新建一個多項的郵件處理變量
        msg['From'] = sendname + '<' + self.from_addr + '>'  # 發送人的郵箱
        msg['To'] = self.to_addr  # 接收人的郵箱
        msg['Subject'] = Header(subject, 'utf-8')  # 標題文本
        text = MIMEText(minetext, 'plain', 'utf-8')  # 主要文本內容
        msg.attach(text)  # 添加文本進多項的郵件處理
        image = open('1.png', 'rb').read()
        mineimage = MIMEImage(image)  # 要發送郵件的圖片
        mineimage['Content-Disposition'] = 'attachment; filename = "people.png"'
        msg.attach(mineimage)
        return msg

    # 發送信息
    def sendmessage(self, sendname, minetext, subject):
        self.smtp.sendmail(self.from_addr, self.to_addr, self.msg_stmp(sendname, minetext, subject).as_string())  # 發送郵件

    # 登錄郵箱
    def start_stmp(self):
        self.smtp.login(self.from_addr, self.password)

    # 退出郵箱
    def stop_stmp(self):
        self.smtp.quit()

main.py

'''main.py'''
from Email_Send import Email_Send
from Email_Received import Email_Received
# opencv
import cv2
# 延時函數
from time import sleep
# 操作系統
import os
# 接入百度api
import baidu

def find_face(path):
    face_patterns = cv2.CascadeClassifier(path+"/haarshare/haarcascade_frontalface_default.xml")
    eye_patterns = cv2.CascadeClassifier(path+"/haarshare/haarcascade_eye.xml")

    cap = cv2.VideoCapture(0)

    while True:
        rep,frame = cap.read()


        faces = face_patterns.detectMultiScale(frame,scaleFactor=1.3,minNeighbors=5)

        for (x,y,w,h) in faces:
            cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2)
            face_area = frame[y:y+h,x:x+w]
            eyes = eye_patterns.detectMultiScale(face_area)
            for (ex,ey,ew,eh) in eyes:
                cv2.rectangle(frame,(x+ex,y+ey),(x+ex+ew,y+ey+eh),(255,0,0),2)
            cv2.imwrite(path+"/1.png",frame)
        if len(faces)>=1:
            return 1,len(faces)

# opencv 打開攝像頭
def open_camera(path):
    cap = cv2.VideoCapture(0)
    ret, frame = cap.read()
    sleep(0.5)
    cv2.imwrite(path+'/1.png',frame)
    cap.release()

if __name__ == '__main__':
    path  = os.getcwd()
    smtp_url = {'163': 'smtp.163.com'}
    pop3_url = {'163': 'pop.163.com'}
    from_addr = "[email protected]"
    password = "xxx"
    to_addr = "[email protected]"
    email_title = ''
    sender_name = ''
    sender_email = ''
    msg=''
    count = 0
    nowcount = 0
    
    email_received = Email_Received(from_addr, password,pop3_url['163'])
    email_received.conect_pop()
    count = email_received.get_length()
    email_received.close()
    while True:
        email_received = Email_Received(from_addr, password, pop3_url['163'])
        email_received.conect_pop()
        email_title,sender_name,sender_email,nowcount = email_received.get_email()
        sleep(2)
        print('nowcount={0},count={1}'.format(nowcount,count))
        if  nowcount > count:
            if "(你發送文件用的用戶名)" in sender_email:
                if email_title=='1':
                    open_camera(path)
                    email_send = Email_Send(from_addr, to_addr, password,smtp_url['163'])
                    email_send.start_stmp()
                    email_send.sendmessage('Mao','電腦拍攝','請接受你的圖片')
                    email_send.stop_stmp()
                    count = nowcount
                    print("發送成功")
                # 語音警報
                if "2:" in email_title:
                    baidu.hecheng_audio(email_title[2:])
                    count = nowcount
                if "3:" in email_title:
                    counts = int(email_title[2:])
                    # open the haarcascade
                    for i in range(counts):
                        flag, faces_counts = find_face(path)
                        if flag == 1:
                            email_send = Email_Send(from_addr, to_addr, password,smtp_url['163'])
                            email_send.start_stmp()
                            email_send.sendmessage('Mao','人臉檢測',"一共檢測到{0}個人再看你的電腦".format(faces_counts))
                            email_send.stop_stmp()
                            count = nowcount
                            print("發送成功")
        email_received.close()

如要轉載請說明出處:https://blog.csdn.net/xiaokai1999/article/details/105690965

引用:

[1]https://www.jianshu.com/p/ea3c57b6c5e1
[2]https://blog.csdn.net/freesigefei/article/details/51313155

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章