Semua Tentang Belajar Teknologi Digital Dalam Kehidupan Sehari - Hari

Minggu, 14 Juli 2024

[raspi - yolo] Google Colab & Ngrok - Mengolah Gambar Untuk Raspi Zero W

 


Cloud computing adalah hal yang cukup lumrah kita temui untuk membantu semua pekerjaan komputasi kita secara jarak jauh dan dimanapun. Saya sering menggunakan vps - google cloud - aws untuk membatu banyak pekerjaan saya dan kali ini saya akan gunakan google colab yang memiliki kemampuan menjalankan script python pada cloud. Permasalahannya adalah jika kita ingin mengakses google colab secara http API /Post /Get maka tidak akan ada IP public yang diberikan oleh google. Sehingga kita membutuhkan fasilitas tunneling "Gratis" bernama NGROK

Ngrok adalah alat yang memungkinkan pengembang untuk mengekspos server lokal ke internet dengan cara yang aman. Ini sangat berguna untuk pengembangan dan pengujian aplikasi web, terutama ketika perlu memeriksa bagaimana aplikasi tersebut berinteraksi dengan layanan eksternal atau perangkat lain yang tidak berada di jaringan lokal. 

Silahkan daftar dengan akun google kamu dan jangan lupa dapatkan authtoken tunneling untuk praktek yang aakan saya contohkan dibawah.



Pada google colab, setelah terkoneksi dengan benar, maka dibutuhkan mengunduh file konfigurasi yolo v3 seperti berikut ini 

!wget https://pjreddie.com/media/files/yolov3.weights
!wget https://raw.githubusercontent.com/pjreddie/darknet/master/cfg/yolov3.cfg
!wget https://raw.githubusercontent.com/pjreddie/darknet/master/data/coco.names

Setellah itu perlu menginstall library python untuk  pyngrok sedangkan flask sudah tersedia secara default

!pip install pyngrok

Dan response nya seperti berikut

Collecting pyngrok Downloading pyngrok-7.1.6-py3-none-any.whl (22 kB) Requirement already satisfied: PyYAML>=5.1 in /usr/local/lib/python3.10/dist-packages (from pyngrok) (6.0.1) Installing collected packages: pyngrok Successfully installed pyngrok-7.1.6

Brikut ini adalah script python untuk mengolah gambar via flask yang mirip dengan tulisan sebelumnya disini . Jangan lupa mengambil authtoken tunnel di dashbor ngrok


from flask import Flask, request, jsonify
import cv2
import numpy as np
import time
from pyngrok import ngrok
import threading



# Replace 'your_authtoken' with your actual authtoken from ngrok dashboard
ngrok.set_auth_token('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')

app = Flask(__name__)


yolo = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg")
classes = []

with open("coco.names", "r") as file:
    classes = [line.strip() for line in file.readlines()]


layer_names = yolo.getLayerNames()
output_layers = [layer_names[i - 1] for i in yolo.getUnconnectedOutLayers()]

colorRed = (0,0,255)
colorGreen = (0,255,0)

# #Loading Images
def detect_objects(img):
    starting_time = time.time()
    height, width, channels = img.shape

    # # Detecting objects
    blob = cv2.dnn.blobFromImage(img, 0.00392, (255, 255), (0, 0, 0), True, crop=False)

    yolo.setInput(blob)
    outputs = yolo.forward(output_layers)

    class_ids = []
    confidences = []
    boxes = []
    for output in outputs:
        for detection in output:
            scores = detection[5:]
            class_id = np.argmax(scores)
            confidence = scores[class_id]
            if confidence > 0.4 and class_id == 0 : # 0 = person
                center_x = int(detection[0] * width)
                center_y = int(detection[1] * height)
                w = int(detection[2] * width)
                h = int(detection[3] * height)

                x = int(center_x - w / 2)
                y = int(center_y - h / 2)

                boxes.append([x, y, w, h])
                confidences.append(float(confidence))
                class_ids.append(class_id)


    indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
    org = 0
    mob = 0
    mot = 0

    for i in range(len(boxes)):
        if i in indexes:
            if class_ids[i] == 0:
                org = org + 1
                label = 'orang : ' + repr(org)
            elif class_ids[i] == 2:
                mob = mob + 1
                label = 'mobil : ' + repr(mob)
            elif class_ids[i] == 3:
                mot = mot + 1
                label = 'motor : ' + repr(mot)
            x, y, w, h = boxes[i]
            #label = str(classes[class_ids[i]]) + ', x=' +repr(x) + ',y=' +repr(y)
            #label = str(classes[class_ids[i]]) + '- no: ' + repr(i+1)
            cv2.rectangle(img, (x, y), (x + w, y + h), colorGreen, 3)
            cv2.putText(img, label, (x, y -5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255) )




    print("{")
    print(f"\"Jumlah Orang\": {org},")
    print(f"\"Jumlah Mobil\": {mob},")
    print(f"\"Jumlah Motor\": {mot},")

    elapsed_time = time.time() - starting_time
    print("\"processing time\":" + repr(elapsed_time)  )
    print("}")
    #cv2.imshow("Image", img)
    cv2.imwrite("output.jpg",img)
    #cv2.waitKey(0)
    #cv2.destroyAllWindows()
    return {"Orang": org, "Mobil": mob, "Motor": mot, "time": elapsed_time }

