Tutorial yang akan saya tuliskan pada blog kali ini merupakan penggabungan dari beberapa tulisan maupun video kuliah saya sebelumnya, sehingga untuk kelancaran tutorial harap menyimak pembahasan sebelumnya yaitu :
- Yolo dan python untuk deteksi objek : Videonya dilihat disini
- Menjalankan python pada node-red : Klik disini
import cv2
import numpy as np
import time
import sys
#penghitung waktu proses
starting_time = time.time()
#cmd windows pake spasi biar bisa dieksekusi pada node-red
if len(sys.argv) != 2:
print("Cara Pakai: python<spasi>script.py<spasi>alamat/stream_url")
sys.exit(1)
# ambil cmd pada bagian sumber streaming sesuai usage
stream_url = sys.argv[1]
# Open the video stream
cap = cv2.VideoCapture(stream_url)
# ambil 1 frame terakhir aja
ret, img = cap.read()
# alamat direktori yolo harus lengkap
yolo = cv2.dnn.readNet("G:\\IOT\\node_red\\yolov3.weights", "G:\\IOT\\node_red\\yolov3.cfg")
classes = []
with open("G:\\IOT\\node_red\\coco.names", "r") as file:
classes = [line.strip() for line in file.readlines()]
#proses yolo
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
#img = cv2.imread(name)
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)
# deteksi 3 object orang (0), mobil(2) dan motor(3)
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.5 and ( class_id == 0 or class_id == 2 or class_id == 3): # 3 objek
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)
#simpan koordinat dan nilai keyakinan
boxes.append([x, y, w, h])
confidences.append(float(confidence))
class_ids.append(class_id)
#perhitungan indeks dan 3 object
indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
org = 0
mob = 0
mot = 0
#kotak dan tulisan deteksi objek
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]
cv2.rectangle(img, (x, y), (x + w, y + h), colorGreen, 3)
cv2.putText(img, label, (x, y -5), cv2.FONT_HERSHEY_DUPLEX, 2, (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("}")
## dibawah ini pilih mau simpan gambar atau tampilkan saja, sesuaikan kebutuhan
#cv2.imshow("Image", img)
cv2.imwrite("G:\\IOT\\node_red\\output.jpg",img) #
#cv2.waitKey(0)
#cv2.destroyAllWindows()
[
{
"id": "5e5b156e7f57b6cc",
"type": "tab",
"label": "aisi555 dot com",
"disabled": false,
"info": "",
"env": []
},
{
"id": "d4809067.5e61a",
"type": "inject",
"z": "5e5b156e7f57b6cc",
"name": "nama stream",
"props": [
{
"p": "payload"
},
{
"p": "topic",
"vt": "str"
}
],
"repeat": "",
"crontab": "",
"once": false,
"onceDelay": "20",
"topic": "",
"payload": "https://cctvjss.jogjakota.go.id/atcs/ATCS_Lampu_Merah_SugengJeroni1.stream/chunklist_w758098670.m3u8",
"payloadType": "str",
"x": 190,
"y": 40,
"wires": [
[
"7a4e8130.b846f8"
]
]
},
{
"id": "7a4e8130.b846f8",
"type": "exec",
"z": "5e5b156e7f57b6cc",
"command": "python G:\\IOT\\node_red\\yolo_stream.py ",
"addpay": "payload",
"append": "",
"useSpawn": "false",
"timer": "",
"winHide": false,
"oldrc": false,
"name": "",
"x": 520,
"y": 40,
"wires": [
[
"c95a2a0563597a2b",
"50dcecd33a88080d"
],
[],
[]
]
},
{
"id": "c95a2a0563597a2b",
"type": "debug",
"z": "5e5b156e7f57b6cc",
"name": "debug 6",
"active": true,
"tosidebar": true,
"console": false,
"tostatus": false,
"complete": "payload",
"targetType": "msg",
"statusVal": "",
"statusType": "auto",
"x": 920,
"y": 20,
"wires": []
},
{
"id": "50dcecd33a88080d",
"type": "trigger",
"z": "5e5b156e7f57b6cc",
"name": "",
"op1": "",
"op2": "G:/IOT/node_red/output.jpg",
"op1type": "nul",
"op2type": "str",
"duration": "250",
"extend": false,
"overrideDelay": false,
"units": "ms",
"reset": "",
"bytopic": "all",
"topic": "topic",
"outputs": 1,
"x": 920,
"y": 80,
"wires": [
[
"d6cf44e31cac223d"
]
]
},
{
"id": "d6cf44e31cac223d",
"type": "image viewer",
"z": "5e5b156e7f57b6cc",
"name": "",
"width": "800",
"data": "payload",
"dataType": "msg",
"active": true,
"x": 190,
"y": 120,
"wires": [
[]
]
}
]
- Yolo v3 yang digunakan masih menggunakan weights bawaan dari yolo, sehingga tingkat keberhasilan pendeteksiannya hanya dibilang "cukup" karena object yg bisa dideteksi banyak dan umum.
- Untuk pendeteksian objek yang spesifik dan lebih teliti bisa melakukan training pada object-object yang di kehendaki saja dan akan dibahas pada kesempatan lainnya
- Tingkat kualitas kamera sangat menentukan deteksi object