Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Hôm nay mình hướng dẫn các bạn viết một ứng dụng nhỏ bằng python về nhận hiện khuôn mặt.

Yêu cầu: Nhận diện khuôn mặt bằng camera + xin chào "tên bạn"

Bước 1: Các bạn cài đặt python nhé, bản mình dùng trong ví dụ này là version 3.10.7. Chú ý khi cài nhớ cài đặt patch luôn nha.

Do mình cài rồi nên hiện như vầy á.

Bước 2: Traning model 
 - Các bạn vào đây nhé: https://teachablemachine.withgoogle.com/train/image
 - Các bạn up ảnh hoặc  sử dụng camera (Nếu không có thì dùng điện thoại làm camera cũng được ah)
 - Sau khi traning xong các bạn tải model về, nãy mình chưa lưu nên làm biếng chụp ảnh lại quá
 - Trên popup lưu model có chỗ copy code á, bạn copy đoạn code vô để làm hàm nhân diện (lười làm lại chỗ này, các bạn chút lấy code bên dưới cũng được)

Bước 3: Vào visual code tạo file nhandien.py (Hoặc bất kỳ IDE nào các bạn quen nha)
- Cài đặt một số thư viện chỗ import trong hình nhen.
- Chú ý là: mình dùng câu lệch #pip3 install ten-package để cài đặt

Cài đặt các thư viện trong import vô nhen

Code:
Hàm xin chào :
def speak(text):
    tts = gTTS(text = text, lang = language, slow = False)
    tts.save("sound.mp3")
    playsound.playsound("sound.mp3", True)
    os.remove("sound.mp3")

Hàm chụp ảnh từ cam và lưu lại với tên test.jpg :
camera = cv2.VideoCapture(0)
def capture_image():
    ret,frame = camera.read()
    if ret == True :
        cv2.imwrite('test.jpg',frame)

Hàm nhận diện khuôn mặt (Copy trên teachablemachine về nhen) có edit lại 1 chút.
def face_detaction():
    np.set_printoptions(suppress=True)
    # Load the model
    model = tf.keras.models.load_model('keras_model.h5')

    # Create the array of the right shape to feed into the keras model
    # The 'length' or number of images you can put into the array is
    # determined by the first position in the shape tuple, in this case 1.
    data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)
    # Replace this with the path to your image
    image = Image.open('test.jpg')
    # resize the image to a 224x224 with the same strategy as in TM2:
    # resizing the image to be at least 224x224 and then cropping from the center
    size = (224, 224)
    image = ImageOps.fit(image, size, Image.ANTIALIAS)

    # turn the image into a numpy array
    image_array = np.asarray(image)
    # Normalize the image
    normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1
    # Load the image into the array
    data[0] = normalized_image_array

    # run the inference
    prediction = model.predict(data)
    print(prediction)

    name = ["Anh Nen", "Hoàng Duy"]
    index = 1
    max_value = -1
    for i in range(0, len(prediction[0])):
        if max_value < prediction[0][i]:
            max_value = prediction[0][i]
            index = i
    print("Result: ", name[index])
    print("Exactly: ", max_value)

    speak("Xin chào " + name[index] )

Gọi lại hàm:
while True:
    capture_image()
    face_detaction()


Các chú ý

1. Nếu bạn cài thư viện python không được do lỗi patch quá dài , thì vào chỉnh registry nhé

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem
Chỉnh về : 1

2. Lỗi không thể run puthon file ở Visual Studio Code
Vào Microsoft Store tải python hoặc set enviroment rồi log off lại máy





Bước 1: Tải Python tại đây: https://www.python.org/downloads/, chọn phiên bản bạn cần


Bước 2: Chạy tệp trình cài đặt và làm theo các bước để cài đặt Python
Trong quá trình cài đặt, hãy chọn Add Python to environment variables. Thao tác này sẽ thêm Python vào các biến môi trường và bạn có thể chạy Python từ bất kỳ phần nào của máy tính.


Bước 3: Test sau khi cài đặt

Bước 4: Cài đặt IDE để code, các bạn có thể tải các phần mềm như Sublime text, VS Code hoặc Notepad++ cũng được.