Rabu, 18 Desember 2019

Aplikasi Deteksi Hijab

PYTHON: appHijab
In [2]:
import os
import MySQLdb
import time
from time import gmtime, strftime
from random import randint
import signal
from PIL import Image
import requests
import cv2
import numpy as np
from matplotlib import pyplot as plt
In [3]:
def indexAda(kalimat,cari):
    result=-1
    try:
        result = kalimat.index(cari)
    except:
        result=-1
    return result

def mtrim(s):
    if s.endswith(" "): s = s[:-1]
    if s.startswith(" "): s = s[1:]
    return s

def display(img):
    cv2.imshow("show",img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    b=edges.shape[0]
    c=edges.shape[1]

    for i in range(b): 
        for j in range(c):
            D=edges[i][j]
            print(str(i)+","+str(j)+"="+str(D))
    return img   

def myresize(img,b,c):
    dim = (b, c)
    resized = cv2.resize(img, dim, interpolation = cv2.INTER_AREA)
    return resized

def resshape(img):
    width = int(img.shape[0])
    height = int(img.shape[1])
    wh=width * height
    dim = (wh, 1)
    resized = cv2.resize(img, dim, interpolation = cv2.INTER_AREA)
    return resized

def uk1(img):
    width = int(img.shape[0])
    height = int(img.shape[1])
    print(width ,' x ' , height)
    return (width ,' x ' , height)

def uk2(img):
    width =len(img[0])
    height = len(img[1])
    print(width ,' x ' , height)
    return (width ,' x ' , height)

def uk3(img):
    s =len(img)
    print(s)
    return s

def uk4(img):
    s =img.shape()
    print(s)
    return s

def uk5(img):
    width =len(img[0])
    print(width)
    return width

def model(img):
    lap=type(img)
    print(lap)
    return lap

def list2int(list1):
    list1=np.array(list1,dtype=int)
    return list1


def rgb2gray(img):
    I= cv2.imread(img)
    G= cv2.cvtColor(I, cv2.COLOR_BGR2GRAY)
    return G

def simpanDB(cursor,db,gambar,nik,status):
    note=""
    tgl=strftime("%Y-%m-%d", gmtime()) #u waktu
    jam=strftime("%H:%M:%S", gmtime()) #u waktu
        
    stgl=strftime("%Y%m%d", gmtime()) #u namafile
    sjam=strftime("%H%M%S", gmtime()) #u namafile
    NF="Img"+stgl+sjam+".jpg"
    keterangan="Image Valid"
      #status =proses, 1 cocok, 2 gagal
    sql = 'INSERT INTO `tb_hasil` ( `tanggal`, `jam`, `status`, `keterangan`,`gambar`,`nik`) VALUES ("%s", "%s", "%s","%s","%s","%s")' % (tgl, jam,status,note,keterangan,nik)
    print (sql)
    v=0
    try:
        cursor.execute(sql)
        db.commit()
        v=1
    except:
        db.rollback()
        
    return v    

def updateDB(cursor,db,idx,status):
    sql = "UPDATE `tb_barang`  set `label`='1',`status`='%s' where id_barang='%s'" % (status,idx)
    print(sql)
    v=0
    try:
        cursor.execute(sql)
        db.commit()
        v=1
    except:
        db.rollback()
        return v
    
def lastDB(cursor,db,idx):
    cursor.execute("SELECT `id_barang` FROM `tb_barang` where `label`='0' order by id_barang desc limit 0,1")
    v=0
    for row in cursor.fetchall():
        v=row[0]

    return v
In [ ]:
 
In [4]:
PATH_UJI='C:/xampp/htdocs/app_hijab2019/ypathfile/'
PATH_TRAIN='C:/xampp/htdocs/app_hijab2019/ypathfile/'
In [ ]:
threshold = 0.7   #60/100
IMG=""
while (True): #True && 
    cocok=-1
    ada=0
    
    db = MySQLdb.connect("localhost","root","","app_hijab2019")
    cursor = db.cursor()
    #print ("Connect...")

    cursor.execute("SELECT `id_barang`,`gambar` FROM `tb_barang` where `label`='0' order by `id_barang` asc limit 0,1")
    for row in cursor.fetchall():
        if cocok==-1:
            id_barang=row[0]
            gambar=row[1]

            print(str(id_barang)+"#"+str(gambar))
            #updateDB(cursor,db,id_barang)
            
            ada=1
            AL=str(PATH_UJI+gambar)
            print(AL)
            img_rgb = cv2.imread(AL)
            IMGUJI= cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
            time.sleep(1)

            cocok=-1
            index=0
            cursor.execute("SELECT `id`,`gambar` FROM `tb_datalatih` order by `id` asc")
            for row in cursor.fetchall():
                index=index+1
                if cocok==-1:
                    id=row[0]
                    gambarLatih=row[1]

                    fototraining=PATH_TRAIN+gambarLatih
                    IMGTRAIN =rgb2gray(fototraining)

                    res = cv2.matchTemplate(IMGUJI,IMGTRAIN,cv2.TM_CCOEFF_NORMED)
                    print("Akurasi Gambar :"+str( index)+"="+str(res)+" %")
                    loc = np.where( res >= threshold)
                    for pt in zip(*loc[::-1]):
                        cocok=cocok+1
   
                
            if cocok==-1: 
                print("Tidak Cocok sama datalatih")
                updateDB(cursor,db,id_barang,"INValid")
            else:
                ALU=PATH_UJI+'zoom.jpg'
                print("Cocok dengan datalatih")
                updateDB(cursor,db,id_barang,"Valid")
                cv2.imwrite(ALU,img_rgb)
                time.sleep(1)

    time.sleep(1)
    db.close()
In [ ]:
 



import os
import MySQLdb
import time
from time import gmtime, strftime
from random import randint
import signal
from PIL import Image
import requests
import cv2
import numpy as np
from matplotlib import pyplot as plt



def indexAda(kalimat,cari):
    result=-1
    try:
        result = kalimat.index(cari)
    except:
        result=-1
    return result

def mtrim(s):
    if s.endswith(" "): s = s[:-1]
    if s.startswith(" "): s = s[1:]
    return s

def display(img):
    cv2.imshow("show",img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    b=edges.shape[0]
    c=edges.shape[1]

    for i in range(b): 
        for j in range(c):
            D=edges[i][j]
            print(str(i)+","+str(j)+"="+str(D))
    return img   

def myresize(img,b,c):
    dim = (b, c)
    resized = cv2.resize(img, dim, interpolation = cv2.INTER_AREA)
    return resized

def resshape(img):
    width = int(img.shape[0])
    height = int(img.shape[1])
    wh=width * height
    dim = (wh, 1)
    resized = cv2.resize(img, dim, interpolation = cv2.INTER_AREA)
    return resized

def uk1(img):
    width = int(img.shape[0])
    height = int(img.shape[1])
    print(width ,' x ' , height)
    return (width ,' x ' , height)

def uk2(img):
    width =len(img[0])
    height = len(img[1])
    print(width ,' x ' , height)
    return (width ,' x ' , height)

def uk3(img):
    s =len(img)
    print(s)
    return s

def uk4(img):
    s =img.shape()
    print(s)
    return s

def uk5(img):
    width =len(img[0])
    print(width)
    return width

def model(img):
    lap=type(img)
    print(lap)
    return lap

def list2int(list1):
    list1=np.array(list1,dtype=int)
    return list1


def rgb2gray(img):
    I= cv2.imread(img)
    G= cv2.cvtColor(I, cv2.COLOR_BGR2GRAY)
    return G

def simpanDB(cursor,db,gambar,nik,status):
    note=""
    tgl=strftime("%Y-%m-%d", gmtime()) #u waktu
    jam=strftime("%H:%M:%S", gmtime()) #u waktu
        
    stgl=strftime("%Y%m%d", gmtime()) #u namafile
    sjam=strftime("%H%M%S", gmtime()) #u namafile
    NF="Img"+stgl+sjam+".jpg"
    keterangan="Image Valid"
      #status =proses, 1 cocok, 2 gagal
    sql = 'INSERT INTO `tb_hasil` ( `tanggal`, `jam`, `status`, `keterangan`,`gambar`,`nik`) VALUES ("%s", "%s", "%s","%s","%s","%s")' % (tgl, jam,status,note,keterangan,nik)
    print (sql)
    v=0
    try:
        cursor.execute(sql)
        db.commit()
        v=1
    except:
        db.rollback()
        
    return v    

def updateDB(cursor,db,idx,status):
    sql = "UPDATE `tb_barang`  set `label`='1',`status`='%s' where id_barang='%s'" % (status,idx)
    print(sql)
    v=0
    try:
        cursor.execute(sql)
        db.commit()
        v=1
    except:
        db.rollback()
        return v
    
def lastDB(cursor,db,idx):
    cursor.execute("SELECT `id_barang` FROM `tb_barang` where `label`='0' order by id_barang desc limit 0,1")
    v=0
    for row in cursor.fetchall():
        v=row[0]

    return v



PATH_UJI='C:/xampp/htdocs/app_hijab2019/ypathfile/'
PATH_TRAIN='C:/xampp/htdocs/app_hijab2019/ypathfile/'


threshold = 0.7   #60/100
IMG=""
while (True): #True && 
    cocok=-1
    ada=0
    
    db = MySQLdb.connect("localhost","root","","app_hijab2019")
    cursor = db.cursor()
    #print ("Connect...")

    cursor.execute("SELECT `id_barang`,`gambar` FROM `tb_barang` where `label`='0' order by `id_barang` asc limit 0,1")
    for row in cursor.fetchall():
        if cocok==-1:
            id_barang=row[0]
            gambar=row[1]

            print(str(id_barang)+"#"+str(gambar))
            #updateDB(cursor,db,id_barang)
            
            ada=1
            AL=str(PATH_UJI+gambar)
            print(AL)
            img_rgb = cv2.imread(AL)
            IMGUJI= cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
            time.sleep(1)

            cocok=-1
            index=0
            cursor.execute("SELECT `id`,`gambar` FROM `tb_datalatih` order by `id` asc")
            for row in cursor.fetchall():
                index=index+1
                if cocok==-1:
                    id=row[0]
                    gambarLatih=row[1]

                    fototraining=PATH_TRAIN+gambarLatih
                    IMGTRAIN =rgb2gray(fototraining)

                    res = cv2.matchTemplate(IMGUJI,IMGTRAIN,cv2.TM_CCOEFF_NORMED)
                    print("Akurasi Gambar :"+str( index)+"="+str(res)+" %")
                    loc = np.where( res >= threshold)
                    for pt in zip(*loc[::-1]):
                        cocok=cocok+1
   
                
            if cocok==-1: 
                print("Tidak Cocok sama datalatih")
                updateDB(cursor,db,id_barang,"INValid")
            else:
                ALU=PATH_UJI+'zoom.jpg'
                print("Cocok dengan datalatih")
                updateDB(cursor,db,id_barang,"Valid")
                cv2.imwrite(ALU,img_rgb)
                time.sleep(1)

    time.sleep(1)
    db.close()