<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[i want to add phython code in 'MMM-Facial-Recognition-OCV3']]></title><description><![CDATA[<p dir="auto">i’m making magicmirror about style fashion.<br />
but i don’t know how to add this code.<br />
Without MagicMirror this phython is very well.<br />
but i want to put this open cv phython code, and work this open cv in MagicMirror.<br />
please teach me how to put this code.<br />
i’m using this modeul MMM-Facial-Recognition-OCV3</p>
<pre><code>import cv2
import numpy as np
import sys
casc='haarcascade_frontalface_default.xml'
eye_cas='haarcascade_eye.xml'

faceCascade=cv2.CascadeClassifier(casc)
eyeCascade=cv2.CascadeClassifier(eye_cas)
cap=cv2.VideoCapture(0)
ret=cap.set(3,240)
ret=cap.set(4,180)
while True:
    num=input('input numbers 1~15= hair, 16~18 = glass')
    if int(num)&gt;0 and int(num)&lt;19:
        break
while True:
    ret,frame=cap.read()
    frame=cv2.flip(frame,1)
    gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
    faces=faceCascade.detectMultiScale(
            gray,
            scaleFactor=1.1,
            minNeighbors=5,
            minSize=(100,100),
            )
    sz=0
    
    a,b,c,d=0,0,0,0
    x,y,w,h=0,0,0,0
    count=0
    for (x,y,w,h) in faces:
        if w&gt;sz:
            sz=w
            a,b,c,d=(x,y,w,h)
            count=count+1
    if count&gt;0:
        (x,y,w,h)=a,b,c,d
        roi_gray=gray[y:y+h,x:x+w]
        roi_color=gray[y:y+h,x:x+w]
        eye=eyeCascade.detectMultiScale(roi_gray)
        cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2)
        sz=0
        count=0
        eyes=[]
        for ex,ey,ew,eh in eye:
            if ey&lt;int(h/2) and ew&gt;sz:
                sz=ew
                a,b,c,d=(ex,ey,ew,eh)
                count=count+1
                eyes.append((a,b,c,d))
        eyes.sort(reverse=True)
        if count&gt;1:#눈이 발견된경우
            xi,yi,wi,hi=eyes[0]
            
            xxi,yyi,wwi,hhi=eyes[1]
            lx=0
            ly=0
            
            rx=0
            ry=0

            if xi&lt;int(w/2):# xi : left   
                lx=x+xi+int(wi/2)
                ly=y+yi+int(hi/2)
                cv2.line(frame,(lx,ly),(lx,ly),(255,255,0),8,cv2.LINE_AA)
            else :
                rx=x+xi+int(wi/2)
                ry=y+yi+int(hi/2)
                cv2.line(frame,(rx,ry),(rx,ry),(255,0,0),8,cv2.LINE_AA)
            cv2.imshow('video',frame)
            
            
            hair_url='./images/'+num+'.png'
            hair=cv2.imread(hair_url,cv2.IMREAD_UNCHANGED)
            height,width,channel=hair.shape
        
            origin_ratio=int(w/h)
            height=origin_ratio*width
            ratio=int(width/w)
            height=int(height/ratio)
            width=int(width/ratio)
            if w&gt;0 and h&gt;0:
                if int(num)&gt;15:# 선글래스 합성#
                    print('3channel')
                    height=int(height/3)
                    y=y+int(height/2)
                    x=x-int(width/12)
                    
                    hair=cv2.resize(hair,(width,height),interpolation=cv2.INTER_AREA)
                    cut_img=frame[y:y+height,x:x+width]
                    gray_hair=cv2.cvtColor(hair,cv2.COLOR_BGR2GRAY)
            
                    gray_hair=cv2.bitwise_not(gray_hair)
                    ret,mask=cv2.threshold(gray_hair,100,255,cv2.THRESH_BINARY)
                    
                    mask_inv=cv2.bitwise_not(mask)
                    fg=cv2.bitwise_and(hair,hair,mask=mask)
                    bg=cv2.bitwise_and(cut_img,cut_img,mask=mask_inv)
                    result=cv2.add(fg,bg)
                    frame[y:y+height,x:x+width]=result
                    cv2.imshow('result',frame)
                else:# 머리합성
                    r,g,b,a=cv2.split(hair)
                    r=cv2.bitwise_and(r,r,mask=a)
                    g=cv2.bitwise_and(g,g,mask=a)
                    b=cv2.bitwise_and(b,b,mask=a)
                    hair=cv2.merge((r,g,b))
                    height=height*2
                    width=width*3
                    if x&gt;int(width/2) and y&gt;int(height/2):
                        x=x-w
                        y=y-int(h/2)
                        cv2.rectangle(frame,(x,y),(x+width,y+height),(0,2,255),2)
                        hair=cv2.resize(hair,(width,height),interpolation=cv2.INTER_AREA)

                        cut_img=frame[y:y+height,x:x+width]
                        gray_hair=cv2.cvtColor(hair,cv2.COLOR_BGR2GRAY)
            
                        ret,mask=cv2.threshold(gray_hair,10,255,cv2.THRESH_BINARY)
                        mask_inv=cv2.bitwise_not(mask)
                        fg=cv2.bitwise_and(hair,hair,mask=mask)
                        bg=cv2.bitwise_and(cut_img,cut_img,mask=mask_inv)
                        result=cv2.add(fg,bg)
                        frame[y:y+height,x:x+width]=result
                        cv2.imshow('result',frame)
                    else:
                        print('step back too close')
        
    if cv2.waitKey(1)&amp;0xff==ord('q'):
        break
cap.release()
cv2.destroyAllWindows()
</code></pre>
]]></description><link>https://forum.magicmirror.builders/topic/15055/i-want-to-add-phython-code-in-mmm-facial-recognition-ocv3</link><generator>RSS for Node</generator><lastBuildDate>Fri, 17 Jul 2026 02:49:52 GMT</lastBuildDate><atom:link href="https://forum.magicmirror.builders/topic/15055.rss" rel="self" type="application/rss+xml"/><pubDate>Tue, 18 May 2021 06:54:31 GMT</pubDate><ttl>60</ttl><item><title><![CDATA[Reply to i want to add phython code in 'MMM-Facial-Recognition-OCV3' on Tue, 18 May 2021 12:52:17 GMT]]></title><description><![CDATA[<p dir="auto">1st, please use code block tags around code… mark the text and hit the button above the editor that looks like &lt;/&gt;</p>
<p dir="auto">i will fix one, u fix the others…</p>
<p dir="auto">now, I’m not sure that this code does…</p>
<p dir="auto">you cannot manipulate (change) the  UI/webpage  with python in MagicMirror…<br />
you can send info to a node_helper  spawn routine that can send info onto the module, which can manipulate (change) the UI/webpage</p>
<p dir="auto">the module u are using has not been updated in 3 years…</p>
<p dir="auto"><a href="https://github.com/nischi/MMM-Face-Reco-DNN" target="_blank" rel="noopener noreferrer nofollow ugc">https://github.com/nischi/MMM-Face-Reco-DNN</a>, HAS been updated recently, and u might get help by posting an issue to its repo</p>
<p dir="auto">the module u are using, launches a python script in the background and checks for responses</p>
<pre><code>    pyshell.on('message', function (message) {
      
      if (message.hasOwnProperty('status')){
      console.log("[" + self.name + "] " + message.status);
      }
      if (message.hasOwnProperty('login')){
        console.log("[" + self.name + "] " + "User " + self.config.users[message.login.user - 1] + " with confidence " + message.login.confidence + " logged in.");
        self.sendSocketNotification('user', {action: "login", user: message.login.user - 1, confidence: message.login.confidence});
        }
      if (message.hasOwnProperty('logout')){
        console.log("[" + self.name + "] " + "User " + self.config.users[message.logout.user - 1] + " logged out.");
        self.sendSocketNotification('user', {action: "logout", user: message.logout.user - 1});
        }
    });
