Minggu, 09 Juli 2023

Python 2023

 # import warnings
# #warnings.filterwarnings('ignore')
# warnings.filterwarnings("ignore", category=FutureWarning)

import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning) 


# import warnings
# with warnings.catch_warnings():
#     warnings.filterwarnings("ignore",category=DeprecationWarning)    
#ENV PYTHONWARNINGS="ignore::DeprecationWarning"
#logging.captureWarnings(True)

# from warnings import filterwarnings
# filterwarnings("ignore")


import warnings
def fxn():
    warnings.warn("deprecated", DeprecationWarning)

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    fxn()

==============================================

import matplotlib.pyplot as plt
import matplotlib.image as img


def uk(img):
    a=np. array(img)
    print(type(a))
    print(a.shape)


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

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

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

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

def uk4(img):

    s =img.shape()
    print(s)
    return s

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

def rgb2gray1(rgb):
    return np.dot(rgb[...,:3], [0.2989, 0.5870, 0.1140])

def rgb2gray2(rgb):
    return cv2.cvtColor(rgb, cv2.COLOR_BGR2GRAY) 

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

def lihat(citra,label):
    asli = cv2.imread(citra)
    gray1 = rgb2gray1(asli)
    gray2 = rgb2gray2(asli)
    gray=gray2
    edges = cv2.Canny(gray,width,height)  

    fig = plt.figure()
    plt.subplot(1, 4, 1)
    plt.imshow(asli)
    plt.title('RGB '+label)

    plt.subplot(1, 4, 2)
    plt.imshow(gray1)
    plt.title('Gray1 '+label)

    plt.subplot(1, 4, 3)
    plt.imshow(gray2)
    plt.title('Gray2 '+label)

    plt.subplot(1, 4, 4)
    #plt.hist(gray2)
    plt.imshow(edges)
    plt.title('Edge '+label)

    plt.show()
    return 1

#####################################

cwd = os.getcwd()
dataset_dir=cwd+'\\datatraining\\'
print(cwd)
imagePaths = sorted(list(path.list_images(dataset_dir)))

size=128
labels = []
descs = []
data = []
train_set_files = os.listdir(dataset_dir) #list
Kategori = set([f.split('_')[0] for f in train_set_files])
JD=len(train_set_files)
for i in range(JD):
    NF=train_set_files[i]
    AL=dataset_dir + NF
    label=NF.split('_')[0]
    ####print(label+'='+AL)
    #os.path.join(dataset_dir, folder, sub_folder, filename)
    #img = plt.imread(AL)
    #labels.append(normalize_label(os.path.splitext(filename)[0]))
    img = cv2.imread(AL)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)            
    h, w = gray.shape
    ymin, ymax, xmin, xmax = h//3, h*2//3, w//3, w*2//3
    crop = gray[ymin:ymax, xmin:xmax] #43x43
    #rezize = cv.resize (crop, (size, size)) #128x128
    resize = cv2.resize(crop, (0,0), fx=0.5, fy=0.5) #22x22
    data.append(resize)
    labels.append(label)
    descs.append(AL)
    #print_progress(i, JD, AL) 
print(Kategori)



#################################


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


size  = 128
LOCALHOST="localhost"
ROOT="root"
PASS=""
DBASE="absen_pare"

db = MySQLdb.connect(LOCALHOST,ROOT,PASS,DBASE)
cursor = db.cursor()
print ("Koneksi Ke Database")

cwd = os.getcwd()
print('PWD='+cwd)
#dataset_dir=cwd+'\\datatraining\\'
dataset_dir='C:\\xampp7\\htdocs\\_2023\\NICO\\AbsenPare\\admin\\ypathfile\\'

imagePaths = sorted(list(path.list_images(dataset_dir)))
face_cascade = cv.CascadeClassifier('haarcascade_frontalface_default.xml') 
font=cv.FONT_HERSHEY_SIMPLEX
def uk(img):
    a=np. array(img)
    total=a.size
    print(str(type(img)),' :' ,str(total),' item')
    print(a.shape)
    
def uks(img):
    a=np. asarray(img)
    total=a.size
    print(str(type(img)),' :' ,str(total),' item')
    print(a.shape)

