added new jupyter notebook

This commit is contained in:
kicap 2024-05-06 08:30:22 +08:00
parent 9b30890b15
commit 531cb04fe4
1 changed files with 175 additions and 149 deletions

View File

@ -1,5 +1,15 @@
{ {
"cells": [ "cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "f90cb956-250b-454e-855e-fefcd0ff880a",
"metadata": {},
"outputs": [],
"source": [
"## Import Library"
]
},
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 1, "execution_count": 1,
@ -29,67 +39,55 @@
], ],
"source": [ "source": [
"cap = cv2.VideoCapture('video/video.mp4')\n", "cap = cv2.VideoCapture('video/video.mp4')\n",
"# mendapatkan jumlah frame, fps, lebar, dan tinggi dari video\n",
"frames_count, fps, width, height = cap.get(cv2.CAP_PROP_FRAME_COUNT), cap.get(cv2.CAP_PROP_FPS), cap.get(\n", "frames_count, fps, width, height = cap.get(cv2.CAP_PROP_FRAME_COUNT), cap.get(cv2.CAP_PROP_FPS), cap.get(\n",
" cv2.CAP_PROP_FRAME_WIDTH), cap.get(cv2.CAP_PROP_FRAME_HEIGHT)\n", " cv2.CAP_PROP_FRAME_WIDTH), cap.get(cv2.CAP_PROP_FRAME_HEIGHT)\n",
"width = int(width)\n", "width = int(width)\n",
"height = int(height)\n", "height = int(height)\n",
"print(frames_count, fps, width, height)\n", "print(frames_count, fps, width, height)\n",
"\n", "\n",
"# membuat sebuah frame pandas dengan jumlah baris yang sama dengan jumlah frame\n", "# membuat data frame pandas dengan jumlah baris sama dengan jumlah frame\n",
"df = pd.DataFrame(index=range(int(frames_count)))\n", "df = pd.DataFrame(index=range(int(frames_count)))\n",
"df.index.name = \"Frame\" # menandai kolom frame\n", "df.index.name = \"Frame\" # frame dalam bahasa indonesia\n",
"\n", "\n",
"framenumber = 0 # mencatat frame saat ini\n", "framenumber = 0 # mencatat frame saat ini\n",
"carscrossedup = 0 # mencatat mobil yang melintasi jalan ke atas\n", "carscrossedup = 0 # mencatat mobil yang melintasi atas\n",
"carscrosseddown = 0 # mencatat mobil yang melintasi jalan ke bawah\n", "carscrosseddown = 0 # mencatat mobil yang melintasi bawah\n",
"carids = [] # daftar kosong untuk menyimpan ID mobil\n", "carids = [] # list kosong untuk menambah id mobil\n",
"caridscrossed = [] # daftar kosong untuk menyimpan ID mobil yang sudah melintasi\n", "caridscrossed = [] # list kosong untuk menambah id mobil yang telah melintasi\n",
"totalcars = 0 # mencatat jumlah total mobil\n", "totalcars = 0 # mencatat total mobil\n",
"\n", "\n",
"fgbg = cv2.createBackgroundSubtractorMOG2() # membuat pengambil gambar latar belakang\n", "fgbg = cv2.createBackgroundSubtractorMOG2() # membuat subtractor latar belakang MOG2\n",
"\n", "\n",
"# informasi untuk mulai menyimpan video\n", "# informasi untuk memulai menyimpan file video\n",
"ret, frame = cap.read() # mengimpor gambar\n", "ret, frame = cap.read() # impor gambar\n",
"ratio = .5 # rasio ukuran pengubahan ukuran\n", "ratio = .5 # rasio pengubah ukuran\n",
"image = cv2.resize(frame, (0, 0), None, ratio, ratio) # mengubah ukuran gambar\n", "image = cv2.resize(frame, (0, 0), None, ratio, ratio) # ubah ukuran gambar\n",
"width2, height2, channels = image.shape\n" "width2, height2, channels = image.shape\n",
"# video = cv2.VideoWriter('penghitung_kendaraan.avi', cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), fps, (height2, width2), 1)"
] ]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 3, "execution_count": null,
"id": "5c8d5645-9df8-457c-88d7-2d3bbc0fade9", "id": "1c53be2e-1fc0-46af-b8dd-84cd6b1dffdb",
"metadata": {}, "metadata": {},
"outputs": [ "outputs": [],
{
"ename": "KeyboardInterrupt",
"evalue": "",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mKeyboardInterrupt\u001b[0m Traceback (most recent call last)",
"Cell \u001b[0;32mIn[3], line 265\u001b[0m\n\u001b[1;32m 260\u001b[0m \u001b[38;5;66;03m# video.write(image) # save the current image to video file from earlier\u001b[39;00m\n\u001b[1;32m 261\u001b[0m \n\u001b[1;32m 262\u001b[0m \u001b[38;5;66;03m# adds to framecount\u001b[39;00m\n\u001b[1;32m 263\u001b[0m framenumber \u001b[38;5;241m=\u001b[39m framenumber \u001b[38;5;241m+\u001b[39m \u001b[38;5;241m1\u001b[39m\n\u001b[0;32m--> 265\u001b[0m k \u001b[38;5;241m=\u001b[39m \u001b[43mcv2\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mwaitKey\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;28;43mint\u001b[39;49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m1000\u001b[39;49m\u001b[38;5;241;43m/\u001b[39;49m\u001b[43mfps\u001b[49m\u001b[43m)\u001b[49m\u001b[43m)\u001b[49m \u001b[38;5;241m&\u001b[39m \u001b[38;5;241m0xff\u001b[39m \u001b[38;5;66;03m# int(1000/fps) is normal speed since waitkey is in ms\u001b[39;00m\n\u001b[1;32m 266\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m k \u001b[38;5;241m==\u001b[39m \u001b[38;5;241m27\u001b[39m:\n\u001b[1;32m 267\u001b[0m \u001b[38;5;28;01mbreak\u001b[39;00m\n",
"\u001b[0;31mKeyboardInterrupt\u001b[0m: "
]
}
],
"source": [ "source": [
"while True:\n", "while True:\n",
"\n", "\n",
" ret, frame = cap.read() # mengimpor gambar\n", " ret, frame = cap.read() # impor gambar\n",
"\n", "\n",
" if ret: # jika ada frame lanjutkan dengan kode\n", " if ret: # jika ada frame lanjutkan kode\n",
"\n", "\n",
" image = cv2.resize(frame, (0, 0), None, ratio, ratio) # mengubah ukuran gambar\n", " image = cv2.resize(frame, (0, 0), None, ratio, ratio) # ubah ukuran gambar\n",
"\n", "\n",
" gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # mengubah gambar ke hitam putih\n", " gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # konversi gambar ke warna abu-abu\n",
"\n", "\n",
" fgmask = fgbg.apply(gray) # menggunakan pengambil gambar latar belakang\n", " fgmask = fgbg.apply(gray) # menggunakan pengurangan latar belakang MOG2\n",
"\n", "\n",
" # menerapkan berbagai batasan pada fgmask untuk menyaring mobil\n", " # menerapkan tingkat kesulitan pada fgmask untuk mencoba mengisolasi mobil\n",
" # perlu bermain dengan setelan tersebut hingga mobil dapat diidentifikasi dengan mudah\n", " # perlu mencoba berbagai pengaturan hingga mobil mudah diidentifikasi\n",
" kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)) # kernel untuk dilakukan pada morphology\n", " kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)) # membuat kernel untuk operasi morfologi\n",
" closing = cv2.morphologyEx(fgmask, cv2.MORPH_CLOSE, kernel)\n", " closing = cv2.morphologyEx(fgmask, cv2.MORPH_CLOSE, kernel)\n",
" opening = cv2.morphologyEx(closing, cv2.MORPH_OPEN, kernel)\n", " opening = cv2.morphologyEx(closing, cv2.MORPH_OPEN, kernel)\n",
" dilation = cv2.dilate(opening, kernel)\n", " dilation = cv2.dilate(opening, kernel)\n",
@ -98,37 +96,38 @@
" # membuat kontur\n", " # membuat kontur\n",
" contours, hierarchy = cv2.findContours(bins, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[-2:]\n", " contours, hierarchy = cv2.findContours(bins, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[-2:]\n",
"\n", "\n",
" # menggunakan konveks hull untuk membuat poligon di sekitar kontur\n", " # menggunakan konveks hull untuk membuat poligon kait dengan kontur\n",
" hull = [cv2.convexHull(c) for c in contours]\n", " hull = [cv2.convexHull(c) for c in contours]\n",
"\n", "\n",
" # menggambar kontur\n", " # menggambar kontur\n",
" cv2.drawContours(image, hull, -1, (0, 255, 0), 3)\n", " cv2.drawContours(image, hull, -1, (0, 255, 0), 3)\n",
"\n", "\n",
" # garis dibuat untuk menghentikan menghitung kontur, perlu dilakukan karena mobil yang jauh akan menjadi satu kontur besar\n", " # garis dibuat untuk menghentikan penghitungan kontur, diperlukan karena mobil jauh menjadi kontur satu\n",
" lineypos = 225\n", " lineypos = 100\n",
" cv2.line(image, (0, lineypos), (width, lineypos), (255, 0, 0), 5)\n", " cv2.line(image, (0, lineypos), (width, lineypos), (255, 0, 0), 5)\n",
"\n", "\n",
" # garis y pos dibuat untuk menghitung kontur\n", " # garis y posisi dibuat untuk menghitung kontur\n",
" lineypos2 = 250\n", " lineypos2 = 125\n",
" cv2.line(image, (0, lineypos2), (width, lineypos2), (0, 255, 0), 5)\n", " cv2.line(image, (0, lineypos2), (width, lineypos2), (0, 255, 0), 5)\n",
"\n", "\n",
" # minimum area untuk kontur\n", " # area minimal untuk kontur agar tidak dihitung sebagai rumit\n",
" minarea = 300\n", " minarea = 400\n",
"\n", "\n",
" # maksimum area untuk kontur\n", " # area maksimal untuk kontur, dapat cukup besar untuk bus\n",
" maxarea = 50000\n", " maxarea = 40000\n",
"\n", "\n",
" # vektor untuk x dan y lokasi centroid di frame saat ini\n", " # vektor untuk x dan y lokasi tengah kontur dalam frame saat ini\n",
" cxx = np.zeros(len(contours))\n", " cxx = np.zeros(len(contours))\n",
" cyy = np.zeros(len(contours))\n", " cyy = np.zeros(len(contours))\n",
"\n", "\n",
" for i in range(len(contours)): # mengulangi seluruh kontur dalam frame saat ini\n", " for i in range(len(contours)): # melakukan iterasi pada semua kontur dalam frame saat ini\n",
"\n", "\n",
" if hierarchy[0, i, 3] == -1: # menggunakan hierarchy untuk hanya menghitung kontur induk (tidak termasuk dalam kontur lain)\n", " # menggunakan hierarki untuk hanya menghitung kontur induk (kontur yang tidak berada dalam kontur lain)\n",
" if hierarchy[0, i, 3] == -1:\n",
"\n", "\n",
" area = cv2.contourArea(contours[i]) # menghitung area kontur\n", " area = cv2.contourArea(contours[i]) # menghitung luas kontur\n",
"\n", "\n",
" if minarea < area < maxarea: # area threshold untuk kontur\n", " if minarea < area < maxarea: # menggunakan area sebagai garis pembatas untuk kontur\n",
"\n", "\n",
" # menghitung centroid dari kontur\n", " # menghitung centroid dari kontur\n",
" cnt = contours[i]\n", " cnt = contours[i]\n",
@ -136,129 +135,152 @@
" cx = int(M['m10'] / M['m00'])\n", " cx = int(M['m10'] / M['m00'])\n",
" cy = int(M['m01'] / M['m00'])\n", " cy = int(M['m01'] / M['m00'])\n",
"\n", "\n",
" if cy > lineypos: # menghapus kontur yang di atas garis\n", " if cy > lineypos: # menghapus kontur yang berada di atas garis (y dimulai dari atas)\n",
"\n", "\n",
" # mengambil titik teratas, kiri, dan lebar dari kontur untuk membuat kotak\n", " # mengambil titik koordinat untuk membuat kotak lingkaran\n",
" # x,y adalah kiri atas dan w,h adalah lebar dan tinggi\n",
" x, y, w, h = cv2.boundingRect(cnt)\n", " x, y, w, h = cv2.boundingRect(cnt)\n",
"\n", "\n",
" # membuat kotak di sekitar kontur\n", " # membuat kotak lingkaran dari kontur\n",
" cv2.rectangle(image, (x, y), (x + w, y + h), (255, 0, 0), 2)\n", " cv2.rectangle(image, (x, y), (x + w, y + h), (255, 0, 0), 2)\n",
"\n", "\n",
" # Menuliskan teks centroid untuk memastikan kembali nanti\n", " # Menambahkan teks centroid untuk memverifikasi pada tahap selanjutnya\n",
" cv2.putText(image, str(cx) + \",\" + str(cy), (cx + 10, cy + 10), cv2.FONT_HERSHEY_SIMPLEX,\n", " cv2.putText(image, str(cx) + \",\" + str(cy), (cx + 10, cy + 10), cv2.FONT_HERSHEY_SIMPLEX,\n",
" .3, (0, 0, 255), 1)\n", " 0.3, (0, 0, 255), 1)\n",
"\n", "\n",
" cv2.drawMarker(image, (cx, cy), (0, 0, 255), cv2.MARKER_STAR, markerSize=5, thickness=1,\n", " cv2.drawMarker(image, (cx, cy), (0, 0, 255), cv2.MARKER_STAR, markerSize=5, thickness=1,\n",
" line_type=cv2.LINE_AA)\n", " line_type=cv2.LINE_AA)\n",
"\n", "\n",
" # menambahkan centroid yang lulus pada kriteria ke dalam list centroid\n", " # menambahkan centroid yang telah memenuhi kriteria ke dalam list centroid\n",
" cxx[i] = cx\n", " cxx[i] = cx\n",
" cyy[i] = cy\n", " cyy[i] = cy\n",
"\n", "\n",
" # menghapus entri 0 dari list centroid\n", " # menghapus nol dalam vector centroid yang tidak dihitung (centroid yang tidak dikirim ke dataframe)\n",
" cxx = cxx[cxx != 0]\n", " cxx = cxx[cxx != 0]\n",
" cyy = cyy[cyy != 0]\n", " cyy = cyy[cyy != 0]\n",
"\n", "\n",
" # list kosong untuk nanti menyimpan indices centroid yang di tambahkan ke dataframe\n", " # list kosong untuk nanti mencatat indeks centroid yang dikirim ke dataframe\n",
" minx_index2 = []\n", " minx_index2 = []\n",
" miny_index2 = []\n", " miny_index2 = []\n",
"\n", "\n",
" # batas maksimum untuk radius dari centroid dari frame saat ini untuk dianggap sama dengan centroid dari frame sebelumnya\n", " # jumlah maksimum yang diizinkan untuk centroid dalam frame saat ini untuk dikaitkan dengan centroid dari frame sebelumnya\n",
" maxrad = 25\n", " maxrad = 25\n",
"\n", "\n",
" # Bagian ini mengelola centroid dan menetapkan mereka untuk carid lama atau carid baru\n", " # bagian berikut mengelola centroid dan mengasignasinya ke id mobil lama atau id mobil baru\n",
"\n", "\n",
" # jika terdapat centroid dalam area yang ditentukan\n",
" if len(cxx): # jika ada centroid dalam area yang ditentukan\n", " if len(cxx): # jika ada centroid dalam area yang ditentukan\n",
"\n", "\n",
" if not carids: # jika carids kosong\n", " if not carids: # jika daftar carids kosong\n",
"\n", "\n",
" for i in range(len(cxx)): # melalui semua centroid\n", " for i in range(len(cxx)): # melakukan loop sebanyak centroid yang ada\n",
"\n", "\n",
" carids.append(i) # menambahkan car id ke list carids kosong\n", " carids.append(i) # menambahkan id mobil ke dalam daftar kosong\n",
" df[str(carids[i])] = \"\" # menambahkan kolom ke dataframe sesuai carid\n", " df[str(carids[i])] = \"\" # menambahkan kolom ke dalam dataframe berdasarkan id mobil\n",
"\n", "\n",
" # menetapkan nilai centroid ke frame (baris) dan carid (kolom) yang sesuai\n", " # mengisi nilai centroid pada frame saat ini dan id mobil yang sesuai\n",
" df.at[int(framenumber), str(carids[i])] = [cxx[i], cyy[i]]\n", " df.at[int(framenumber), str(carids[i])] = [cxx[i], cyy[i]]\n",
"\n", "\n",
" totalcars = carids[i] + 1 # menambahkan count car\n", " totalcars = carids[i] + 1 # menambahkan 1 pada jumlah mobil\n",
"\n", "\n",
" else: # jika carids sudah ada\n", " else: # jika sudah ada id mobil\n",
"\n", "\n",
" dx = np.zeros((len(cxx), len(carids))) # array baru untuk menghitung deltas\n", " dx = np.zeros((len(cxx), len(carids))) # array untuk menghitung deltanya\n",
" dy = np.zeros((len(cyy), len(carids))) # array baru untuk menghitung deltas\n", " dy = np.zeros((len(cyy), len(carids))) # array untuk menghitung deltanya\n",
"\n", "\n",
" for i in range(len(cxx)): # melalui semua centroid\n", " for i in range(len(cxx)): # melakukan loop sebanyak centroid yang ada\n",
"\n", "\n",
" for j in range(len(carids)): # melalui semua car id yang sudah ada\n", " for j in range(len(carids)): # melakukan loop sebanyak id mobil yang ada\n",
"\n", "\n",
" # mengambil centroid dari frame sebelumnya untuk carid tertentu\n", " # mengambil centroid dari frame sebelumnya untuk id mobil tertentu\n",
" oldcxcy = df.iloc[int(framenumber - 1)][str(carids[j])]\n", " oldcxcy = df.iloc[int(framenumber - 1)][str(carids[j])]\n",
"\n", "\n",
" # mengambil centroid dari frame saat ini yang tidak selalu sesuai dengan centroid frame sebelumnya\n", " # mengambil centroid dari frame sekarang yang tidak selalu sesuai dengan centroid dari frame sebelumnya\n",
" curcxcy = np.array([cxx[i], cyy[i]])\n", " curcxcy = np.array([cxx[i], cyy[i]])\n",
"\n", "\n",
" if not oldcxcy: # periksa apakah centroid sebelumnya kosong jika arah sudah tidak ada di layar\n", " if not oldcxcy: # jika centroid dari frame sebelumnya kosong karena mobil keluar layar\n",
"\n", "\n",
" continue # lanjutkan ke carid berikutnya\n", " continue # lanjutkan ke id mobil selanjutnya\n",
"\n", "\n",
" else: # hitung delta centroid untuk membandingkan dengan centroid frame saat ini\n", " else: # hitung deltanya untuk dibandingkan dengan centroid dari frame sekarang\n",
"\n", "\n",
" dx[i, j] = oldcxcy[0] - curcxcy[0]\n", " dx[i, j] = oldcxcy[0] - curcxcy[0]\n",
" dy[i, j] = oldcxcy[1] - curcxcy[1]\n", " dy[i, j] = oldcxcy[1] - curcxcy[1]\n",
"\n", "\n",
" for j in range(len(carids)): # melalui semua car id saat ini\n", " for j in range(len(carids)): # melakukan loop sebanyak id mobil yang ada\n",
"\n", "\n",
" sumsum = np.abs(dx[:, j]) + np.abs(dy[:, j]) # menghitung delta wrt car id\n", " jumlahjumlah = np.abs(dx[:, j]) + np.abs(dy[:, j]) # menghitung jumlah delta wrt id mobil tertentu\n",
"\n", "\n",
" # mengambil indeks centroid yang memiliki nilai delta minimum dan ini indeks benar\n", " # mencari indeks id mobil yang memiliki nilai minimum dan ini indeks yang tepat\n",
" correctindextrue = np.argmin(np.abs(sumsum))\n", " indeksindextrue = np.argmin(np.abs(jumlahjumlah))\n",
" minx_index = correctindextrue\n", " minx_index = indeksindextrue\n",
" miny_index = correctindextrue\n", " miny_index = indeksindextrue\n",
"\n", "\n",
" # mengambil delta nilai minimum untuk dibandingkan dengan radius\n", " # mengambil nilai delta untuk id mobil yang dipilih\n",
" mindx = dx[minx_index, j]\n", " deltadeltadx = dx[minx_index, j]\n",
" mindy = dy[miny_index, j]\n", " deltadeltady = dy[miny_index, j]\n",
"\n", "\n",
" if mindx == 0 and mindy == 0 and np.all(dx[:, j] == 0) and np.all(dy[:, j] == 0):\n", " if deltadeltadx == 0 and deltadeltady == 0 and np.all(dx[:, j] == 0) and np.all(dy[:, j] == 0):\n",
" # periksa apakah minimum nilai adalah 0 dan semua delta adalah nol\n", " # periksa apakah nilai minimum adalah 0 dan periksa apakah semua delta adalah nol karena ini adalah kumpulan kosong\n",
" # delta dapat berupa nol jika centroid tidak bergerak\n", " # delta dapat berupa nol jika centroid tidak berpindah\n",
"\n", "\n",
" continue # lanjutkan ke carid berikutnya\n", " continue # lanjutkan ke id mobil selanjutnya\n",
"\n", "\n",
" else:\n", " else:\n",
"\n", "\n",
" # jika delta nilai adalah kurang dari maksimal radius maka tambahkan centroid ke carid sebelumnya\n", " # jika nilai delta kurang dari radius maksimum maka tambahkan centroid ke id mobil yang sesuai\n",
" if np.abs(mindx) < maxrad and np.abs(mindy) < maxrad:\n", " if np.abs(deltadeltadx) < maxrad and np.abs(deltadeltady) < maxrad:\n",
"\n", "\n",
" # tambahkan centroid ke carid yang sudah ada\n", " # menambahkan centroid ke id mobil yang sudah ada\n",
" df.at[int(framenumber), str(carids[j])] = [cxx[minx_index], cyy[miny_index]]\n", " df.at[int(framenumber), str(carids[j])] = [cxx[minx_index], cyy[miny_index]]\n",
" minx_index2.append(minx_index) # tambahkan semua indeks yang ditambahkan ke carid ke list\n", " minx_index2.append(minx_index) # menambahkan indeks centroid yang sudah ditambahkan ke id mobil lain\n",
" miny_index2.append(miny_index)\n", " miny_index2.append(miny_index)\n",
"\n", "\n",
" currentcars = 0 # current cars on screen\n", " for i in range(len(cxx)): # melakukan loop sebanyak centroid yang ada\n",
" currentcarsindex = [] # current cars on screen carid index\n",
"\n", "\n",
" for i in range(len(carids)): # loops through all carids\n", " # jika centroid tidak ada dalam list minindex maka mobil baru perlu ditambahkan\n",
" if i not in minx_index2 and miny_index2:\n",
"\n", "\n",
" df[str(totalcars)] = \"\" # membuat kolom baru untuk mobil baru yang tercatat\n",
" totalcars = totalcars + 1 # menambahkan jumlah mobil yang tercatat\n",
" t = totalcars - 1 # t adalah placeholder untuk jumlah mobil\n",
" carids.append(t) # menambahkan id mobil ke list id mobil\n",
" df.at[int(framenumber), str(t)] = [cxx[i], cyy[i]] # menambahkan centroid ke mobil yang sudah ada\n",
"\n",
" elif curcxcy[0] and not oldcxcy and not minx_index2 and not miny_index2:\n",
" # jika centroid saat ini ada namun centroid sebelumnya tidak ada\n",
" # mobil baru perlu ditambahkan jika minindex2 kosong\n",
"\n",
" df[str(totalcars)] = \"\" # membuat kolom baru untuk mobil baru yang tercatat\n",
" totalcars = totalcars + 1 # menambahkan jumlah mobil yang tercatat\n",
" t = totalcars - 1 # t adalah placeholder untuk jumlah mobil\n",
" carids.append(t) # menambahkan id mobil ke list id mobil\n",
" df.at[int(framenumber), str(t)] = [cxx[i], cyy[i]] # menambahkan centroid ke mobil yang sudah ada\n",
"\n",
" # Bagian di bawah menglabel centroid yang ada di layar\n",
"\n",
" currentcars = 0 # mobil yang ada di layar\n",
" currentcarsindex = [] # indeks id mobil yang ada di layar\n",
"\n",
" for i in range(len(carids)): # melakukan loops sebanyak jumlah id mobil\n",
"\n",
" # memeriksa frame saat ini untuk mengetahui id mobil yang sedang aktif\n",
" # dengan memeriksa adanya centroid pada frame saat ini untuk id mobil tertentu\n",
" if df.at[int(framenumber), str(carids[i])] != '':\n", " if df.at[int(framenumber), str(carids[i])] != '':\n",
" # checks the current frame to see which car ids are active\n",
" # by checking in centroid exists on current frame for certain car id\n",
"\n", "\n",
" currentcars = currentcars + 1 # adds another to current cars on screen\n", " currentcars = currentcars + 1 # menambahkan mobil yang ada di layar\n",
" currentcarsindex.append(i) # adds car ids to current cars on screen\n", " currentcarsindex.append(i) # menambahkan id mobil yang ada di layar\n",
"\n", "\n",
" for i in range(currentcars): # loops through all current car ids on screen\n", " for i in range(currentcars): # melakukan loops sebanyak jumlah mobil yang ada di layar\n",
"\n", "\n",
" # grabs centroid of certain carid for current frame\n", " # mengambil centroid untuk id mobil tertentu pada frame saat ini\n",
" curcent = df.iloc[int(framenumber)][str(carids[currentcarsindex[i]])]\n", " curcent = df.iloc[int(framenumber)][str(carids[currentcarsindex[i]])]\n",
"\n", "\n",
" # grabs centroid of certain carid for previous frame\n", " # mengambil centroid untuk id mobil tertentu pada frame sebelumnya\n",
" oldcent = df.iloc[int(framenumber - 1)][str(carids[currentcarsindex[i]])]\n", " oldcent = df.iloc[int(framenumber - 1)][str(carids[currentcarsindex[i]])]\n",
"\n", "\n",
" if curcent: # if there is a current centroid\n", " if curcent: # jika ada centroid pada frame saat ini\n",
"\n", "\n",
" # On-screen text for current centroid\n", " # Teks di layar untuk centroid saat ini\n",
" cv2.putText(image, \"Centroid\" + str(curcent[0]) + \",\" + str(curcent[1]),\n", " cv2.putText(image, \"Centroid\" + str(curcent[0]) + \",\" + str(curcent[1]),\n",
" (int(curcent[0]), int(curcent[1])), cv2.FONT_HERSHEY_SIMPLEX, .5, (0, 255, 255), 2)\n", " (int(curcent[0]), int(curcent[1])), cv2.FONT_HERSHEY_SIMPLEX, .5, (0, 255, 255), 2)\n",
"\n", "\n",
@ -268,26 +290,27 @@
" cv2.drawMarker(image, (int(curcent[0]), int(curcent[1])), (0, 0, 255), cv2.MARKER_STAR, markerSize=5,\n", " cv2.drawMarker(image, (int(curcent[0]), int(curcent[1])), (0, 0, 255), cv2.MARKER_STAR, markerSize=5,\n",
" thickness=1, line_type=cv2.LINE_AA)\n", " thickness=1, line_type=cv2.LINE_AA)\n",
"\n", "\n",
" if oldcent: # checks if old centroid exists\n", " # Periksa apakah centroid lama ada\n",
" # adds radius box from previous centroid to current centroid for visualization\n", " # Tambahkan kotak radius dari centroid lama ke centroid saat ini untuk visualisasi\n",
" xstart = oldcent[0] - maxrad\n", " if oldcent:\n",
" ystart = oldcent[1] - maxrad\n", " xmulai = oldcent[0] - maxrad\n",
" xwidth = oldcent[0] + maxrad\n", " ymulai = oldcent[1] - maxrad\n",
" yheight = oldcent[1] + maxrad\n", " xakhir = oldcent[0] + maxrad\n",
" cv2.rectangle(image, (int(xstart), int(ystart)), (int(xwidth), int(yheight)), (0, 125, 0), 1)\n", " yakhir = oldcent[1] + maxrad\n",
" cv2.rectangle(image, (int(xmulai), int(ymulai)), (int(xakhir), int(yakhir)), (0, 125, 0), 1)\n",
"\n", "\n",
" # checks if old centroid is on or below line and curcent is on or above line\n", " # Periksa apakah centroid lama di bawah garis dan centroid baru di atas garis\n",
" # to count cars and that car hasn't been counted yet\n", " # Untuk menghitung mobil dan memastikan mobil tidak dihitung dua kali\n",
" if oldcent[1] >= lineypos2 and curcent[1] <= lineypos2 and carids[\n", " if oldcent[1] >= lineypos2 and curcent[1] <= lineypos2 and carids[\n",
" currentcarsindex[i]] not in caridscrossed:\n", " currentcarsindex[i]] not in caridscrossed:\n",
"\n", "\n",
" carscrossedup = carscrossedup + 1\n", " carscrossedup = carscrossedup + 1\n",
" cv2.line(image, (0, lineypos2), (width, lineypos2), (0, 0, 255), 5)\n", " cv2.line(image, (0, lineypos2), (width, lineypos2), (0, 0, 255), 5)\n",
" caridscrossed.append(\n", " caridscrossed.append(\n",
" currentcarsindex[i]) # adds car id to list of count cars to prevent double counting\n", " currentcarsindex[i]) # Tambahkan id mobil ke daftar mobil yang dihitung untuk mencegah penghitungan dua kali\n",
"\n", "\n",
" # checks if old centroid is on or above line and curcent is on or below line\n", " # Periksa apakah centroid lama di atas garis dan centroid baru di bawah garis\n",
" # to count cars and that car hasn't been counted yet\n", " # Untuk menghitung mobil dan memastikan mobil tidak dihitung dua kali\n",
" elif oldcent[1] <= lineypos2 and curcent[1] >= lineypos2 and carids[\n", " elif oldcent[1] <= lineypos2 and curcent[1] >= lineypos2 and carids[\n",
" currentcarsindex[i]] not in caridscrossed:\n", " currentcarsindex[i]] not in caridscrossed:\n",
"\n", "\n",
@ -295,57 +318,60 @@
" cv2.line(image, (0, lineypos2), (width, lineypos2), (0, 0, 125), 5)\n", " cv2.line(image, (0, lineypos2), (width, lineypos2), (0, 0, 125), 5)\n",
" caridscrossed.append(currentcarsindex[i])\n", " caridscrossed.append(currentcarsindex[i])\n",
"\n", "\n",
" # Top left hand corner on-screen text\n", " # menampilkan jumlah mobil yang melintasi atas\n",
" cv2.rectangle(image, (0, 0), (250, 100), (255, 0, 0), -1) # background rectangle for on-screen text\n", " cv2.putText(image, \"Mobil yang Melintasi Atas: \" + str(carscrossedup), (0, 15), cv2.FONT_HERSHEY_SIMPLEX, .5, (255, 255, 255),\n",
"\n",
" cv2.putText(image, \"Cars in Area: \" + str(currentcars), (0, 15), cv2.FONT_HERSHEY_SIMPLEX, .5, (0, 170, 0), 1)\n",
"\n",
" cv2.putText(image, \"Cars Crossed Up: \" + str(carscrossedup), (0, 30), cv2.FONT_HERSHEY_SIMPLEX, .5, (0, 170, 0),\n",
" 1)\n", " 1)\n",
"\n", "\n",
" cv2.putText(image, \"Cars Crossed Down: \" + str(carscrosseddown), (0, 45), cv2.FONT_HERSHEY_SIMPLEX, .5,\n", " # menampilkan jumlah mobil yang melintasi bawah\n",
" (0, 170, 0), 1)\n", " cv2.putText(image, \"Mobil yang Melintasi Bawah: \" + str(carscrosseddown), (0, 30), cv2.FONT_HERSHEY_SIMPLEX, .5,\n",
" (255, 255, 255), 1)\n",
"\n", "\n",
" cv2.putText(image, \"Total Cars Detected: \" + str(len(carids)), (0, 60), cv2.FONT_HERSHEY_SIMPLEX, .5,\n", " # # menampilkan jumlah total mobil yang terdeteksi\n",
" (0, 170, 0), 1)\n", " # cv2.putText(image, \"Total Mobil yang Terdeteksi: \" + str(len(carids)), (0, 60), cv2.FONT_HERSHEY_SIMPLEX, .5,\n",
" # (255, 255, 255), 1)\n",
"\n", "\n",
" cv2.putText(image, \"Frame: \" + str(framenumber) + ' of ' + str(frames_count), (0, 75), cv2.FONT_HERSHEY_SIMPLEX,\n", " # menampilkan frame saat ini dan total frame\n",
" .5, (0, 170, 0), 1)\n", " cv2.putText(image, \"Frame: \" + str(framenumber) + ' dari ' + str(frames_count), (0, 45), cv2.FONT_HERSHEY_SIMPLEX,\n",
" .5, (255, 255, 255), 1)\n",
"\n", "\n",
" cv2.putText(image, 'Time: ' + str(round(framenumber / fps, 2)) + ' sec of ' + str(round(frames_count / fps, 2))\n", " # menampilkan waktu yang sudah berlalu dan total waktu\n",
" + ' sec', (0, 90), cv2.FONT_HERSHEY_SIMPLEX, .5, (0, 170, 0), 1)\n", " cv2.putText(image, 'Waktu: ' + str(round(framenumber / fps, 2)) + ' detik dari ' + str(round(frames_count / fps, 2))\n",
" + ' detik', (0, 60), cv2.FONT_HERSHEY_SIMPLEX, .5, (255, 255, 255), 1)\n",
"\n", "\n",
" # displays images and transformations\n", " # menampilkan images dan transformasi\n",
" cv2.imshow(\"countours\", image)\n", " cv2.imshow(\"Output\", image)\n",
" cv2.moveWindow(\"countours\", 0, 0)\n", " cv2.moveWindow(\"Output\", 0, 0)\n",
"\n", "\n",
" cv2.imshow(\"fgmask\", fgmask)\n", " cv2.imshow(\"gray\", gray)\n",
" cv2.moveWindow(\"fgmask\", int(width * ratio), 0)\n", " cv2.moveWindow(\"gray\", int(width * ratio), 0)\n",
"\n", "\n",
" cv2.imshow(\"closing\", closing)\n", " cv2.imshow(\"closing\", closing)\n",
" cv2.moveWindow(\"closing\", width, 0)\n", " cv2.moveWindow(\"closing\", width, 0)\n",
"\n", "\n",
" cv2.imshow(\"opening\", opening)\n", " # cv2.imshow(\"opening\", opening)\n",
" cv2.moveWindow(\"opening\", 0, int(height * ratio))\n", " # cv2.moveWindow(\"opening\", 0, int(height * ratio))\n",
"\n", "\n",
" cv2.imshow(\"dilation\", dilation)\n", " # cv2.imshow(\"dilation\", dilation)\n",
" cv2.moveWindow(\"dilation\", int(width * ratio), int(height * ratio))\n", " # cv2.moveWindow(\"dilation\", int(width * ratio), int(height * ratio))\n",
"\n", "\n",
" cv2.imshow(\"binary\", bins)\n", " # cv2.imshow(\"binary\", bins)\n",
" cv2.moveWindow(\"binary\", width, int(height * ratio))\n", " # cv2.moveWindow(\"binary\", width, int(height * ratio))\n",
"\n", "\n",
" # video.write(image) # save the current image to video file from earlier\n",
"\n", "\n",
" # adds to framecount\n", " # adds to framecount\n",
" framenumber = framenumber + 1\n", " framenumber = framenumber + 1\n",
"\n", "\n",
" k = cv2.waitKey(int(1000/fps)) & 0xff # int(1000/fps) is normal speed since waitkey is in ms\n", " # Menunggu key dari user dalam milidetik, fps adalah frame per detik, dan 0xff adalah binary\n",
" if k == 27:\n", " # bahasa indonesia: Menunggu key dari user dalam milidetik\n",
" k = cv2.waitKey(int(1000/fps)) & 0xff \n",
" if k == 27: # bahasa indonesia: Jika key nya adalah 27 (ESC) maka break loop\n",
" break\n", " break\n",
"\n", "\n",
" else: # if video is finished then break loop\n", " else: # bahasa indonesia: Jika video selesai maka break loop\n",
"\n", "\n",
" break\n" "\n",
" break\n",
"\n"
] ]
}, },
{ {