</code></pre>
<p dir="auto">and the DNN does similar</p>
<pre><code>  self.pyshell.on('message', function(message) {
      // A status message has received and will log
      if (message.hasOwnProperty('status')) {
        console.log('[' + self.name + '] ' + message.status);
      }

      // Somebody new are in front of the camera, send it back to the Magic Mirror Module
      if (message.hasOwnProperty('login')) {
</code></pre>
<p dir="auto">only checking for login and logout</p>
]]></description><link>https://forum.magicmirror.builders/post/91506</link><guid isPermaLink="true">https://forum.magicmirror.builders/post/91506</guid><dc:creator><![CDATA[sdetweil]]></dc:creator><pubDate>Tue, 18 May 2021 12:52:17 GMT</pubDate></item><item><title><![CDATA[Reply to i want to add phython code in 'MMM-Facial-Recognition-OCV3' on Tue, 18 May 2021 08:14:18 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="/user/%EA%B9%80%EC%9C%A4%ED%98%B8" aria-label="Profile: 김윤호">@<bdi>김윤호</bdi></a> # -<em>- coding: utf-8 -</em>-</p>
<p dir="auto">from PyQt5 import QtCore, QtGui, QtWidgets #pip install pyqt5(pip install python3-pyqt5)<br />
import forecastio #pip install python-forecastio  [Weather api] [<a href="https://github.com/ZeevG/python-forecast.io" target="_blank" rel="noopener noreferrer nofollow ugc">https://github.com/ZeevG/python-forecast.io</a>]<br />
import yapi #pip install yapi [<a href="https://github.com/ahmetkotan/yapi" target="_blank" rel="noopener noreferrer nofollow ugc">https://github.com/ahmetkotan/yapi</a>]<br />
import feedparser #pip install feedparser [News api] [<a href="http://w3devlabs.net/wp/?p=16964" target="_blank" rel="noopener noreferrer nofollow ugc">http://w3devlabs.net/wp/?p=16964</a>]<br />
import datetime<br />
from time import sleep<br />
import threading<br />
import tkinter as tk #this can’t pip install<br />
import requests<br />
import json<br />
import cv2<br />
from PyQt5.QtGui import QPixmap, QImage<br />
import pafy #pip install pafy , pip install youtube_dl</p>
<p dir="auto">#==================================================================================================<br />
#==============UI_MAIN==============================================================================<br />
#==================================================================================================</p>
<p dir="auto">class Ui_MainWindow(object):<br />
hello_world = 0<br />
root = <a href="http://tk.Tk" target="_blank" rel="noopener noreferrer nofollow ugc">tk.Tk</a>()<br />
width = root.winfo_screenwidth()<br />
height = root.winfo_screenheight()<br />
News_url = “<a href="http://fs.jtbc.joins.com//RSS/newsflash.xml" target="_blank" rel="noopener noreferrer nofollow ugc">http://fs.jtbc.joins.com//RSS/newsflash.xml</a>”<br />
start_or_stop=False<br />
start=True</p>
<pre><code>def setupUi(self, MainWindow):
    MainWindow.setObjectName("MainWindow")

    palette = QtGui.QPalette()

    brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
    brush.setStyle(QtCore.Qt.SolidPattern)
    palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)

    brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
    brush.setStyle(QtCore.Qt.SolidPattern)
    palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)

    MainWindow.setPalette(palette)
    #MainWindow.resize(800, 600)
    MainWindow.showFullScreen()

    self.centralwidget = QtWidgets.QWidget(MainWindow)
    self.centralwidget.setObjectName("centralwidget")

    #날씨 이모티콘 ====================================================================
    self.weather = QtWidgets.QLabel(self.centralwidget)
    self.weather.setGeometry(QtCore.QRect(20, 15, 150,130))
    self.weather.setObjectName("weather")

    #온도 label [온도 출력]
    self.temperature = QtWidgets.QLabel(self.centralwidget)
    self.temperature.setGeometry(QtCore.QRect(25, 120, 150,130))
    self.temperature.setObjectName("temperature")
    self.temperature.setFont(QtGui.QFont("맑은 고딕",20))

    #================================================================================
    #clock 이라는 이름으로 label 생성 [hello world]===================================
    self.clock = QtWidgets.QLabel(self.centralwidget)
    self.clock.setGeometry(QtCore.QRect(200,300,100,50))
    self.clock.setObjectName("clock")

    #time 이라는 이름으로 label 생성 [(오전/오후)시/분]
    self.time = QtWidgets.QLabel(self.centralwidget)
    self.time.setGeometry(QtCore.QRect(170,80,800,60))
    self.time.setObjectName("time")
    #setFont(QtGui.QFont("Font_name",Font_size))
    self.time.setFont(QtGui.QFont("맑은 고딕",50)) 

    #date 이라는 이름으로 label 생성 [년/월/일]
    self.date = QtWidgets.QLabel(self.centralwidget)
    self.date.setGeometry(QtCore.QRect(180, 15, 300, 50))
    self.date.setObjectName("date")
    self.date.setFont(QtGui.QFont("맑은 고딕",20))
    #===============================================================================
    #clock_button 이라는 이름으로 버튼을 생성 [쓰레드가 잘 작동하는지 확인]
    # self.clock_button = QtWidgets.QPushButton(self.centralwidget)
    # self.clock_button.setGeometry(QtCore.QRect(200, 280, 75, 23))
    # self.clock_button.setObjectName("clock_button")
    
    # self.youtube_button = QtWidgets.QPushButton(self.centralwidget)
    # self.youtube_button.setGeometry(QtCore.QRect(1500, 450, 75, 23))
    # self.youtube_button.setObjectName("youtube_button")
    #===================================================================
    #new 라벨 생성========================================================
    self.news1 = QtWidgets.QLabel(self.centralwidget)
    self.news1.setGeometry(QtCore.QRect(self.width-470,self.height-350,470,50))
    self.news1.setObjectName("news1")
    self.news1.setFont(QtGui.QFont("맑은 고딕",11))

    self.news2 = QtWidgets.QLabel(self.centralwidget)
    self.news2.setGeometry(QtCore.QRect(self.width-470,self.height-320,470,50))
    self.news2.setObjectName("news2")
    self.news2.setFont(QtGui.QFont("맑은 고딕",11))

    self.news3 = QtWidgets.QLabel(self.centralwidget)
    self.news3.setGeometry(QtCore.QRect(self.width-470,self.height-290,470,50))
    self.news3.setObjectName("news3")
    self.news3.setFont(QtGui.QFont("맑은 고딕",11))

    self.news4 = QtWidgets.QLabel(self.centralwidget)
    self.news4.setGeometry(QtCore.QRect(self.width-470,self.height-260,470,50))
    self.news4.setObjectName("news4")
    self.news4.setFont(QtGui.QFont("맑은 고딕",11))

    self.news5 = QtWidgets.QLabel(self.centralwidget)
    self.news5.setGeometry(QtCore.QRect(self.width-470,self.height-230,470,50))
    self.news5.setObjectName("news5")
    self.news5.setFont(QtGui.QFont("맑은 고딕",11))

    self.news6 = QtWidgets.QLabel(self.centralwidget)
    self.news6.setGeometry(QtCore.QRect(self.width-470,self.height-200,470,50))
    self.news6.setObjectName("news6")
    self.news6.setFont(QtGui.QFont("맑은 고딕",11))

    self.news7 = QtWidgets.QLabel(self.centralwidget)
    self.news7.setGeometry(QtCore.QRect(self.width-470,self.height-170,470,50))
    self.news7.setObjectName("news7")
    self.news7.setFont(QtGui.QFont("맑은 고딕",11))

    self.news8 = QtWidgets.QLabel(self.centralwidget)
    self.news8.setGeometry(QtCore.QRect(self.width-470,self.height-140,470,50))
    self.news8.setObjectName("news8")
    self.news8.setFont(QtGui.QFont("맑은 고딕",11))

    self.news9 = QtWidgets.QLabel(self.centralwidget)
    self.news9.setGeometry(QtCore.QRect(self.width-470,self.height-110,470,50))
    self.news9.setObjectName("news9")
    self.news9.setFont(QtGui.QFont("맑은 고딕",11))

    self.news10 = QtWidgets.QLabel(self.centralwidget)
    self.news10.setGeometry(QtCore.QRect(self.width-470,self.height-80,470,50))
    self.news10.setObjectName("news10")
    self.news10.setFont(QtGui.QFont("맑은 고딕",11))

    #====================================================================
    #meal_label 생성 =====================================================
    self.b_label = QtWidgets.QLabel(self.centralwidget)
    self.b_label.setGeometry(QtCore.QRect(50,self.height-500,470,200))
    self.b_label.setObjectName("b_label")
    self.b_label.setText("아침")
    self.b_label.setFont(QtGui.QFont("맑은 고딕",11))
    self.breakfast_label = QtWidgets.QLabel(self.centralwidget)
    self.breakfast_label.setGeometry(QtCore.QRect(125,self.height-500,470,200))
    self.breakfast_label.setObjectName("breakfast_label")
    self.breakfast_label.setFont(QtGui.QFont("맑은 고딕",11))

    self.l_label = QtWidgets.QLabel(self.centralwidget)
    self.l_label.setGeometry(QtCore.QRect(50,self.height-350,470,200))
    self.l_label.setObjectName("l_label")
    self.l_label.setText("점심")
    self.l_label.setFont(QtGui.QFont("맑은 고딕",11))
    self.lunch_label = QtWidgets.QLabel(self.centralwidget)
    self.lunch_label.setGeometry(QtCore.QRect(125,self.height-350,470,200))
    self.lunch_label.setObjectName("lunch_label")
    self.lunch_label.setFont(QtGui.QFont("맑은 고딕",11))

    self.d_label = QtWidgets.QLabel(self.centralwidget)
    self.d_label.setGeometry(QtCore.QRect(50,self.height-200,470,200))
    self.d_label.setObjectName("d_label")
    self.d_label.setText("저녁")
    self.d_label.setFont(QtGui.QFont("맑은 고딕",11))
    self.dinner_label = QtWidgets.QLabel(self.centralwidget)
    self.dinner_label.setGeometry(QtCore.QRect(125,self.height-200,470,200))
    self.dinner_label.setObjectName("dinner_label")
    self.dinner_label.setFont(QtGui.QFont("맑은 고딕",11))

    #====================================================================
    #video_viewer_label 생성 =====================================================
    self.video_viewer_label = QtWidgets.QLabel(self.centralwidget)
    self.video_viewer_label.setGeometry(QtCore.QRect(self.width-400,0,400,225))
    self.video_viewer_label.setObjectName("video_viewer_label")

    self.video_name_label = QtWidgets.QLabel(self.centralwidget)
    self.video_name_label.setGeometry(QtCore.QRect(self.width-400,250,400,20))
    self.video_name_label.setObjectName("video_name_label")
    self.video_name_label.setFont(QtGui.QFont("맑은 고딕",11))
    #===================================================================
    #===================================================================

    MainWindow.setCentralWidget(self.centralwidget)
    self.menubar = QtWidgets.QMenuBar(MainWindow)
    self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
    self.menubar.setObjectName("menubar")
    MainWindow.setMenuBar(self.menubar)
    self.statusbar = QtWidgets.QStatusBar(MainWindow)
    self.statusbar.setObjectName("statusbar")
    MainWindow.setStatusBar(self.statusbar)

    self.retranslateUi(MainWindow)
    QtCore.QMetaObject.connectSlotsByName(MainWindow)