@app.route("/detect", methods=["POST"])
def detect():
    file = request.files["image"]
    npimg = np.fromfile(file, np.uint8)
    image = cv2.imdecode(npimg, cv2.IMREAD_COLOR)

    # Measure start time
    start_time = time.time()

    result = detect_objects(image)

    # Measure end time
    end_time = time.time()

    # Calculate processing time
    processing_time = end_time - start_time
    result['processing_time'] = float(processing_time)  # Ensure it's a float

    return jsonify(result)


# Function to run Flask server
def run_flask():
    app.run(port=5000)

# Start Flask server in a separate thread
flask_thread = threading.Thread(target=run_flask)
flask_thread.start()

# Set up ngrok tunnel
public_url = ngrok.connect(5000)
print("Flask server is running at:", public_url)

Sedangkan script pada raspberry pi zero tetap sama dengan tulisan sebelumnya. Jalankan script pada google colab sampai muncul alamat public dari ngrok tunneling.


 * Serving Flask app '__main__'
 * Debug mode: off
INFO:werkzeug:WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on http://127.0.0.1:5000
INFO:werkzeug:Press CTRL+C to quit
Flask server is running at: NgrokTunnel: "https://029a-34-105-62-129.ngrok-free.app" -> "http://localhost:5000"


Hasilnya luar biasa cepat dan gratis pula !




Dikarenakan alamat publik dari tunneling ngrok berubah setiap kali script dijalankan pada google colab, maka saya sudah berhasil mengakalinya dengan memanfaatkan MQTT sebagai pengirim alamat tunnel nya dan dapat digunakan oleh banyak pengguna semisal banyak raspberry pi zero w + cam di beberapa titik lampu. Ini akan saya bahas jika ada yang tertarik dengan tulisan saya ini (by request).

SELAMAT BELAJAR !
Share:

0 komentar:

Posting Komentar

Kontak Penulis



12179018.png (60×60)
+628155737755

Mail : ahocool@gmail.com

Site View

Categories

555 (8) 7 segmen (3) adc (4) amplifier (2) analog (19) android (12) antares (11) arduino (26) artikel (11) attiny (3) attiny2313 (19) audio (5) baterai (5) blog (1) bluetooth (1) chatgpt (2) cmos (2) crypto (2) dasar (46) digital (11) dimmer (5) display (3) esp8266 (26) euro2020 (13) gcc (1) iklan (1) infrared (2) Input Output (3) iot (72) jam (7) jualan (12) kereta api (1) keyboard (1) keypad (3) kios pulsa (2) kit (6) komponen (17) komputer (3) komunikasi (1) kontrol (8) lain-lain (8) lcd (2) led (14) led matrix (6) line tracer (1) lm35 (1) lora (11) lorawan (2) MATV (1) memory (1) metal detector (4) microcontroller (70) micropython (6) mikrokontroler (1) mikrokontroller (14) mikrotik (5) modbus (9) mqtt (3) ninmedia (5) ntp (1) paket belajar (19) palang pintu otomatis (1) parabola (88) pcb (2) power (1) praktek (2) project (33) proyek (1) python (8) radio (28) raspberry pi (9) remote (1) revisi (1) rfid (1) robot (1) rpm (2) rs232 (1) script break down (3) sdcard (3) sensor (2) sharing (3) signage (1) sinyal (1) sms (6) software (18) solar (1) solusi (1) tachometer (2) technology (1) teknologi (2) telegram (2) telepon (9) televisi (167) television (28) telkomiot (3) transistor (2) troubleshoot (3) tulisan (93) tutorial (108) tv digital (6) tvri (2) vu meter (2) vumeter (2) wav player (3) wayang (1) wifi (3) yolo (7)

Arsip Blog

Diskusi


kaskus
Forum Hobby Elektronika