diff --git a/Deteksi Plat Nomor Dengan Faster RCNN & SSD MobileNet/generate_tfrecord.py b/Deteksi Plat Nomor Dengan Faster RCNN & SSD MobileNet/generate_tfrecord.py new file mode 100644 index 0000000..f90948f --- /dev/null +++ b/Deteksi Plat Nomor Dengan Faster RCNN & SSD MobileNet/generate_tfrecord.py @@ -0,0 +1,149 @@ + +# Import Library +from __future__ import division +from __future__ import print_function +from __future__ import absolute_import + +# untuk mengatur lokasi path +import os + +# dalam script ini digunakan untuk konversi image kedalam format byte +import io + +# untuk mengolah csv +import pandas as pd + +# untuk generate tfrecord +import tensorflow as tf + +# untuk mengolah/read data image +from PIL import Image + +# dalam script ini digunakan untuk transformasi setiap value yg akan dijadikan tfrecord +from object_detection.utils import dataset_util + +# untuk keperluan mengolah array, list, dict +from collections import namedtuple, OrderedDict + + +# parsing parameter dari command python (train/test, data csv, path output untuk tfrecord) +flags = tf.app.flags +flags.DEFINE_string('type', '', 'Type of CSV input (train/test)') +flags.DEFINE_string('csv_input', '', 'Path to the CSV input') +flags.DEFINE_string('output_path', '', 'Path to output TFRecord') +FLAGS = flags.FLAGS +# --------------------------------------------------------------------- + + +# Translasi nama kelas dalam bentuk text ke bentuk indeks integer +def class_text_to_int(row_label): + if row_label == 'plate': + return 1 + else: + None +# --------------------------------------------------------------------- + + +# untuk memisahkan data csv yg terbaca kedalam beberapa kolom (delimiter) +def split(df, group): + data = namedtuple('data', ['filename', 'object']) + gb = df.groupby(group) + return [data(filename, gb.get_group(x)) for filename, x in zip(gb.groups.keys(), gb.groups)] +# --------------------------------------------------------------------- + + +# Fungsi untuk menghasilkan tf record +def create_tf_example(group, path): + # membaca file image + with tf.gfile.GFile(os.path.join(path, '{}'.format(group.filename)), 'rb') as fid: + encoded_jpg = fid.read() + encoded_jpg_io = io.BytesIO(encoded_jpg) + image = Image.open(encoded_jpg_io) + # ----------------------------------------------------------------- + + # mendapatkan ukuran image + width, height = image.size + + # mendapatkan nama file dari image + filename = group.filename.encode('utf8') + image_format = b'jpg' + + # inisialisasi list + xmins = [] + xmaxs = [] + ymins = [] + ymaxs = [] + classes_text = [] + classes = [] + # ----------------------------------------------------------------- + + + # untuk setiap box pada image lakukan berikut,.. + for index, row in group.object.iterrows(): + # konversi setiap koordinat dari box dari pixel ke domain 0 - 1 + xmins.append(row['xmin'] / width) + xmaxs.append(row['xmax'] / width) + ymins.append(row['ymin'] / height) + ymaxs.append(row['ymax'] / height) + # ----------------------------------------------------------------- + + # Menyimpan nama kelas kedalam list dalam bentuk text + classes_text.append(row['class'].encode('utf8')) + + # Menyimpan nama kelas kedalam list dalam bentuk index integer + classes.append(class_text_to_int(row['class'])) + + + # ----------------------------------------------------------------- + + # konversi ke tfrecord menggunakan fungsi tensorflow + tf_example = tf.train.Example(features=tf.train.Features(feature={ + 'image/height': dataset_util.int64_feature(height), + 'image/width': dataset_util.int64_feature(width), + 'image/filename': dataset_util.bytes_feature(filename), + 'image/source_id': dataset_util.bytes_feature(filename), + 'image/encoded': dataset_util.bytes_feature(encoded_jpg), + 'image/format': dataset_util.bytes_feature(image_format), + 'image/object/bbox/xmin': dataset_util.float_list_feature(xmins), + 'image/object/bbox/xmax': dataset_util.float_list_feature(xmaxs), + 'image/object/bbox/ymin': dataset_util.float_list_feature(ymins), + 'image/object/bbox/ymax': dataset_util.float_list_feature(ymaxs), + 'image/object/class/text': dataset_util.bytes_list_feature(classes_text), + 'image/object/class/label': dataset_util.int64_list_feature(classes), + })) + # ----------------------------------------------------------------- + + + return tf_example +# --------------------------------------------------------------------- + + + +def main(_): + # menyiapkan variable untuk menyimpan tf record kedalam bentuk file + writer = tf.python_io.TFRecordWriter(FLAGS.output_path) + + # inisialisasi path, apakah untuk path data train atau data test + path = os.path.join(os.getcwd(), 'images/{}'.format(FLAGS.type)) + + # membaca file csv + examples = pd.read_csv(FLAGS.csv_input) + + # memisahkan setiap kolom yg terbaca dari data csv + grouped = split(examples, 'filename') + + # mengolah tfrecord lalu menyimpannya kedalam bentuk file .tfrecord + for group in grouped: + tf_example = create_tf_example(group, path) + writer.write(tf_example.SerializeToString()) + writer.close() + # ----------------------------------------------------------------- + + # menampilkan lokasi file .tfrecord + output_path = os.path.join(os.getcwd(), FLAGS.output_path) + print('Successfully created the TFRecords: {}'.format(output_path)) + # ----------------------------------------------------------------- + + +if __name__ == '__main__': + tf.app.run() \ No newline at end of file diff --git a/Deteksi Plat Nomor Dengan Faster RCNN & SSD MobileNet/plate_detection/Object_detection_image.py b/Deteksi Plat Nomor Dengan Faster RCNN & SSD MobileNet/plate_detection/Object_detection_image.py new file mode 100644 index 0000000..0fe105b --- /dev/null +++ b/Deteksi Plat Nomor Dengan Faster RCNN & SSD MobileNet/plate_detection/Object_detection_image.py @@ -0,0 +1,69 @@ +#import library +import numpy as np +import cv2 +from detector import detector +from imutils import paths +import os +import time + +#import plot_cv dari folder utils +from utils import plot_cv + +#variabel det untuk memanggil class detector +det = detector.detector() + +#mengatur path lukasi image yang akan di testing +image_folder = 'test_image' + +#menyimpan file test image +imageNames = os.listdir(image_folder) + +#nama class +name_class = ["plate"] + +# mengulang pada setiap image yang ada pada folder +for imageName in imageNames: + + #membaca file gambar + image = cv2.imread(image_folder + '/' + imageName) + + #untuk ngedetek lokasi kotak pada gambar + (boxes, scores, classes, num, dump ) = det.detect_plate(image) + + #jika dalam gambar tidak ditemukan box maka next + if len(boxes) == 0: + print('skip detection') + continue + + #get ukuran gambar original + h, w = image.shape[:2] + boxes = boxes[0] + scores = scores[0] + classes = classes[0] + + #untuk filter box mana yang akan ditampilan + for box, score, class_idx in zip(boxes, scores, classes): + (startY, startX, endY, endX) = box + #koordinat box + startX = int(startX * w) + startY = int(startY * h) + endX = int(endX * w) + endY = int(endY * h) + #koordinat box yang di dapat + box = (startX, startY, endX, endY) + #untuk menampilkan persentase confidence rate dalam % + text = name_class[int(class_idx-1)] + " " + str(int(score * 100)) + "%" + #jika score lebih besar dari 0,7 maka box akan ditampilkan + if score > 0.7: + image = plot_cv.plot_object(image, box, text, int(class_idx-1)) + + # Semua hasil telah diambil pada gambar. Sekarang tampilkan gambar. + cv2.namedWindow("plate detector", cv2.WINDOW_KEEPRATIO) + cv2.setWindowProperty("plate detector", cv2.WND_PROP_ASPECT_RATIO, cv2.WINDOW_KEEPRATIO) + cv2.imshow('plate detector', image) + + # tekan apapun untuk menutup gambar + cv2.waitKey(0) + +# Menutup window +cv2.destroyAllWindows() diff --git a/Deteksi Plat Nomor Dengan Faster RCNN & SSD MobileNet/plate_detection/Object_detection_video.py b/Deteksi Plat Nomor Dengan Faster RCNN & SSD MobileNet/plate_detection/Object_detection_video.py new file mode 100644 index 0000000..101a94a --- /dev/null +++ b/Deteksi Plat Nomor Dengan Faster RCNN & SSD MobileNet/plate_detection/Object_detection_video.py @@ -0,0 +1,71 @@ +#import library +import numpy as np +import cv2 +from detector import detector +from imutils import paths +import os +import time + +#import plot_cv dari folder utils +from utils import plot_cv + +#untuk notifikasi +print("[INFO] starting video stream...") + +#untuk mengatur path pada file yang akan di test +vs = cv2.VideoCapture('test_image/testing_vidio.mp4') +#melakukan jeda +time.sleep(2.0) + +#variabel det untuk memanggil class detector +det = detector.detector() + +#nama class +name_class = ["plate"] + +# Mengulang setiap gambar +while True: + + #print(imageName) + ret, image = vs.read() + #untuk mendetek + (boxes, scores, classes, num, category_index) = det.detect_plate(image) + #jika box tidak ada maka next + if len(boxes) == 0: + print('skip detection') + continue + #ukuran gambar original + h, w = image.shape[:2] + boxes = boxes[0] + scores = scores[0] + classes = classes[0] + + #untuk filter box mana yang akan ditampilan + for box, score, class_idx in zip(boxes, scores, classes): + (startY, startX, endY, endX) = box + #koordinat box dikali dengan lebar dan tinggi gambar + startX = int(startX * w) + startY = int(startY * h) + endX = int(endX * w) + endY = int(endY * h) + #koordinat box yang di dapat + box = (startX, startY, endX, endY) + #untuk menampilkan persentase confidence rate dalam % + text = name_class[int(class_idx-1)] + " " + str(int(score * 100)) + "%" + #jika score lebih besar dari 0,7 maka box akan ditampilkan + if score > 0.7: + image = plot_cv.plot_object(image, box, text, int(class_idx-1)) + + # Semua hasil telah diambil pada gambar. Sekarang tampilkan gambar. + cv2.namedWindow("Plate detector", cv2.WINDOW_KEEPRATIO) + cv2.setWindowProperty("Plate detector", cv2.WND_PROP_ASPECT_RATIO, cv2.WINDOW_KEEPRATIO) + cv2.imshow('Plate detector', image) + + # tekan apapun untuk menutup gambar + key = cv2.waitKey(1) & 0xFF + + # jika menekan q maka proses loop berhenti + if key == ord("q"): + break +# Menutup window +cv2.destroyAllWindows() diff --git a/Deteksi Plat Nomor Dengan Faster RCNN & SSD MobileNet/plate_detection/Object_detection_webcam.py b/Deteksi Plat Nomor Dengan Faster RCNN & SSD MobileNet/plate_detection/Object_detection_webcam.py new file mode 100644 index 0000000..34db95a --- /dev/null +++ b/Deteksi Plat Nomor Dengan Faster RCNN & SSD MobileNet/plate_detection/Object_detection_webcam.py @@ -0,0 +1,76 @@ +#import library +import numpy as np +import cv2 +from detector import detector +from imutils import paths +import os +import time + +#import plot_cv dari folder utils +from utils import plot_cv + +#untuk notifikasi +print("[INFO] starting video stream...") + +#untuk mengaktifkan camera +vs = cv2.VideoCapture(0, cv2.CAP_DSHOW) + +#mengatur ukuran camera +vs.set(cv2.CAP_PROP_FRAME_WIDTH, 1080) +vs.set(cv2.CAP_PROP_FRAME_HEIGHT, 720) + +#melakukan jeda +time.sleep(2.0) + +#variabel det untuk memanggil class detector +det = detector.detector() + +#nama class +name_class = ["plate"] + +# Mengulang setiap gambar +while True: + + #print(imageName) + ret, image = vs.read() + #untuk mendetek + (boxes, scores, classes, num, category_index) = det.detect_plate(image) + #jika box tidak ada maka next + if len(boxes) == 0: + print('skip detection') + continue + #ukuran gambar original + h, w = image.shape[:2] + boxes = boxes[0] + scores = scores[0] + classes = classes[0] + + #untuk filter box mana yang akan ditampilan + for box, score, class_idx in zip(boxes, scores, classes): + (startY, startX, endY, endX) = box + #koordinat box dikali dengan lebar dan tinggi gambar + startX = int(startX * w) + startY = int(startY * h) + endX = int(endX * w) + endY = int(endY * h) + #box yang di dapat + box = (startX, startY, endX, endY) + #untuk menampilkan persentase confidence rate dalam % + text = name_class[int(class_idx-1)] + " " + str(int(score * 100)) + "%" + #jika score lebih besar dari 0,7 maka box akan ditampilkan + if score > 0.7: + image = plot_cv.plot_object(image, box, text, int(class_idx-1)) + + # Semua hasil telah diambil pada gambar. Sekarang tampilkan gambar. + cv2.namedWindow("plate detector", cv2.WINDOW_KEEPRATIO) + cv2.setWindowProperty("plate detector", cv2.WND_PROP_ASPECT_RATIO, cv2.WINDOW_KEEPRATIO) + cv2.imshow('plate detector', image) + + # tekan apapun untuk menutup gambar + key = cv2.waitKey(1) & 0xFF + + # jika menekan q maka proses loop berhenti + if key == ord("q"): + break +# Menutup window +cv2.destroyAllWindows() diff --git a/Deteksi Plat Nomor Dengan Faster RCNN & SSD MobileNet/plate_detection/detector/detector.py b/Deteksi Plat Nomor Dengan Faster RCNN & SSD MobileNet/plate_detection/detector/detector.py new file mode 100644 index 0000000..38a92f9 --- /dev/null +++ b/Deteksi Plat Nomor Dengan Faster RCNN & SSD MobileNet/plate_detection/detector/detector.py @@ -0,0 +1,70 @@ +# Import library +import os +import cv2 +import numpy as np +import tensorflow as tf +import sys + + +# untuk path folder sistem object detection +sys.path.append("..") + +#class detector +class detector: +#inisialisasi var + def __init__(self): + #nyari lokasi folder detector + folder_detector = 'detector' + + # Mengarahkan path ke frozen.pb yang berisikan model yang + # kan digunakan untuk sistem objek deteksi + PATH_TO_CKPT = os.path.sep.join([folder_detector, 'frozen_inference_graph.pb']) + + # mengarahkan path ke labelmap.pbtxt untuk mengetahui jumlah class + PATH_TO_LABELS = os.path.sep.join([folder_detector, 'labelmap.pbtxt']) + + # Jumlah kelas yang bisa diidentifikasi oleh objek detektor adalah 1 yaitu plate + NUM_CLASSES = 1 + + # Muat model Tensorflow ke dalam memori untuk persiapkan sessios tersorflow. + # session ini yang dipanggil sama detector + self.detection_graph = tf.Graph() + with self.detection_graph.as_default(): + od_graph_def = tf.GraphDef() + with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid: + serialized_graph = fid.read() + od_graph_def.ParseFromString(serialized_graph) + tf.import_graph_def(od_graph_def, name='') + + self.sess = tf.Session(graph=self.detection_graph) + + # inisialisasi variabel untuk penyimpanan sementara saat testing + # Tetapkan tensor input dan output (mis. Data) untuk classifier deteksi objek Input tensor adalah gambar + self.image_tensor = self.detection_graph.get_tensor_by_name('image_tensor:0') + + # Output tensor adalah kotak deteksi, skor, dan kelas + # Setiap kotak mewakili bagian dari gambar di mana objek tertentu terdeteksi + self.detection_boxes = self.detection_graph.get_tensor_by_name('detection_boxes:0') + + # Setiap skor mewakili tingkat kepercayaan untuk masing-masing objek. + # Skor ditampilkan pada gambar hasil, bersama dengan label kelas. + self.detection_scores = self.detection_graph.get_tensor_by_name('detection_scores:0') + self.detection_classes = self.detection_graph.get_tensor_by_name('detection_classes:0') + + # Jumlah objek yang terdeteksi + self.num_detections = self.detection_graph.get_tensor_by_name('num_detections:0') + + def detect_plate(self, frame): + + image_expanded = np.expand_dims(frame, axis=0) + + # Disini deteksi sebenarnya dilakukan dengan menjalankan model dengan gambar sebagai input + (boxes, scores, classes, num) = self.sess.run( + [self.detection_boxes, self.detection_scores, self.detection_classes, self.num_detections], + feed_dict={self.image_tensor: image_expanded}) + return (boxes, scores, classes, num, None) + + + + + diff --git a/Deteksi Plat Nomor Dengan Faster RCNN & SSD MobileNet/plate_detection/detector/frozen_inference_graph.pb b/Deteksi Plat Nomor Dengan Faster RCNN & SSD MobileNet/plate_detection/detector/frozen_inference_graph.pb new file mode 100644 index 0000000..2691fc3 Binary files /dev/null and b/Deteksi Plat Nomor Dengan Faster RCNN & SSD MobileNet/plate_detection/detector/frozen_inference_graph.pb differ diff --git a/Deteksi Plat Nomor Dengan Faster RCNN & SSD MobileNet/plate_detection/detector/labelmap.pbtxt b/Deteksi Plat Nomor Dengan Faster RCNN & SSD MobileNet/plate_detection/detector/labelmap.pbtxt new file mode 100644 index 0000000..0a269d7 --- /dev/null +++ b/Deteksi Plat Nomor Dengan Faster RCNN & SSD MobileNet/plate_detection/detector/labelmap.pbtxt @@ -0,0 +1,4 @@ +item { + id: 1 + name: 'plate' +} \ No newline at end of file diff --git a/Deteksi Plat Nomor Dengan Faster RCNN & SSD MobileNet/plate_detection/utils/plot_cv.py b/Deteksi Plat Nomor Dengan Faster RCNN & SSD MobileNet/plate_detection/utils/plot_cv.py new file mode 100644 index 0000000..c1188c0 --- /dev/null +++ b/Deteksi Plat Nomor Dengan Faster RCNN & SSD MobileNet/plate_detection/utils/plot_cv.py @@ -0,0 +1,47 @@ +#import library +import cv2 +import datetime +import numpy as np + +#var ploot_object berisi frame, box, text dan warna +def plot_object(frame, box, text, idx_color): + #untuk warna RGB + color_bgr = (0, 147, 0) + overlay = frame.copy() + #ukuran Gambar + (H, W) = frame.shape[:2] + #untuk ketebalan box , w gambar dibagi 400 + box_border = int(W / 400) + #koordinat box + (startX, startY, endX, endY) = box + y = startY - 10 if startY - 10 > 10 else startY + 10 + yBox = y + 5 + #index warna hijau + cv2.rectangle(overlay, (startX, startY), (endX, endY), + (255, 255, 255), box_border+4) + #untuk kotak text + cv2.rectangle(overlay, (startX, startY), (endX, endY), + color_bgr, box_border+2) + + font = cv2.FONT_HERSHEY_SIMPLEX + + # make a black image + img = np.zeros((500, 500)) + # set some text + # get the width and height of the text box + (text_width, text_height) = cv2.getTextSize(text, font, fontScale=(0.4*box_border), thickness=box_border)[0] + # set the text start position + text_offset_x = startX + text_offset_y = y + # make the coords of the box with a small padding of two pixels + box_coords = ((text_offset_x, text_offset_y), (text_offset_x + text_width + 2, text_offset_y - text_height - 2)) + cv2.rectangle(overlay, box_coords[0], box_coords[1], color_bgr, cv2.FILLED) + cv2.putText(overlay, text, (text_offset_x, text_offset_y), font, fontScale=0.70, color=(255, 255, 255), thickness=2) + + + alpha = 1 # Transparency factor. + + # Following line overlays transparent rectangle over the image + frame = cv2.addWeighted(overlay, alpha, frame, 1 - alpha, 0) + + return frame \ No newline at end of file diff --git a/Deteksi Plat Nomor/xml_to_csv.py b/Deteksi Plat Nomor Dengan Faster RCNN & SSD MobileNet/xml_to_csv.py similarity index 100% rename from Deteksi Plat Nomor/xml_to_csv.py rename to Deteksi Plat Nomor Dengan Faster RCNN & SSD MobileNet/xml_to_csv.py