def retranslateUi(self, MainWindow):
    _translate = QtCore.QCoreApplication.translate
    MainWindow.setWindowTitle(_translate("MainWindow", "SmartMirror"))
    # self.clock_button.setText(_translate("MainWindow", "PushButton"))
    # self.youtube_button.setText(_translate("MainWindow", "Youtube"))

#-----------------------------------------------------------------------------------------
# 이벤트
# EVENT
#-----------------------------------------------------------------------------------------

#버튼을 누를시
# def button(self,MainWindow):
#     self.clock_button.clicked.connect(self.hello) #누를시 hello 함수랑 연결
#     self.youtube_button.clicked.connect(self.Stop_video)

#프린트 hello world 함수
def hello(self,MainWindow):
    self.hello_world = self.hello_world + 1
    self.clock.setText("%d %s" %(self.hello_world, "hello world"))

#시간을 알려주는 함수 메인 화면에 생성
# now.(year,month,day,hour,minute,second)
def set_time(self,MainWindow):
    EvenOrAfter = "오전"
    while True:
        now=datetime.datetime.now() #현재 시각을 시스템에서 가져옴
        hour=now.hour

        if(now.hour&gt;=12):
            EvenOrAfter="오후"
            hour=now.hour%12

            if(now.hour==12):
                hour=12

        else:
            EvenOrAfter="오전"

        self.date.setText("%s년 %s월 %s일"%(now.year,now.month,now.day))
        self.time.setText(EvenOrAfter+" %s시 %s분" %(hour,now.minute))
        sleep(1)