def getWajah(dataset_dir,NF,F1,F2):
    AL=dataset_dir + NF
    print(AL)
    #gray = cv.cvtColor(img, cv2.COLOR_BGR2GRAY) 
    img = cv.imread(AL)
    gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)  
    
    roi=gray
    pathsimpan = dataset_dir.replace(F1,F2)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)    
    for (x,y,w,h) in faces:
        #cv2.rectangle(img,(x,y),(x+w=[],y+h),(255,0,0),2)          
        roi = gray[y:y+h, x:x+w]    
        #myresize = cv2.resize(roi, (0,0), fx=0.5, fy=0.5) #22x22)
        
    GB= pathsimpan + NF
    print('PathGB:',GB) 
    cv.imwrite(GB,roi)
    h, w = roi.shape
    ymin, ymax, xmin, xmax = h//3, h*2//3, w//3, w*2//3
    roi2= roi[ymin:ymax, xmin:xmax] #43x43 crop
    myresize = cv.resize(roi2, (0,0), fx=0.5, fy=0.5)
    #myresize = cv2.resize (roi2, (size, size)) #128x128 rezize
    return myresize

def updateDB(cursor,db,idx,status,dkolom1,dkolom2,nf): 
    sql = "UPDATE `tb_absensi`  set `tag`='1',`res_masuk`='%s',`catatan_masuk`='%s',`foto_masuk2`='%s'  where `id_absensi`='%s'" % (dkolom1,dkolom2,nf,idx)
    if status=='Pulang':
        sql = "UPDATE `tb_absensi`  set `tag`='1',`res_pulang`='%s',`catatan_pulang`='%s',`foto_pulang2`='%s'  where `id_absensi`='%s'" % (dkolom1,dkolom2,nf,idx)
    print(sql)
    v=0
    try:
        cursor.execute(sql)
        db.commit()
        v=1
    except:
        db.rollback()
        return v
    
def lastDB(cursor,db,idx):
    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"
    cursor.execute("SELECT `id_absensi` FROM `tb_absensi` where `tag`='0' order by id_absensi desc limit 0,1")
    v=0
    for row in cursor.fetchall():
        v=row[0]

    return v



============================

new_string = string.replace("r", "e" )

SET DAN LIST:

Input : {1, 2, 3, 4} #SET
Output : [1, 2, 3, 4] #LIST
my_set = {'Geeks', 'for', 'geeks'}
 
s = list(my_set)
print(s)
NA = NA.astype(float)
import numpy as np

#list of strings
A = ['33.33', '33.33', '33.33', '33.37']
print A

#numpy of strings
arr = np.array(A)
print arr

#numpy of float32's
arr = np.array(A, dtype=np.float32)
print arr

#post process
print np.mean(arr), np.max(arr), np.min(arr)



import numpy as np
A = ['33.33', '33.33', '33.33', '33.37']
# convert to float
arr = np.array(map(float, A)) 
# calc values
print np.mean(arr), np.max(arr), np.min(arr)



To convert your strings to floats, the simplest way is a list comprehension:

A = ['33.33', '33.33', '33.33', '33.37']
floats = [float(e) for e in A]

Now you can convert to an array:

array_A = np.array(floats)

The rest is probably known to you:

mean, min, max = np.mean(array_A), np.min(array_A), np.max(array_A)




import numpy as np

A = ["33.33", "33.33", "33.33", "33.37"]
for i in range(0,len(A)):
    n = A[i]
    n=float(n)
    A[i] = n

NA = np.asarray(A)

AVG = np.mean(NA, axis=0)
maxx = max(A)
minn = min(A)

print (AVG)
print (maxx)
print (minn)










https://stackoverflow.com/questions/42663171/how-to-convert-a-list-of-strings-into-a-numeric-numpy-array

https://www.simplilearn.com/tutorials/python-tutorial/list-to-string-in-python

https://www.freecodecamp.org/news/python-string-to-array-how-to-convert-text-to-a-list/





birthdate = "19/10/1993"
birthdate_list
=
birthdate.split("/")

print(birthdate_list)
print(type(birthdate_list))

#output
#['19', '10', '1993']
#<class 'list'>

------------------------

birthdate = "19/10/1993"
birthdate_list
=
birthdate.split("/")
str_to_int
=
list(map(int, birthdate_list))

print(type(str_to_int))
print(str_to_int)

#output
#<class 'list'>
#[19, 10, 1993]