#weather (아이콘 설정 및 기온 출력)
def weather_icon(self,MainWindow):
    while True:
        api_key = "darksky_api_key"

        #대구소프트웨어고등학교 위치
        lat = 35.663106 
        lng = 128.413759

        #서버 접속후 데이터를 받아옴
        forecast = forecastio.load_forecast(api_key, lat, lng)
        weather=forecast.currently()


        weather_cashe=weather.icon

        self.temperature.setText("[ %.1f ℃ ]" %(weather.temperature))
        
        if "day" in weather_cashe:
            if "partly-cloudy" in weather_cashe:
                self.weather.setPixmap(QtGui.QPixmap("weather_icon\cloudy_day.png"))
            elif "cloudy" in weather_cashe:
                self.weather.setPixmap(QtGui.QPixmap("weather_icon\clouds.png"))
            elif "clear" in weather_cashe:
                self.weather.setPixmap(QtGui.QPixmap("weather_icon\sun.png"))

        elif "night" in weather_cashe:
            if "partly-cloudy" in weather_cashe:
                self.weather.setPixmap(QtGui.QPixmap("weather_icon\cloudy_night.png"))
            elif "cloudy" in weather_cashe:
                self.weather.setPixmap(QtGui.QPixmap("weather_icon\clouds.png"))
            elif "clear" in weather_cashe:
                self.weather.setPixmap(QtGui.QPixmap("weather_icon\moon.png"))
        
        elif "cloudy" in weather_cashe:
            self.weather.setPixmap(QtGui.QPixmap("weather_icon\clouds.png"))

        elif "rain" in weather_cashe:
            self.weather.setPixmap(QtGui.QPixmap("weather_icon\drop.png"))

        elif "snow" in weather_cashe:
            self.weather.setPixmap(QtGui.QPixmap("weather_icon\snowflake.png"))

        sleep(300)

#News (타이틀&amp;기사 출력)
def News(self,MainWindow) :
    d = feedparser.parse(self.News_url)
    while True :
        num = 1
        for e in d.entries :
            if num%10==1:
                self.news1.setText("[%d] %s"%(num,e.title))
            elif num%10==2:
                self.news2.setText("[%d] %s"%(num,e.title))
            elif num%10==3:
                self.news3.setText("[%d] %s"%(num,e.title))
            elif num%10==4:
                self.news4.setText("[%d] %s"%(num,e.title))
            elif num%10==5:
                self.news5.setText("[%d] %s"%(num,e.title))
            elif num%10==6:
                self.news6.setText("[%d] %s"%(num,e.title))
            elif num%10==7:
                self.news7.setText("[%d] %s"%(num,e.title))
            elif num%10==8:
                self.news8.setText("[%d] %s"%(num,e.title))
            elif num%10==9:
                self.news9.setText("[%d] %s"%(num,e.title))
            elif num%10==0:
                self.news10.setText("[%d] %s"%(num,e.title))
            num=num+1
            sleep(1)

#급식 출력
def School_meal(self,MainWindow):
    while True:
        now=datetime.datetime.now()

        response = requests.get('https://schoolmenukr.ml/api/high/D100000282?year='+str(now.year)+'&amp;month='+str(now.month)+'&amp;date='+str(now.day)+'&amp;hideAllergy=true')
        meal_menu = json.loads(response.text)

        str_menu=str(meal_menu)

        breakfast=""
        lunch=""
        dinner=""

        br=0
        lu=0
        di=0

        i=0

        while True:
            try :
                if "'" in str_menu[br]:
                    if "[" in str_menu[br-1] :
                        if " " in  str_menu[br-2] :
                            if ":" in str_menu[br-3] :
                                if "'" in str_menu[br-4] :
                                    if "t" in str_menu[br-5] :
                                        br=br+1
                                        break
                br=br+1
            except IndexError as e :
                pass
        breakfast=breakfast+" "
        while True:
            try : 
                if "]" in str_menu[br] :
                    break
                elif "'" in str_menu[br] :
                    pass
                elif "," in str_menu[br] :
                    breakfast=breakfast+"\n"
                else :
                    breakfast=breakfast+str_menu[br]
                
                br=br+1
            except IndexError as e :
                pass
        self.breakfast_label.setText(breakfast)

        while True:
            try :
                if "'" in str_menu[lu]:
                    if "[" in str_menu[lu-1] :
                        if " " in  str_menu[lu-2] :
                            if ":" in str_menu[lu-3] :
                                if "'" in str_menu[lu-4] :
                                    if "h" in str_menu[lu-5] :
                                        lu=lu+1
                                        break
                lu=lu+1;
            except IndexError as e:
                pass
        lunch=lunch+" "
        while True:
            try :
                if "]" in str_menu[lu] :
                    break
                elif "'" in str_menu[lu] :
                    pass
                elif "," in str_menu[lu] :
                    lunch=lunch+"\n"
                else :
                    lunch=lunch+str_menu[lu]
                
                lu=lu+1
            except IndexError as e:
                pass
        self.lunch_label.setText(lunch)

        while True:
            try :
                if "'" in str_menu[di]:
                    if "[" in str_menu[di-1] :
                        if " " in  str_menu[di-2] :
                            if ":" in str_menu[di-3] :
                                if "'" in str_menu[di-4] :
                                    if "r" in str_menu[di-5] :
                                        di=di+1
                                        break
                di=di+1;
            except IndexError as e :
                pass
        dinner=dinner+" "
        while True:
            try : 
                if "]" in str_menu[di] :
                    break
                elif "'" in str_menu[di] :
                    pass
                elif "," in str_menu[di] :
                    dinner=dinner+"\n"
                else :
                    dinner=dinner+str_menu[di]
                
                di=di+1
            except IndexError as e:
                pass
        self.dinner_label.setText(dinner)

def Video_to_frame(self, MainWindow):
    while True:
        url = "https://youtu.be/"

        api = yapi.YoutubeAPI('youtube_data_api_ver3_key')
        video_name="자막뉴스 "
        results = api.general_search(video_name, max_results=2)
        
        str_results=str(results)

        i=0
        TrueOrFalse=False
        video_id=""

        #print(str_results)
        
        while True:
            try :

                if "'" in str_results[i]:
                    if "=" in str_results[i-1]:
                        if "d" in str_results[i-2]:
                            if "I" in str_results[i-3]:
                                if "o" in str_results[i-4]:
                                    i=i+1
                                    TrueOrFalse=True
                                    break
                i=i+1

            except IndexError as e:
                print("error")
                break

        while TrueOrFalse:
            if "'" in str_results[i]:
                break
            else :
                video_id=video_id+str_results[i]

            i=i+1

        url = url+video_id

        try :
            vPafy = pafy.new(url)
            self.video_name_label.setText(vPafy.title)
            video_length=vPafy.length/60

        except Exception as e :
            self.video_viewer_label.setText("Error")
            self.start=False
        print(video_length/60)

        play = vPafy.getbest(preftype="mp4")
            
        cap = cv2.VideoCapture(play.url)

        while self.start:
            self.ret, self.frame = cap.read()
            if self.ret:
                self.rgbImage = cv2.cvtColor(self.frame, cv2.COLOR_BGR2RGB)
                self.convertToQtFormat = QImage(self.rgbImage.data, self.rgbImage.shape[1], self.rgbImage.shape[0], QImage.Format_RGB888)
                   
                self.pixmap = QPixmap(self.convertToQtFormat)
                self.p = self.pixmap.scaled(400, 225, QtCore.Qt.IgnoreAspectRatio)

                self.video_viewer_label.setPixmap(self.p)
                self.video_viewer_label.update()

                sleep(0.02) #Youtube 영상 1프레임당 0.02초

            else :
                break
                
            if self.start_or_stop:
                break

        cap.release()
        cv2.destroyAllWindows()
            
# def Stop_video(self,MainWindow) :
#     if self.start_or_stop :
#         self.start_or_stop=False
#     else :
#         self.start_or_stop=True

#----------------------------------------------------------------------------------------------------
#------------------------ 쓰레드 ---------------------------------------------------------------------
#----------------------------------------------------------------------------------------------------

#Set_time을 쓰레드로 사용
def time_start(self,MainWindow):
    thread=threading.Thread(target=self.set_time,args=(self,))
    thread.daemon=True #프로그램 종료시 프로세스도 함께 종료 (백그라운드 재생 X)
    thread.start()

#weather_icon을 쓰레드로 사용
def weather_start(self,MainWindow):
    thread=threading.Thread(target=self.weather_icon,args=(self,))
    thread.daemon=True #프로그램 종료시 프로세스도 함께 종료 (백그라운드 재생 X)
    thread.start()

#News를 쓰레드로 사용
def News_start(self,MainWindow):
    thread=threading.Thread(target=self.News,args=(self,))
    thread.daemon=True #프로그램 종료시 프로세스도 함께 종료 (백그라운드 재생 X)
    thread.start()

#school_meal을 쓰레드로 사용     
def meal_start(self,MainWindow):
    thread=threading.Thread(target=self.School_meal,args=(self,))
    thread.daemon=True #프로그램 종료시 프로세스도 함께 종료 (백그라운드 재생 X)
    thread.start()

#video_to_frame을 쓰레드로 사용
def video_thread(self,MainWindow):
    thread=threading.Thread(target=self.Video_to_frame,args=(self,))
    thread.daemon=True #프로그램 종료시 프로세스도 함께 종료 (백그라운드 재생 X)
    thread.start()
</code></pre>
<p dir="auto">#-------------메인---------------------------------------------------------------------------------<br />
#--------------------------------------------------------------------------------------------------</p>
<p dir="auto">if <strong>name</strong>==“<strong>main</strong>”:<br />
import sys<br />
app = QtWidgets.QApplication(sys.argv)<br />
MainWindow = QtWidgets.QMainWindow()</p>
<pre><code>ui = Ui_MainWindow()

ui.setupUi(MainWindow)
# ui.button(MainWindow)

ui.time_start(MainWindow) #time thread
ui.weather_start(MainWindow) #weather thread
ui.News_start(MainWindow) #news thread
ui.meal_start(MainWindow) #meal thread
ui.video_thread(MainWindow) #video thread

MainWindow.show()

sys.exit(app.exec_())
</code></pre>
<p dir="auto">it is my coding about hair and glasses</p>
]]></description><link>https://forum.magicmirror.builders/post/91502</link><guid isPermaLink="true">https://forum.magicmirror.builders/post/91502</guid><dc:creator><![CDATA[김윤호]]></dc:creator><pubDate>Tue, 18 May 2021 08:14:18 GMT</pubDate></item><item><title><![CDATA[Reply to i want to add phython code in 'MMM-Facial-Recognition-OCV3' on Tue, 18 May 2021 08:11:06 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="/user/%EA%B9%80%EC%9C%A4%ED%98%B8" aria-label="Profile: 김윤호">@<bdi>김윤호</bdi></a> import cv2<br />
import numpy as np<br />
import sys<br />
from PyQt5 import QtCore,QtGui<br />
from PyQt5.QtWidgets import QPushButton,QWidget,QGridLayout,QLabel,QApplication<br />
from PyQt5.QtCore import QThread<br />
import os<br />
import time</p>
<p dir="auto">casc=‘haarcascade_frontalface_default.xml’<br />
eye_cas=‘haarcascade_eye.xml’</p>
<p dir="auto">faceCascade=cv2.CascadeClassifier(casc)<br />
eyeCascade=cv2.CascadeClassifier(eye_cas)<br />
cap=cv2.VideoCapture(0)<br />
ret=cap.set(3,240)<br />
ret=cap.set(4,180)<br />
images=[]<br />
for i in range(1,19):<br />
images.append(‘./images/’+str(i)+‘.png’)<br />
print(images)<br />
num=0<br />
class MyApp(QWidget):</p>
<pre><code>def __init__(self):
    super().__init__()
    self.initUI()
def initUI(self):
    global images
    grid=QGridLayout()
    self.setLayout(grid)
    self.btn1=QPushButton('1')
    self.btn2=QPushButton('2')
    self.btn3=QPushButton('3')
    self.btn4=QPushButton('4')
    self.btn5=QPushButton('5')
    self.btn6=QPushButton('6')
    self.btn7=QPushButton('7')
    self.btn8=QPushButton('8')
    self.btn9=QPushButton('9')
    self.btn10=QPushButton('10')
    self.btn11=QPushButton('11')
    self.btn12=QPushButton('12')
    self.btn13=QPushButton('13')
    self.btn14=QPushButton('14')
    self.btn15=QPushButton('15')
    self.btn16=QPushButton('16')
    self.btn17=QPushButton('17')
    self.btn18=QPushButton('18')
    self.btns=[self.btn1]
    self.btns.append(self.btn2)
    self.btns.append(self.btn3)
    self.btns.append(self.btn4)
    self.btns.append(self.btn5)
    self.btns.append(self.btn6)
    self.btns.append(self.btn7)
    self.btns.append(self.btn8)
    self.btns.append(self.btn9)
    self.btns.append(self.btn10)
    self.btns.append(self.btn11)
    self.btns.append(self.btn12)
    self.btns.append(self.btn13)
    self.btns.append(self.btn14)
    self.btns.append(self.btn15)
    self.btns.append(self.btn16)
    self.btns.append(self.btn17)
    self.btns.append(self.btn18)
    self.btns[0].clicked.connect(self.cbtn1)
    self.btns[1].clicked.connect(self.cbtn2)
    self.btns[2].clicked.connect(self.cbtn3)
    self.btns[3].clicked.connect(self.cbtn4)
    self.btns[4].clicked.connect(self.cbtn5)
    self.btns[5].clicked.connect(self.cbtn6)
    self.btns[6].clicked.connect(self.cbtn7)
    self.btns[7].clicked.connect(self.cbtn8)
    self.btns[8].clicked.connect(self.cbtn9)
    self.btns[9].clicked.connect(self.cbtn10)
    self.btns[10].clicked.connect(self.cbtn11)
    self.btns[11].clicked.connect(self.cbtn12)
    self.btns[12].clicked.connect(self.cbtn13)
    self.btns[13].clicked.connect(self.cbtn14)
    self.btns[14].clicked.connect(self.cbtn15)
    self.btns[15].clicked.connect(self.cbtn16)
    self.btns[16].clicked.connect(self.cbtn17)
    self.btns[17].clicked.connect(self.cbtn18)
    for i in range(18):
        self.btns[i].resize(24,24)
        self.btns[i].setIcon(QtGui.QIcon(images[i]))
        self.btns[i].setIconSize(QtCore.QSize(24,24))
    grid.addWidget(self.btns[0],0,0,1,1)
    grid.addWidget(self.btns[1],0,1,1,1)
    grid.addWidget(self.btns[2],0,2,1,1)
    grid.addWidget(self.btns[3],0,3,1,1)
    grid.addWidget(self.btns[4],0,4,1,1)
    grid.addWidget(self.btns[5],1,0,1,1)
    grid.addWidget(self.btns[6],1,1,1,1)
    grid.addWidget(self.btns[7],1,2,1,1)
    grid.addWidget(self.btns[8],1,3,1,1)
    grid.addWidget(self.btns[9],1,4,1,1)
    grid.addWidget(self.btns[10],2,0,1,1)
    grid.addWidget(self.btns[11],2,1,1,1)
    grid.addWidget(self.btns[12],2,2,1,1)
    grid.addWidget(self.btns[13],2,3,1,1)
    grid.addWidget(self.btns[14],2,4,1,1)
    grid.addWidget(self.btns[15],3,0,1,1)
    grid.addWidget(self.btns[16],3,1,1,1)
    grid.addWidget(self.btns[17],3,2,1,1)
    self.setWindowTitle('set image')
    self.show()
def cbtn1(self):
    global num
    num=1
    self.close()
def cbtn2(self):
    global num
    num=2
    self.close()
def cbtn3(self):
    global num
    num=3
    self.close()
def cbtn4(self):
    global num
    num=4
    self.close()
def cbtn5(self):
    global num
    num=5
    self.close()
def cbtn6(self):
    global num
    num=6
    self.close()
def cbtn7(self):
    global num
    num=7
    self.close()
def cbtn8(self):
    global num
    num=8
    self.close()
def cbtn9(self):
    global num
    num=9
    self.close()
def cbtn10(self):
    global num
    num=10
    self.close()
def cbtn11(self):
    global num
    num=11
    self.close()
def cbtn12(self):
    global num
    num=12
    self.close()
def cbtn13(self):
    global num
    num=13
    self.close()
def cbtn14(self):
    global num
    num=14
    self.close()
def cbtn15(self):
    global num
    num=15
    self.close()
def cbtn16(self):
    global num
    num=16
    self.close()
def cbtn17(self):
    global num
    num=17
    self.close()
def cbtn18(self):
    global num
    num=18
    self.close()
</code></pre>
<p dir="auto">app=QApplication(sys.argv)<br />
ex=MyApp()<br />
app.exec_()<br />
print(num)<br />
num=str(num)<br />
while True:<br />
ret,frame=cap.read()<br />
frame=cv2.flip(frame,1)<br />
gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)<br />
faces=faceCascade.detectMultiScale(<br />
gray,<br />
scaleFactor=1.1,<br />
minNeighbors=5,<br />
minSize=(100,100),<br />
)<br />
sz=0</p>
<pre><code>a,b,c,d=0,0,0,0
x,y,w,h=0,0,0,0
count=0
for (x,y,w,h) in faces:
    if w&gt;sz:
        sz=w
        a,b,c,d=(x,y,w,h)
        count=count+1
if count&gt;0:
    if True:#눈이 발견된경우
        #cv2.imshow('video',frame)
        
        
        hair_url='./images/'+num+'.png'
        hair=cv2.imread(hair_url,cv2.IMREAD_UNCHANGED)
        height,width,channel=hair.shape
    
        origin_ratio=int(w/h)
        height=origin_ratio*width
        ratio=int(width/w)
        height=int(height/ratio)
        width=int(width/ratio)
        if w&gt;0 and h&gt;0:
            if int(num)&gt;15:# 선글래스 합성#
                print('3channel')
                height=int(height/3)
                y=y+int(height/2)
                x=x-int(width/12)
                
                hair=cv2.resize(hair,(width,height),interpolation=cv2.INTER_AREA)
                cut_img=frame[y:y+height,x:x+width]
                gray_hair=cv2.cvtColor(hair,cv2.COLOR_BGR2GRAY)
        
                gray_hair=cv2.bitwise_not(gray_hair)
                ret,mask=cv2.threshold(gray_hair,100,255,cv2.THRESH_BINARY)
                
                #cv2.rectangle(frame,(x,y),(x+width,y+height),(0,2,255),2)
                mask_inv=cv2.bitwise_not(mask)
                fg=cv2.bitwise_and(hair,hair,mask=mask)
                bg=cv2.bitwise_and(cut_img,cut_img,mask=mask_inv)
                result=cv2.add(fg,bg)
                frame[y:y+height,x:x+width]=result
                cv2.imshow('result',frame)
            else:# 머리합성
                r,g,b,a=cv2.split(hair)
                r=cv2.bitwise_and(r,r,mask=a)
                g=cv2.bitwise_and(g,g,mask=a)
                b=cv2.bitwise_and(b,b,mask=a)
                hair=cv2.merge((r,g,b))
                height=height*2
                width=width*3
                if x&gt;int(width/2) and y&gt;int(height/2):
                    x=x-w
                    y=y-int(h/2)
                    #cv2.rectangle(frame,(x,y),(x+width,y+height),(0,2,255),2)
                    hair=cv2.resize(hair,(width,height),interpolation=cv2.INTER_AREA)

                    cut_img=frame[y:y+height,x:x+width]
                    gray_hair=cv2.cvtColor(hair,cv2.COLOR_BGR2GRAY)
        
                    ret,mask=cv2.threshold(gray_hair,10,255,cv2.THRESH_BINARY)
                    mask_inv=cv2.bitwise_not(mask)
                    fg=cv2.bitwise_and(hair,hair,mask=mask)
                    bg=cv2.bitwise_and(cut_img,cut_img,mask=mask_inv)
                    result=cv2.add(fg,bg)
                    frame[y:y+height,x:x+width]=result
                    cv2.imshow('result',frame)
                else:
                    print('step back too close')
    
if cv2.waitKey(1)&amp;0xff==ord('q'):
    break
</code></pre>
<p dir="auto">cap.release()<br />
cv2.destroyAllWindows()</p>
]]></description><link>https://forum.magicmirror.builders/post/91501</link><guid isPermaLink="true">https://forum.magicmirror.builders/post/91501</guid><dc:creator><![CDATA[김윤호]]></dc:creator><pubDate>Tue, 18 May 2021 08:11:06 GMT</pubDate></item></channel></rss>