Пример #1
0
def main():

    blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN()         # attempt KNN training

    if blnKNNTrainingSuccessful == False:                               # if KNN training was not successful
        print "\nerror: KNN traning was not successful\n"               # show error message
        return                                                          # and exit program
    # end if

    imgOriginalScene  = cv2.imread(sys.argv[1])              # open image

    if imgOriginalScene is None:                            # if image was not read successfully
        print "\nerror: image not read from file \n\n"      # print error message to std out
        os.system("pause")                                  # pause so user can see error message
        return                                              # and exit program
    # end if

    listOfPossiblePlates = DetectPlates.detectPlatesInScene(imgOriginalScene)           # detect plates

    listOfPossiblePlates = DetectChars.detectCharsInPlates(listOfPossiblePlates)        # detect chars in plates

    #cv2.imshow("imgOriginalScene", imgOriginalScene)            # show scene image

    if len(listOfPossiblePlates) == 0:                          # if no plates were found
        print "\nno license plates were detected\n"             # inform user no plates were found
    else:                                                       # else
                # if we get in here list of possible plates has at leat one plate

                # sort the list of possible plates in DESCENDING order (most number of chars to least number of chars)
        listOfPossiblePlates.sort(key = lambda possiblePlate: len(possiblePlate.strChars), reverse = True)

                # suppose the plate with the most recognized chars (the first plate in sorted by string length descending order) is the actual plate
        licPlate = listOfPossiblePlates[0]

        #cv2.imshow("imgPlate", licPlate.imgPlate)           # show crop of plate and threshold of plate
        #cv2.imshow("imgThresh", licPlate.imgThresh)

        if len(licPlate.strChars) == 0:                     # if no chars were found in the plate
            print "\nno characters were detected\n\n"       # show message
            return                                          # and exit program
        # end if

        drawRedRectangleAroundPlate(imgOriginalScene, licPlate)             # draw red rectangle around plate

        print "\nlicense plate read from image = " + licPlate.strChars + "\n"       # write license plate text to std out
        print "----------------------------------------"


        cv2.imshow("imgOriginalScene", imgOriginalScene)                # re-show scene image

        #cv2.imwrite("imgOriginalScene.png", imgOriginalScene)           # write image out to file

        cv2.imwrite(sys.argv[2], imgOriginalScene)

    # end if else

    cv2.waitKey(0)					# hold windows open until user presses a key

    return
Пример #2
0
def main():

    blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN()

    if blnKNNTrainingSuccessful == False:                               # nếu train không thành công
        print("\nerror: KNN traning was not successful\n")  # thông báo lỗi
        return                                                          # kết thúc chương trình


    imgOriginalScene  = cv2.imread("1.jpg")               # mở image được chọn

    if imgOriginalScene is None:                            # nếu hình ảnh không được nhận diện thành công
        print("\nerror: image not read from file \n\n")  # in ra màn hình
        os.system("pause")                                  # tạm dừng chương trình
        return                                              # kết thúc chương trình
    # end if

    listOfPossiblePlates = DetectPlates.detectPlatesInScene(imgOriginalScene)           # phát hiện image

    listOfPossiblePlates = DetectChars.detectCharsInPlates(listOfPossiblePlates)        # tìm thấy kí tự trong image

    cv2.imshow("imgOriginalScene", imgOriginalScene)            # hiển thị image

    if len(listOfPossiblePlates) == 0:                          # nếu không tìm thấy ký tự
        print("\nno license plates were detected\n")  # thông báo trên màn hình không tìm thấy hình
    else:



        listOfPossiblePlates.sort(key = lambda possiblePlate: len(possiblePlate.strChars), reverse = True)


        licPlate = listOfPossiblePlates[0]

        cv2.imshow("imgPlate", licPlate.imgPlate)           # hiển thị tấm biển số
        cv2.imshow("imgThresh", licPlate.imgThresh)

        if len(licPlate.strChars) == 0:                     # nếu không tìm thấy ký tự trên biển số
            print("\nno characters were detected\n\n")  # hiện thị tin nhắn
            return                                          # kết thúc chương trình


        drawRedRectangleAroundPlate(imgOriginalScene, licPlate)             # khoanh viền đỏ xác định định biển số xe

        print("\nlicense plate read from image = " + licPlate.strChars + "\n")  # in ra biển số dưới console
        print("----------------------------------------")

        writeLicensePlateCharsOnImage(imgOriginalScene, licPlate)           # hiện thị biển số dưới dạng text trên ảnh

        cv2.imshow("imgOriginalScene", imgOriginalScene)                # show lại hình hảnh toàn cảnh

        cv2.imwrite("imgOriginalScene.png", imgOriginalScene)           # ghi hình ảnh ra



    cv2.waitKey(0)

    return
Пример #3
0
def main():
    blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN(
    )  # pokušaj KNN treninga

    if blnKNNTrainingSuccessful == False:
        print("\nerror: KNN trening nije uspješan\n")
        return
    # end if

    imgOriginalScene = cv2.imread("5.jpg")

    if imgOriginalScene is None:
        print("\nerror: slika nije pronađena \n\n")
        os.system("pause")
        return
    # end if

    listOfPossPlates = DetectPlates.detectPlatesInScene(
        imgOriginalScene)  # detekcija oznaka
    listOfPossPlates = DetectChars.detectCharsInPlates(
        listOfPossPlates)  # detekcija karaktera na oznaci
    cv2.imshow("imgOriginalScene", imgOriginalScene)  # prikaz polazne slike

    if len(listOfPossPlates) == 0:  # ako reg. oznake nisu nađene
        print("\noznake nisu pronađene\n")
    else:  #ako jesu
        # poredajte popis mogućih oznaka po padajućem redoslijedu
        listOfPossPlates.sort(key=lambda possPlate: len(possPlate.strChars),
                              reverse=True)
        # pretpostavlja se da je oznaka s najviše prepoznatih znakova stvarna (prva ploča razvrstana po dužini niza silaznim redoslijedom)
        licPlate = listOfPossPlates[0]

        #obrezivanje i prikaz obrezane oznake i praga oznake
        cv2.imshow("imgPlate", licPlate.imgPlate)
        cv2.imshow("imgThresh", licPlate.imgThresh)

        if len(licPlate.strChars) == 0:  # ako karakteri nisu pronađeni
            print("\nni jedan karakter nije pronađen\n\n")
            return
        # end if

        drawRedRectangleAroundPlate(imgOriginalScene,
                                    licPlate)  # crveni okvir oko reg. oznake

        print("\nreg. oznaka iščitana sa slike = " + licPlate.strChars + "\n")
        print("***")

        writeLicensePlateCharsOnImage(
            imgOriginalScene, licPlate)  # ispis teksta reg. oznake na slici
        cv2.imshow("imgOriginalScene",
                   imgOriginalScene)  # ponovni prikaz polazne slike
        cv2.imwrite("imgOriginalScene.png",
                    imgOriginalScene)  # zapis slike sa tekstom u .png formatu

    # end if else

    cv2.waitKey(0)  # čeka dok korisnik ne pritisne tipku za nastavak
    return
Пример #4
0
def main():

    blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN()         # attempt KNN training

    if blnKNNTrainingSuccessful == False:                               # if KNN training was not successful
        print "\nerror: KNN traning was not successful\n"               # show error message
        return                                                          # and exit program
    # end if

    imgOriginalScene  = cv2.imread("1.png")               # open image

    if imgOriginalScene is None:                            # if image was not read successfully
        print "\nerror: image not read from file \n\n"      # print error message to std out
        os.system("pause")                                  # pause so user can see error message
        return                                              # and exit program
    # end if

    listOfPossiblePlates = DetectPlates.detectPlatesInScene(imgOriginalScene)           # detect plates

    listOfPossiblePlates = DetectChars.detectCharsInPlates(listOfPossiblePlates)        # detect chars in plates

    cv2.imshow("imgOriginalScene", imgOriginalScene)            # show scene image

    if len(listOfPossiblePlates) == 0:                          # if no plates were found
        print "\nno license plates were detected\n"             # inform user no plates were found
    else:                                                       # else
                # if we get in here list of possible plates has at leat one plate

                # sort the list of possible plates in DESCENDING order (most number of chars to least number of chars)
        listOfPossiblePlates.sort(key = lambda possiblePlate: len(possiblePlate.strChars), reverse = True)

                # suppose the plate with the most recognized chars (the first plate in sorted by string length descending order) is the actual plate
        licPlate = listOfPossiblePlates[0]

        cv2.imshow("imgPlate", licPlate.imgPlate)           # show crop of plate and threshold of plate
        cv2.imshow("imgThresh", licPlate.imgThresh)

        if len(licPlate.strChars) == 0:                     # if no chars were found in the plate
            print "\nno characters were detected\n\n"       # show message
            return                                          # and exit program
        # end if

        drawRedRectangleAroundPlate(imgOriginalScene, licPlate)             # draw red rectangle around plate

        print "\nlicense plate read from image = " + licPlate.strChars + "\n"       # write license plate text to std out
        print "----------------------------------------"

        writeLicensePlateCharsOnImage(imgOriginalScene, licPlate)           # write license plate text on the image

        cv2.imshow("imgOriginalScene", imgOriginalScene)                # re-show scene image

        cv2.imwrite("imgOriginalScene.png", imgOriginalScene)           # write image out to file

    # end if else

    cv2.waitKey(0)					# hold windows open until user presses a key

    return
Пример #5
0
def main():
    cam = cv2.VideoCapture(0)
    time.sleep(10)

    blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN(
    )  # attempt KNN training

    while True:
        ret, imgOriginalScene = cam.read()
        cv2.imshow('webcam', imgOriginalScene)
        if ord(msvcrt.getch()) == 27:
            cam.release()
            cv2.destroyAllWindows()
            break
        # end if
        if imgOriginalScene is None:  # if image was not read successfully
            print("\nerror: image not read from file \n\n"
                  )  # print error message to std out
            os.system("pause")  # pause so user can see error message
            return  # and exit program
        # end if

        listOfPossiblePlates = DetectPlates.detectPlatesInScene(
            imgOriginalScene)  # detect plates
        listOfPossiblePlates = DetectChars.detectCharsInPlates(
            listOfPossiblePlates)  # detect chars in plates
        #    cv2.imshow("imgOriginalScene", imgOriginalScene)            # show scene image

        if len(listOfPossiblePlates) > 5:  # if no plates were found
            # sort the list of possible plates in DESCENDING order (most number of chars to least number of chars)
            listOfPossiblePlates.sort(
                key=lambda possiblePlate: len(possiblePlate.strChars),
                reverse=True)
            # suppose the plate with the most recognized chars (the first plate in sorted by string length descending order) is the actual plate
            licPlate = listOfPossiblePlates[0]
            #            cv2.imshow("imgPlate", licPlate.imgPlate)           # show crop of plate and threshold of plate
            #        cv2.imshow("imgThresh", licPlate.imgThresh)
            if not licPlate.strChars == '' and len(licPlate.strChars) > 1:
                #                drawRedRectangleAroundPlate(imgOriginalScene, licPlate)             # draw red rectangle around plate
                #                writeLicensePlateCharsOnImage(imgOriginalScene, licPlate)           # write license plate text on the image
                pais = "1"
                if re.match('^[A-Z]{3}[0-9]{4}$', licPlate.strChars):
                    pais = "Uruguay"
                if re.match('^[0-9]{3}[A-Z]{4}$', licPlate.strChars):
                    pais = "Paraguay"
                if re.match('^[A-Z]{2}[0-9]{3}[A-Z]{2}$', licPlate.strChars):
                    pais = "Argentina"
                if re.match('^[A-Z]{3}[0-9]{3}$', licPlate.strChars):
                    pais = "Argentina"
                if not pais == "":
                    print("\nlicense plate de " + pais + " = " +
                          licPlate.strChars
                          )  # write license plate text to std out
    #        cv2.imshow("imgOriginalScene", imgOriginalScene)                # re-show scene image
    #        cv2.imwrite("imgOriginalScene.png", imgOriginalScene)            # write image out to file
    # end if else
    cam.release()
    cv2.destroyAllWindows()
Пример #6
0
def main():
    print("Loading Images ...")
    # KNN ML Model ################################################################################################################
    blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN(
        CLASS_TXT_DIR, FLAT_IMG_DIR)  # attempt KNN training

    if blnKNNTrainingSuccessful == False:
        print("\nerror: KNN traning was not successful\n")
        return
    # end if

    # Loading Images ##############################################################################################################
    BR_IMGS = os.listdir(DATASET_DIR)
    BR_IMGS = [img for img in BR_IMGS if ".jpg" in img]
    extractedPlates = []
    numberPlateList = []
    filename = []

    # Write extracted plates images to path
    print("Begin Pre-processing images ...")
    for BR_IMG in BR_IMGS:
        BR_IMG_path = DATASET_DIR + BR_IMG
        imgOriginal = cv2.imread(BR_IMG_path)
        listOfPossiblePlates = DetectPlates.detectPlates(imgOriginal)
        listOfPossiblePlates = DetectChars.detectCharsInPlates(
            listOfPossiblePlates)

        # Sorting list of possible plates in DESC order (the one with most chars recognized)
        listOfPossiblePlates.sort(
            key=lambda possiblePlate: len(possiblePlate.strChars),
            reverse=True)
        licPlate = listOfPossiblePlates[0]
        extractedPlates.append(licPlate.imgPlate)
        numberPlateList.append(BR_IMG.rsplit('.', 1)[0])

        cv2.imwrite(EXTRACTED_PLATES_DIR + BR_IMG, licPlate.imgPlate)

    # Export list of number plate to csv
    WriteNumberPlateList(numberPlateList)
    print("Completed pre-processing and export list of number plates.")

    # Pre-process extracted plates and export processed image file
    print("Begin Image Pre-processing for OCR..")
    ocr_preprocessed_plates = OCR.preprocess(extractedPlates, numberPlateList,
                                             PREPROCESSED_PLATES_DIR)

    # OCR the preprocessed extracted plates and export the OCR Output to csv
    OCROutput = OCR.OCR(ocr_preprocessed_plates)
    print("Completed Image Pre-processing for OCR and export to csv.")

    # Accuracy result based on predicted number plate vs actual number plates
    OCR_Result = OCR.CheckOCR(OCROutput, numberPlateList)

    # Export Result to csv
    ExportActualAndPredictedNumberPlate(numberPlateList, OCROutput)

    return  # end of main()
Пример #7
0
def main():
    licno = 0
    cap = cv2.VideoCapture(0)
    while (True):
        ret, frame = cap.read()
        blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN()
        if blnKNNTrainingSuccessful == False:
            print("\nerror: KNN traning was not successful\n")
            return

        imgOriginalScene = frame  ## for video
        cv2.imshow('video', imgOriginalScene)
        platename = 'video' + str(licno) + '.png'

        #        imgOriginalScene  = cv2.imread(str(imagepath))                      ## for image
        #        platename=str(imagepath).split('\\')
        #        platename=str(platename[-1])

        if imgOriginalScene is None:
            print("\nerror: image not read from file \n\n")
            os.system("pause")
            return
        listOfPossiblePlates = DetectPlates.detectPlatesInScene(
            imgOriginalScene)
        listOfPossiblePlates = DetectChars.detectCharsInPlates(
            listOfPossiblePlates)
        if len(listOfPossiblePlates) == 0:
            print("\nno license plates were detected\n")
        else:
            listOfPossiblePlates.sort(
                key=lambda possiblePlate: len(possiblePlate.strChars),
                reverse=True)
            licPlate = listOfPossiblePlates[0]
            os.chdir('thresimages')
            cv2.imwrite(platename, ~licPlate.imgThresh)
            os.chdir('..')
            tesser.tessocr(platename, licPlate.strChars)

            if len(licPlate.strChars) == 0:
                print("\nno characters were detected\n\n")
    #                return
            drawRedRectangleAroundPlate(imgOriginalScene, licPlate)
            print("\nLicense plate read from image = " + licPlate.strChars +
                  "\n")
            print("----------------------------------------")
            writeLicensePlateCharsOnImage(imgOriginalScene, licPlate)
            os.chdir('output')
            cv2.imwrite(platename, imgOriginalScene)
            os.chdir('..')
            licno = licno + 1
            cv2.imshow('video',
                       imgOriginalScene)  ##Uncomment this block for video
        if cv2.waitKey(1) & 0xFF == ord('q'):  ##
            cap.release()  ##
            cv2.destroyAllWindows()  ##
            break  ##Uncomment this block for video
    return
Пример #8
0
def readPlateNumber(request, imageName):
    blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN(
    )  # attempt KNN training

    if blnKNNTrainingSuccessful == False:  # if KNN training was not successful
        print(
            "\nerror: KNN traning was not successful\n")  # show error message
        return  # and exit program
    # end if

    imagePath = "D:/personal/Project Python/plateNumberImage/" + imageName
    imgOriginalScene = cv2.imread(imagePath)  # open image

    if imgOriginalScene is None:  # if image was not read successfully
        print("\nerror: image not read from file \n\n"
              )  # print error message to std out
        #os.system("pause")  # pause so user can see error message
        data = {'status': 'OK', 'plateNumber': ''}
        return JsonResponse(data)
        # and exit program
    # end if

    listOfPossiblePlates = DetectPlates.detectPlatesInScene(
        imgOriginalScene)  # detect plates

    listOfPossiblePlates = DetectChars.detectCharsInPlates(
        listOfPossiblePlates)  # detect chars in plates

    if len(listOfPossiblePlates) == 0:  # if no plates were found
        print("\nno license plates were detected\n"
              )  # inform user no plates were found
        data = {'status': 'OK', 'plateNumber': ''}
        return JsonResponse(data)
    else:  # else
        # if we get in here list of possible plates has at leat one plate

        # sort the list of possible plates in DESCENDING order (most number of chars to least number of chars)
        listOfPossiblePlates.sort(
            key=lambda possiblePlate: len(possiblePlate.strChars),
            reverse=True)

        # suppose the plate with the most recognized chars (the first plate in sorted by string length descending order) is the actual plate
        licPlate = listOfPossiblePlates[0]
        licPlate1 = listOfPossiblePlates[1]
        if len(licPlate.strChars) == 0:  # if no chars were found in the plate
            print("\nno characters were detected\n\n")  # show message
            return  # and exit program
        # end if

        print("\nlicense plate read from image = " + licPlate1.strChars + "-" +
              licPlate.strChars + "\n")  # write license plate text to std out
        print("----------------------------------------")
        data = {
            'status': 'OK',
            'plateNumber': licPlate1.strChars + "-" + licPlate.strChars
        }
    return JsonResponse(data)
def main():

    blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN()
    if blnKNNTrainingSuccessful == False:
        print("\nerror: KNN traning was not successful\n")
        return
    # end if

    imgOriginalScene = cv2.imread("2.jpg")

    if imgOriginalScene is None:
        print("\nerror: image not read from file \n\n")
        os.system("pause")
        return
    # end if

    listOfPossiblePlates = DetectPlates.detectPlatesInScene(imgOriginalScene)

    listOfPossiblePlates = DetectChars.detectCharsInPlates(
        listOfPossiblePlates)

    cv2.imshow("imgOriginalScene", imgOriginalScene)

    if len(listOfPossiblePlates) == 0:
        print("\nno license plates were detected\n")
    else:  # else

        listOfPossiblePlates.sort(
            key=lambda possiblePlate: len(possiblePlate.strChars),
            reverse=True)

        licPlate = listOfPossiblePlates[0]

        cv2.imshow("imgPlate", licPlate.imgPlate)
        cv2.imshow("imgThresh", licPlate.imgThresh)

        if len(licPlate.strChars) == 0:
            print("\nno characters were detected\n\n")
            return
        # end if

        drawRedRectangleAroundPlate(imgOriginalScene, licPlate)
        print("\nlicense plate read from image = " + licPlate.strChars + "\n")
        print("----------------------------------------")

        writeLicensePlateCharsOnImage(imgOriginalScene, licPlate)

        cv2.imshow("imgOriginalScene", imgOriginalScene)

        cv2.imwrite("imgOriginalScene.png", imgOriginalScene)

    # end if else

    cv2.waitKey(0)

    return
Пример #10
0
def main(filePath="LicPlateImages/br2.png"):
    try:
        blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN(
        )  # attempt KNN training
        if blnKNNTrainingSuccessful == False:  # if KNN training was not successful
            print("\nerror: KNN traning was not successful\n"
                  )  # show error message
            return  # and exit program

        imgOriginalScene = cv2.imread(filePath)  # open image

        if imgOriginalScene is None:  # if image was not read successfully
            print("\nerror: image not read from file \n\n"
                  )  # print error message to std out
            os.system("pause")  # pause so user can see error message
            return  # and exit program

        listOfPossiblePlates = DetectPlates.detectPlatesInScene(
            imgOriginalScene)  # detect plates

        listOfPossiblePlates = DetectChars.detectCharsInPlates(
            listOfPossiblePlates)  # detect chars in plates

        if config.enableWindowsMode:
            cv2.imshow('Imagem Original', imgOriginalScene)

        if len(listOfPossiblePlates) == 0:  # if no plates were found
            print("\nno license plates were detected\n"
                  )  # inform user no plates were found
        else:  # else
            listOfPossiblePlates.sort(
                key=lambda possiblePlate: len(possiblePlate.strChars),
                reverse=True)
            licPlate = listOfPossiblePlates[0]

            if config.enableWindowsMode:
                cv2.imshow('Placa', licPlate.imgPlate)
                cv2.imshow('Placa com Processamento', licPlate.imgThresh)

            if len(licPlate.strChars
                   ) == 0:  # if no chars were found in the plate
                print("\nno characters were detected\n\n")  # show message
                return  # and exit program

            drawRedRectangleAroundPlate(
                imgOriginalScene, licPlate)  # draw red rectangle around plate

            if config.enableWindowsMode:
                cv2.imshow('Imagem Original', imgOriginalScene)

        cv2.waitKey(0)

        return licPlate.strChars
    except expression as identifier:
        return 'Erro ao encontrar placa para {filePath}'
Пример #11
0
    def analyse(self, frame_queue, analysed_frame_queue, autonomous_states_queue, \
    commands_queue, car_states_queue):
        """
        get the current frame from FRAME_QUEUE and analyse
        """
        current_thread = threading.currentThread()
        self.__command_timer = time.time()
        bln_knn_training_successful = DetectChars.loadKNNDataAndTrainKNN(
        )  # attempt KNN training
        if bool(bln_knn_training_successful) is False:
            return

        self.__fps_timer = time.time()
        while getattr(current_thread, 'is_running', True):
            string_data = frame_queue.get(True, None)
            frame = numpy.fromstring(string_data, dtype='uint8')
            self.__current_frame = cv2.imdecode(frame, 1)

            self.__get_cruise_states_data(car_states_queue)

            if getattr(current_thread, 'is_analysing', True):
                self.__car_detection(autonomous_states_queue)
                self.__detect_objects()
                self.__lane_assist()

                if getattr(current_thread, 'is_deciding', True):
                    self.__take_cruise_decision(commands_queue)
                    self.__avoid_detected_objects(commands_queue)

                self.__draw_rect_around_plate(self.__current_frame)
                self.__draw_distance_to_car()
                self.__draw_car_cruise_watch_area()
                self.__draw_lane_assist_decision()
                self.__draw_detected_objects()

            self.__draw_fps()

            result, encrypted_image = \
                cv2.imencode('.jpg', self.__current_frame, self.__encode_parameter)

            if bool(result) is False:
                break

            analysed_frame = numpy.array(encrypted_image)
            analysed_frame_queue.put(str(analysed_frame.tostring()), True,
                                     None)
            frame_queue.task_done()

            self.__fps_counter = self.__fps_counter + 1

            if time.time() - self.__fps_timer > 1:
                self.__frame_fps = self.__fps_counter
                self.__fps_counter = 0
                self.__fps_timer = time.time()
Пример #12
0
def main():
    # attempt KNN training
    blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN()         
    # if KNN training was not successful
    if blnKNNTrainingSuccessful == False:                              
        print("\nerror: KNN traning was not successful\n")  
        return                                                         
    
    #imgOriginalScene  = cv2.imread("./test_image.jpg")              
    img  = cv2.imread("./images/plate.png")  

    if img is None:                           
        print("\n error: image not read from file \n\n")  
        os.system("pause")                                 
        return                                            
  
    # detect plates
    listOfPossiblePlates = DetectPlates.detectPlatesInScene(img)           
    # detect chars in plates
    listOfPossiblePlates = DetectChars.detectCharsInPlates(listOfPossiblePlates)        

    cv2.imshow("imgOriginalScene", img)           
    # if no plates were found
    if len(listOfPossiblePlates) == 0:                          
        print("\n no license plates were detected\n")  
    else:                                                       
        # if we get in here list of possible plates has at leat one plate

        # sort the list of possible plates in DESCENDING order (most number of chars to least number of chars)
        listOfPossiblePlates.sort(key = lambda possiblePlate: len(possiblePlate.strChars), reverse = True)

         # suppose the plate with the most recognized chars (the first plate in sorted by string length descending order) is the actual plate
        licPlate = listOfPossiblePlates[0]

        cv2.imshow("imgPlate", licPlate.imgPlate)  
        # show crop of plate and threshold of plate        
        cv2.imshow("imgThresh", licPlate.imgThresh)

        if len(licPlate.strChars) == 0:                     
            print("\nno characters were detected\n\n") 
            return                                         

        drawRedRectangleAroundPlate(img, licPlate)             
        print("\n license plate read from image = " + licPlate.strChars + "\n")  
        print("----------------------------------------")

        writeLicensePlateCharsOnImage(img, licPlate)           
        cv2.imshow("imgOriginalScene", img)               
        cv2.imwrite("imgOriginalScene.png", img)           
  

    cv2.waitKey(0)					

    return
Пример #13
0
def findPlates(imagePath):
    #path = filedialog.askopenfilename(title='open')
    carStatus = ""
    # attempt KNN training
    blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN()

    # if KNN training was not successful
    if blnKNNTrainingSuccessful == False:
        return False

    imgOriginalScene = cv2.imread(imagePath)
    # if image was not read successfully
    if imgOriginalScene is None:
        return False

    listOfPossiblePlates = DetectPlates.detectPlatesInScene(
        imgOriginalScene)  # detect plates

    listOfPossiblePlates = DetectChars.detectCharsInPlates(
        listOfPossiblePlates)  # detect chars in plates

    # if no plates were found
    if len(listOfPossiblePlates) == 0:
        # inform user no plates were found
        return False
    else:
        # if we get in here list of possible plates has at leat one plate  sort the list of possible plates in DESCENDING order (most number of chars to least number of chars)
        listOfPossiblePlates.sort(
            key=lambda possiblePlate: len(possiblePlate.strChars),
            reverse=True)

        # suppose the plate with the most recognized chars (the first plate in sorted by string length descending order) is the actual plate
        licPlate = listOfPossiblePlates[0]

        if len(licPlate.strChars) == 0:
            # if no chars were found in the plate
            # print ("\nno characters were detected\n\n")
            return False

        licensePlateText = licPlate.strChars

        #checking plate on server
        serverAddress = "http://localhost/Recognition/api.php"
        requestData = requests.get(serverAddress + "?license=" +
                                   licensePlateText)
        returnText = requestData.text
        if returnText == 'false':
            carStatus = "\n UNAUTHORISED CAR!\n\n" + licensePlateText

        elif returnText == 'true':
            carStatus = "\n AUTHORISED CAR!\n\n" + licensePlateText  # hold windows open until user presses a key

    return carStatus
Пример #14
0
def main():

    blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN()         # attempt KNN training

    if blnKNNTrainingSuccessful == False:                               
        print("\nerror: KNN traning was not successful\n")  
        return                                                          

    imgOriginalScene  = cv2.imread("LicPlateImages/16.png")               

    if imgOriginalScene is None:                            
        print("\nerror: image not read from file \n\n")  
        os.system("pause")                                  
        return

    listOfPossiblePlates = DetectPlates.detectPlatesInScene(imgOriginalScene)           # detect plates

    listOfPossiblePlates = DetectChars.detectCharsInPlates(listOfPossiblePlates)        # detect chars in plates

    cv2.imshow("imgOriginalScene", imgOriginalScene)            

    if len(listOfPossiblePlates) == 0:                          
        print("\nno license plates were detected\n")  
    else:                                                      

                # sort the list of possible plates in DESCENDING order (most number of chars to least number of chars)
        listOfPossiblePlates.sort(key = lambda possiblePlate: len(possiblePlate.strChars), reverse = True)

                # suppose the plate with the most recognized chars (the first plate in sorted by string length descending order) is the actual plate
        licPlate = listOfPossiblePlates[0]

        cv2.imshow("imgPlate", licPlate.imgPlate)           # show crop of plate and threshold of plate
        cv2.imshow("imgThresh", licPlate.imgThresh)

        if len(licPlate.strChars) == 0:                     
            print("\nno characters were detected\n\n")  
            return                                          
        

        drawRedRectangleAroundPlate(imgOriginalScene, licPlate)             # draw red rectangle around plate

        print("\nlicense plate read from image = " + licPlate.strChars + "\n")  # write license plate text to std out
        print("----------------------------------------")

        writeLicensePlateCharsOnImage(imgOriginalScene, licPlate)           # write license plate text on the image

        cv2.imshow("imgOriginalScene", imgOriginalScene)                # re-show scene image

        cv2.imwrite("imgOriginalScene.png", imgOriginalScene)           
    cv2.waitKey(0)					# hold windows open until user presses a key

    return
Пример #15
0
        def main():

            blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN(
            )  # attempt KNN training

            if blnKNNTrainingSuccessful == False:  # if KNN training was not successful

                return HttpResponse(
                    "<pstyle='color:red;font-size:20px;font-family:tahoma,times,calibri;padding-left:500px;padding-top:40px;background-color:cyan;'>error: KNN traning was not successful</p>"
                )  # and exit program
            # end if

            imgOriginalScene = cv2.imread(image)
            # open image

            if imgOriginalScene is None:  # if image was not read successfully
                return HttpResponse(
                    "<pstyle='color:red;font-size:20px;font-family:tahoma,times,calibri;padding-left:500px;padding-top:40px;background-color:cyan;'>error: image not read from file</p>"
                )  # and exit program
            # end if

            listOfPossiblePlates = DetectPlates.detectPlatesInScene(
                imgOriginalScene)  # detect plates

            listOfPossiblePlates = DetectChars.detectCharsInPlates(
                listOfPossiblePlates)  # detect chars in plates

            if len(listOfPossiblePlates) == 0:  # if no plates were found
                msg = "\nno license plates were detected\n"  # inform user no plates were found
            else:  # else
                # if we get in here list of possible plates has at leat one plate

                # sort the list of possible plates in DESCENDING order (most number of chars to least number of chars)
                listOfPossiblePlates.sort(
                    key=lambda possiblePlate: len(possiblePlate.strChars),
                    reverse=True)

                # suppose the plate with the most recognized chars (the first plate in sorted by string length descending order) is the actual plate
                licPlate = listOfPossiblePlates[0]

                if len(licPlate.strChars
                       ) == 0:  # if no chars were found in the plate

                    return HttpResponse(
                        "<pstyle='color:red;font-size:20px;font-family:tahoma,times,calibri;padding-left:500px;padding-top:40px;background-color:cyan;'>no characters were detected</p>"
                    )
                # end if

            return HttpResponse(
                "<pstyle='color:red;font-size:20px;font-family:tahoma,times,calibri;padding-left:500px;padding-top:40px;background-color:cyan;'>Matched Car Number is"
                + licPlate.strChars + "</p>")
def main():

    blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN()         # treniranje KNN-a

    if blnKNNTrainingSuccessful == False:                               # Ukoliko nije uspesno izvrseno treniranje vraca se poruka o tome
        print ("\nerror: KNN traning was not successful\n")
        return


    imgOriginalScene  = cv2.imread("6.png")               # otvaranje slike

    if imgOriginalScene is None:                            # ukoliko slika nije uspesno otvorena vraca se poruka o tome
        print("\nerror: image not read from file \n\n")
        os.system("pause")
        return


    possiblePlates = DetectPlates.detectPlatesInScene(imgOriginalScene)           # detektovanje samih tablica

    possiblePlates = DetectChars.detectCharsInPlates(possiblePlates)        # detektovanje karaktera na tablicama

    cv2.imshow("Original image", imgOriginalScene)

    if len(possiblePlates) == 0:
        print("\nno license plates were detected\n")
    else:
        possiblePlates.sort(key = lambda possiblePlate: len(possiblePlate.strChars), reverse = True)


        licPlate = possiblePlates[0]

        if len(licPlate.strChars) == 0:
            print("\nno characters were detected\n\n")
            return
        # end if

        Draw.drawRedRectangleAroundPlate(imgOriginalScene, licPlate)

        print("\nlicense plate read from image = " + licPlate.strChars + "\n")
        print("----------------------------------------")

        Draw.writeLicensePlateCharsOnImage(imgOriginalScene, licPlate)

        cv2.imshow("Result", imgOriginalScene)

        cv2.imwrite("result.png", imgOriginalScene)

    cv2.waitKey(0)

    return
Пример #17
0
def number_plate(imgOriginalScene):
    # imgOriginalScene = Image.fromarray(imgOriginalScene, 'RGB')
    blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN()
    if blnKNNTrainingSuccessful == False:
        print("\nerror: KNN traning was not successful\n")
        return
    # imgOriginalScene  = cv2.imread("1.png")
    if imgOriginalScene is None:
        print("\nerror: image not read from file \n\n")
        # os.system("pause")
        return

    listOfPossiblePlates = DetectPlates.detectPlatesInScene(imgOriginalScene)

    listOfPossiblePlates = DetectChars.detectCharsInPlates(
        listOfPossiblePlates)

    # cv2.imshow("imgOriginalScene", imgOriginalScene)

    if len(listOfPossiblePlates) == 0:
        print("\nno license plates were detected\n")
    else:
        listOfPossiblePlates.sort(
            key=lambda possiblePlate: len(possiblePlate.strChars),
            reverse=True)

        # suppose the plate with the most recognized chars (the first plate in sorted by string length descending order) is the actual plate
        licPlate = listOfPossiblePlates[0]

        # cv2.imshow("imgPlate", licPlate.imgPlate)
        # cv2.imshow("imgThresh", licPlate.imgThresh)

        if len(licPlate.strChars) == 0:
            print("\nno characters were detected\n\n")
            return

        drawRedRectangleAroundPlate(imgOriginalScene, licPlate)

        if len(licPlate.strChars) > 1:
            print("\nlicense plate read from image = " + licPlate.strChars +
                  "\n")
            print("----------------------------------------")
            #print(licPlate.strChars)

        writeLicensePlateCharsOnImage(imgOriginalScene, licPlate)

        # cv2.imshow("imgOriginalScene", imgOriginalScene)

        # cv2.imwrite("imgOriginalScene.png", imgOriginalScene)
    return
Пример #18
0
def main():
        
    #response = requests.get('http://localhost/getImage2.php').text
    #print(response)
    # do something
    
    start = time.time()
    blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN()         # attempt KNN training
    if blnKNNTrainingSuccessful == False:                               # if KNN training was not successful
        print("\nerror: KNN traning was not successful\n")  # show error message
        return                                                          # and exit program
    # end if
    

    imgOriginalScene  = cv2.imread("/home/pi/Downloads/gambar/banyak/28.jpg")
    imgOriginalScene  = imutils.resize(imgOriginalScene, width = 1355)

    imgGrayscale, imgThresh = pp.preprocess(imgOriginalScene)
    if imgOriginalScene is None:                            # if image was not read successfully
        print("\nerror: image not read from file \n\n")  # print error message to std out
        os.system("pause")                                  # pause so user can see error message
        return                                              # and exit program
    # end if



    plateResult = detectPlate(imgOriginalScene)
    end = time.time()
    print(end-start)
    
    #verify before send to db
    #twoChar = plateResult[:2]
    #oneChar = plateResult[:1]
    #ValidTwoChars = ["DD", "DP", "DW", "DC"]
    #ValidOneChars = [ord('B')]
    #    print("Hasil huruf awal sesuai")
        #sendRequest(plateResult, response)
    #elif oneChar in ValidOneChars :
        #sendRequest(plateResult, response)
     #   print("Hasil huruf awal sesuai")
    #else :
        #plateResult = "bukan plat terdeteksi"
    #sendRequest(plateResult, response)
     #   print("Hasil tidak sesuai")
    
    
    cv2.waitKey(0)					# hold windows open until user presses a key

    return
Пример #19
0
def main(filename):

    testKNN = DetectChars.loadKNNDataAndTrainKNN()

    if testKNN == False:
        print("\nerror: KNN traning was not successful\n")
        return

    imgOriginalScene = cv2.imread(filename)

    if imgOriginalScene is None:
        print("\nerror: image not read from file \n\n")
        os.system("pause")
        return

    listOfPossiblePlates = DetectPlates.detectPlatesInScene(
        imgOriginalScene)  #Find possible license plates(not match yet)
    listOfPossiblePlates = DetectChars.detectCharsInPlates(
        listOfPossiblePlates
    )  # the license plate which get recognized of specific content after processing

    if len(listOfPossiblePlates) == 0:
        print("\nno license plates were detected\n")
    else:

        # sort recognized plates in DESCENDING order based on the number of recognized chars
        listOfPossiblePlates.sort(
            key=lambda possiblePlate: len(possiblePlate.strChars),
            reverse=True)

        # the one with the most recognized chars is real plate
        licPlate = listOfPossiblePlates[0]

        if len(licPlate.strChars) == 0:
            print("\nno characters were detected\n\n")
            return

        print("\nlicense plate read from image = " + licPlate.strChars + "\n")
        print("----------------------------------------")

        localtime = datetime.datetime.now()
        date = localtime.strftime('%Y.%m.%d')
        localtime = localtime.strftime('%Y-%m-%d-%H:%M:%S')
        enterTime, leaveTime, duration = Mongo.insert(licPlate.strChars, date,
                                                      localtime, localtime)

    return licPlate.strChars, enterTime, leaveTime, duration
Пример #20
0
def num_read(var):
    blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN()
    if blnKNNTrainingSuccessful == False:
        print("\nerror: KNN traning was not successful\n")
        return
    # end if
    '''
    path= argparse.ArgumentParser()
    path.add_argument("-i", "--input", required=True,
                    help="path to input image")
    args = vars(path.parse_args())
    imgOriginalScene  = cv2.imread(args["input"])
    vech=vehicle.test_single_image(args["input"])
    '''
    path = var
    imgOriginalScene = cv2.imread(path)  # open image
    #vech = vehicle.test_single_image(path)

    if imgOriginalScene is None:
        print("\nerror: image not read from file \n\n")  #
        os.system("pause")
        return
    # end if
    listOfPossiblePlates = DetectPlates.detectPlatesInScene(imgOriginalScene)
    listOfPossiblePlates = DetectChars.detectCharsInPlates(
        listOfPossiblePlates)
    #cv2.imshow("imgOriginalScene", imgOriginalScene)
    if len(listOfPossiblePlates) == 0:
        print("\nno license plates were detected\n")
    else:
        listOfPossiblePlates.sort(
            key=lambda possiblePlate: len(possiblePlate.strChars),
            reverse=True)
        licPlate = listOfPossiblePlates[0]
        #cv2.imshow("imgPlate", licPlate.imgPlate)
        #cv2.imshow("imgThresh", licPlate.imgThresh)
        if len(licPlate.strChars) == 0:
            #print("\nno characters were detected\n\n")
            return
        # end if
        #print("\nlicense plate read from image = " + licPlate.strChars + "\n")
        #print("----------------------------------------")
        #cv2.imshow("imgOriginalScene", imgOriginalScene)
        cv2.imwrite("imgOriginalScene.png", imgOriginalScene)

    # end if else
    return licPlate.strChars
def main():

    blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN()

    if blnKNNTrainingSuccessful == False:
        print("\nerror: KNN training was not successful\n")
        return

    imgOriginalScene = cv2.imread("6.jpg")

    if imgOriginalScene is None:
        print("\nerror: image not read from file \n\n")
        os.system("pause")
        return

    listOfPossiblePlates = DetectPlates.detectPlatesInScene(imgOriginalScene)

    listOfPossiblePlates = DetectChars.detectCharsInPlates(
        listOfPossiblePlates)

    cv2.imshow("imgOriginalScene", imgOriginalScene)

    if len(listOfPossiblePlates) == 0:
        print("\nno license plates were detected\n")
    else:

        listOfPossiblePlates.sort(
            key=lambda possiblePlate: len(possiblePlate.strChars),
            reverse=True)

        licPlate = listOfPossiblePlates[0]

        if len(licPlate.strChars) == 0:
            print("\nno characters were detected\n\n")
            return

        #print("\nlicense plate read from image = " + licPlate.strChars + "\n")
        #print("----------------------------------------")
        return licPlate.strChars

    return
def LicRecognition():

    KNNTrainSuccess = DetectChars.loadKNNDataAndTrainKNN()
    if KNNTrainSuccess == False:
        print("error: KNN traning was not successful")
        return

    #imgOriginalScene  = cv2.imread('/home/pi/scripts/camera/LicenseImage.jpg')
    imgOriginalScene = cv2.imread('car2.jpg')  #car2.jpg, car8.jpg
    if imgOriginalScene is None:
        print("error: image not read from file")
        os.system("pause")
        return

    listOfPossiblePlates = DetectPlates.detectPlatesInScene(imgOriginalScene)
    listOfPossiblePlates = DetectChars.detectCharsInPlates(
        listOfPossiblePlates)

    if len(listOfPossiblePlates) == 0:
        print("no license plates were detected")

    else:
        listOfPossiblePlates.sort(
            key=lambda possiblePlate: len(possiblePlate.strChars),
            reverse=True)
        licPlate = listOfPossiblePlates[0]

        if len(licPlate.strChars) == 0:
            print("no characters were detected")
            return

        drawRedRectangleAroundPlate(imgOriginalScene, licPlate)
        with open('numberplate.txt', 'w') as file:
            file.write(licPlate.strChars)
        print("license plate read from image = " + licPlate.strChars)
        print("----------------------------------------")
        writeLicensePlateCharsOnImage(imgOriginalScene, licPlate)
        cv2.imshow("imgOriginalScene", imgOriginalScene)
        cv2.imwrite("imgOriginalScene.png", imgOriginalScene)
    return
Пример #23
0
def main():
    blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN()
    if blnKNNTrainingSuccessful == False:
        print("\nerror: KNN traning was not successful\n")
        return
    imgOriginalScene = cv2.imread(str(imagepath))
    if imgOriginalScene is None:
        print("\nerror: image not read from file \n\n")
        os.system("pause")
        return
    listOfPossiblePlates = DetectPlates.detectPlatesInScene(imgOriginalScene)
    listOfPossiblePlates = DetectChars.detectCharsInPlates(
        listOfPossiblePlates)
    if len(listOfPossiblePlates) == 0:
        print("\nno license plates were detected\n")
    else:
        listOfPossiblePlates.sort(
            key=lambda possiblePlate: len(possiblePlate.strChars),
            reverse=True)
        licPlate = listOfPossiblePlates[0]
        os.chdir('thresimages')
        key = str(imagepath).split('\\')
        key = str(key[-1])
        cv2.imwrite(key, ~licPlate.imgThresh)

        os.chdir('..')
        tesser.tessocr(key, licPlate.strChars)

        if len(licPlate.strChars) == 0:
            print("\nno characters were detected\n\n")
            return
        drawRedRectangleAroundPlate(imgOriginalScene, licPlate)
        print("\nLicense plate read from image = " + licPlate.strChars + "\n")
        print("----------------------------------------")

        writeLicensePlateCharsOnImage(imgOriginalScene, licPlate)
        os.chdir('output')
        cv2.imwrite(key, imgOriginalScene)
        os.chdir('..')
    return
Пример #24
0
def findPlate(imgOriginalScene):

    blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN(
    )  # attempt KNN training

    if blnKNNTrainingSuccessful == False:  # if KNN training was not successful
        print "\nerror: KNN traning was not successful\n"  # show error message
        return  # and exit program
    # end if

    if imgOriginalScene is None:  # if image was not read successfully
        print "\nerror: image not read from file \n\n"  # print error message to std out
        os.system("pause")  # pause so user can see error message
        return  # and exit program
    # end if

    plateList = DetectPlates.detectPlatesInScene(
        imgOriginalScene)  # detect plates

    plateList = DetectChars.detectCharsInPlates(
        plateList)  # detect chars in plates

    if len(plateList) == 0:  # if no plates were found
        return  # inform user no plates were found
    else:  # else

        plateList.sort(key=lambda possiblePlate: len(possiblePlate.strChars),
                       reverse=True)

        plateNo = plateList[0]

        if len(plateNo.strChars) == 0:  # if no chars were found in the plate
            return  # and exit program
        # end if

        stringArray = []

        return plateNo
Пример #25
0
def main(foto_name):

    blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN()         # attempt KNN training
    path = "./LicPlateImages/" + foto_name
    if blnKNNTrainingSuccessful == False:                               # if KNN training was not successful
        print ("\nerror: KNN traning was not successful\n")               # show error message
        return                                                          # and exit program
    # end if

    imgOriginalScene  = cv2.imread(path)               # open image

    if imgOriginalScene is None:                            # if image was not read successfully
        print ("\nerror: image not read from file \n\n")      # print error message to std out
        os.system("pause")                                  # pause so user can see error message
        return                                              # and exit program
    # end if

    listOfPossiblePlates = DetectPlates.detectPlatesInScene(imgOriginalScene)           # detect plates

    listOfPossiblePlates = DetectChars.detectCharsInPlates(listOfPossiblePlates)        # detect chars in plates

#cv2.imshow("imgOriginalScene", imgOriginalScene)            # show scene image

    if len(listOfPossiblePlates) == 0:                          # if no plates were found
        print ("\nno license plates were detected\n")             # inform user no plates were found
    else:                                                       # else
                # if we get in here list of possible plates has at leat one plate
                # sort the list of possible plates in DESCENDING order (most number of chars to least number of chars)
        listOfPossiblePlates.sort(key = lambda possiblePlate: len(possiblePlate.strChars), reverse = True)

                # suppose the plate with the most recognized chars (the first plate in sorted by string length descending order) is the actual plate
        licPlate = listOfPossiblePlates[0]
        if len(licPlate.strChars) == 0:                     # if no chars were found in the plate
            print ("\nno characters were detected\n\n")       # show message
            return                                          # and exit program
        # end if
        print ("\nlicense plate read from image = " + licPlate.strChars + "\n")       # write license plate text to std out
        print ("----------------------------------------")
Пример #26
0
def main():

    
    blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN()         # attempt KNN training

    if blnKNNTrainingSuccessful == False:                               # if KNN training was not successful
        print "\nerror: KNN traning was not successful\n"               # show error message
        return                                                          # and exit program
    # end if




    threads_list = []

    
    while(True)
        imgOriginalScene = cv2.imread("LicPlateImages/{}.png".format(i))  # open image

        if imgOriginalScene is None:  # if image was not read successfully
            print "\nerror: image not read from file \n\n"  # print error message to std out
            os.system("pause")  # pause so user can see error message
            return  # and exit program
        # end if
        
        thrd = threading.Thread(target =mainPart,  args = (imgOriginalScene,i,))
        threads_list.append(thrd)
        print('{} has started'.format(i))
        thrd.start()
    
    for thrd in threads_list:
        thrd.join()


    print("all done")

    return
 def main(self, cropped_plate_image, cropped_car):
 
     blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN()         # attempt KNN training
 
     if blnKNNTrainingSuccessful == False:                               # if KNN training was not successful
         print("\nerror: KNN traning was not successful\n")  # show error message
         return                                                          # and exit program
 
     imgOriginalScene  = cropped_plate_image               # open image
 
     if imgOriginalScene is None:                            # if image was not read successfully
         print("\nerror: image not read from file \n\n")  # print error message to std out
         os.system("pause")                                  # pause so user can see error message
         return                                              # and exit program
 
     listOfPossiblePlates = DetectPlates.detectPlatesInScene(imgOriginalScene)           # detect plates
 
     listOfPossiblePlates = DetectChars.detectCharsInPlates(listOfPossiblePlates)        # detect chars in plates
 
 
     if len(listOfPossiblePlates) != 0:                          
         listOfPossiblePlates.sort(key = lambda possiblePlate: len(possiblePlate.strChars), reverse = True)
 
         licPlate = listOfPossiblePlates[0]
 
         if len(licPlate.strChars) == 0:                     # if no chars were found in the plate
             return self.no_plate, self.get_car_color(cropped_car)                                       # and exit program
         
         if not self.getFromPlateRecord(licPlate.strChars) :
             self.plate_record.append(licPlate.strChars)
             color_value = self.get_car_color(cropped_car)
             return licPlate.strChars, color_value
         else:
             return self.same_frame, self.no_color
     else:
         return self.no_plate, self.no_color
Пример #28
0
def findPlate(imgOriginalScene):

    blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN()         # attempt KNN training

    if blnKNNTrainingSuccessful == False:                               # if KNN training was not successful
        print "\nerror: KNN traning was not successful\n"               # show error message
        return                                                          # and exit program
    # end if


    if imgOriginalScene is None:                            # if image was not read successfully
        print "\nerror: image not read from file \n\n"      # print error message to std out
        os.system("pause")                                  # pause so user can see error message
        return                                              # and exit program
    # end if

    plateList = DetectPlates.detectPlatesInScene(imgOriginalScene)           # detect plates

    plateList = DetectChars.detectCharsInPlates(plateList)        # detect chars in plates


    if len(plateList) == 0:                          # if no plates were found
        return            # inform user no plates were found
    else:                                                       # else
              
        plateList.sort(key = lambda possiblePlate: len(possiblePlate.strChars), reverse = True)

        plateNo = plateList[0]

        if len(plateNo.strChars) == 0:                     # if no chars were found in the plate
            return                                          # and exit program
        # end if

        stringArray = []
        
        return plateNo
Пример #29
0
def recognise(filePath):

    blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN(
    )  # attempt KNN training

    if blnKNNTrainingSuccessful == False:  # if KNN training was not successful
        # print "\nerror: KNN traning was not successful\n"
        # error = True            # show error message
        return -5  # and exit program
    # end if

    imgOriginalScene = cv2.imread(filePath)  # open image

    if imgOriginalScene is None:  # if image was not read successfully
        return -2  # and exit program
    # end if

    listOfPossiblePlates = DetectPlates.detectPlatesInScene(
        imgOriginalScene)  # detect plates

    listOfPossiblePlates = DetectChars.detectCharsInPlates(
        listOfPossiblePlates)  # detect chars in plates

    if len(listOfPossiblePlates) == 0:  # if no plates were found

        return -3  # inform user no plates were found
    else:  # else
        listOfPossiblePlates.sort(
            key=lambda possiblePlate: len(possiblePlate.strChars),
            reverse=True)
        licPlate = listOfPossiblePlates[0]

        if len(licPlate.strChars) == 0:
            return -4

    return licPlate.strChars
Пример #30
0
def main():
    blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN(
    )  # attempt KNN training

    if not blnKNNTrainingSuccessful:  # if KNN training was not successful
        print(
            "\nerror: KNN traning was not successful\n")  # show error message
        return  # and exit program
    # end if

    connectMongo()

    root = Tk()
    root.minsize(450, 300)
    root.title("CarPark Automation Image Processing")
    labelFrame = Frame(root)
    labelFrame.grid(column=0, row=1, padx=20, pady=20)
    button = Button(labelFrame, text="Browse A File", command=fileDialog)
    button.grid(column=1, row=1)

    # butt = Button(labelFrame, text="Say Hi", command=sayHi)
    # butt.grid(column=1, row=3)

    root.mainloop()
def main():
    #time.sleep(5)
    blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN(
    )  # attempt KNN training
    if blnKNNTrainingSuccessful == False:  # if KNN training was not successful
        print(
            "\nerror: KNN traning was not successful\n")  # show error message
        return  # and exit program
    # end if
    X_data = []
    files = glob.glob("LicencePlateImages/*.jpg")
    print(files)
    count = 1
    for myfile in files:
        imgOriginalScene = cv2.imread(myfile)  # open image
        X_data.append(imgOriginalScene)
        if imgOriginalScene is None:  # if image was not read successfully
            print("\nerror: image not read from file \n\n"
                  )  # print error message to std out
            os.system("pause")  # pause so user can see error message
            return  # and exit program
    # end if

        listOfPossiblePlates = DetectPlates.detectPlatesInScene(
            imgOriginalScene)  # detect plates

        listOfPossiblePlates = DetectChars.detectCharsInPlates(
            listOfPossiblePlates)  # detect chars in plates

        #cv2.imshow("imgOriginalScene", imgOriginalScene)            # show scene image

        if len(listOfPossiblePlates) == 0:  # if no plates were found
            print("\nno license plates were detected\n"
                  )  # inform user no plates were found
        else:  # else
            # if we get in here list of possible plates has at leat one plate

            # sort the list of possible plates in DESCENDING order (most number of chars to least number of chars)
            listOfPossiblePlates.sort(
                key=lambda possiblePlate: len(possiblePlate.strChars),
                reverse=True)

            # suppose the plate with the most recognized chars (the first plate in sorted by string length descending order) is the actual plate
            licPlate = listOfPossiblePlates[0]

            cv2.imwrite(
                "Result/plate%d.png" % count,
                licPlate.imgPlate)  # show crop of plate and threshold of plate
            cv2.imwrite("Result/imgThresh%d.png" % count, licPlate.imgThresh)
            count = count + 1
            if len(licPlate.strChars
                   ) == 0:  # if no chars were found in the plate
                print("\nno characters were detected\n\n")  # show message
                return  # and exit program
        # end if

            drawRedRectangleAroundPlate(
                imgOriginalScene, licPlate)  # draw red rectangle around plate

            print("\nlicense plate read from image = " + licPlate.strChars +
                  "\n")  # write license plate text to std out
            print("----------------------------------------")
            db.entry(licPlate.strChars)

            writeLicensePlateCharsOnImage(
                imgOriginalScene,
                licPlate)  # write license plate text on the image
def main():

    # First create a Github instance: using username and password
    #    g = Github("FinalProjectGit", "Github@12")
    #   repo = g.get_repo("FinalProjectGit/Project")

    #contents = repo.get_contents("Capture.PNG")
    #repo.delete_file(contents.path, "remove test", contents.sha)

    #    repoClone = pygit2.clone_repository(repo.git_url, 'D:\OpenCV_3_License_Plate_Recognition_Python-master\p')
    #    repoClone.remotes.set_url("origin", repo.clone_url)

    #    from github import Github
    #    import pygit2

    #    cam = cv2.VideoCapture(0)
    #
    #    cv2.namedWindow("test")
    #
    #    img_counter = 0
    #    ret, frame = cam.read()
    #    cv2.imshow("test", frame)
    #    img_name = "npr.png".format(img_counter)
    #    cv2.imwrite(img_name, frame)
    #    print("{} written!".format(img_name))
    #    img_counter += 1
    #    cam.release()
    #    cv2.destroyAllWindows()
    img_name = "test.jpg"

    blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN(
    )  # attempt KNN training

    if blnKNNTrainingSuccessful == False:  # if KNN training was not successful
        print(
            "\nerror: KNN traning was not successful\n")  # show error message
        return  # and exit program
    # end if
#    imgOriginalScene = np.full((100,80,3), 12, dtype = np.uint8)
    imgOriginalScene = cv2.imread(img_name)

    #    imgOriginalScene = np.array(imgOriginalScene, dtype=np.uint8)
    #  imgOriginalScene.show()
    #    from matplotlib import pyplot as plt
    #    plt.imshow(imgOriginalScene)
    #    plt.show()

    # open image
    if imgOriginalScene is None:  # if image was not read successfully
        file1 = open("output\Output.txt", "w")
        file1.write("error1")
        file1.close()
        return  # and exit program
    # end if

    listOfPossiblePlates = DetectPlates.detectPlatesInScene(
        imgOriginalScene)  # detect plates

    listOfPossiblePlates = DetectChars.detectCharsInPlates(
        listOfPossiblePlates)  # detect chars in plates

    #    cv2.imshow("imgOriginalScene", imgOriginalScene)            # show scene image

    if len(listOfPossiblePlates) == 0:  # if no plates were found
        file1 = open("output\Output.txt", "w")
        file1.write("error2")
        file1.close()
    else:  # else
        # if we get in here list of possible plates has at leat one plate

        # sort the list of possible plates in DESCENDING order (most number of chars to least number of chars)
        listOfPossiblePlates.sort(
            key=lambda possiblePlate: len(possiblePlate.strChars),
            reverse=True)

        # suppose the plate with the most recognized chars (the first plate in sorted by string length descending order) is the actual plate
        licPlate = listOfPossiblePlates[0]

        cv2.imwrite("cropedimage\Capture.PNG", licPlate.imgPlate)

        image = cv2.imread("cropedimage\Capture.PNG")
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

        gray = cv2.threshold(gray, 0, 255,
                             cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]

        filename = "{}.png".format(os.getpid())
        cv2.imwrite(filename, gray)

        text = pytesseract.image_to_string(Image.open(filename))
        os.remove(filename)

        plate = ""
        for c in text:
            if c.isupper():
                plate += c
            elif c.isdigit():
                plate += c
            #end if

        file1 = open(r"output\Output.txt", "w")
        file1.write(plate)
        file1.close()
Пример #33
0
def main():
    #############gui-work############################

    root = Tk()

    def write_slogan():
        print("Tkinter is easy to use!")
        root.filename = filedialog.askopenfilename(
            initialdir="/",
            title="Select file",
            filetypes=(("jpeg files", "*.jpg"), ("all files", "*.*")))

    label1 = Label(root,
                   text="AUTOMATIC NUMBER PLATE RECOGNITION SYSTEM",
                   fg="green",
                   bg="black",
                   height=4,
                   width=100,
                   font=10)
    button1 = Button(root, text="QUIT", fg="red", command=quit)

    button2 = Button(root, text="Pick", command=write_slogan)

    label2 = Label(root,
                   text="Click 'Pick' button to select an image",
                   font="Verdana 10 italic")

    img1 = PhotoImage(file="giphy.gif")
    img2 = PhotoImage(file="giphy.gif")
    img3 = PhotoImage(file="giphy.gif")

    w1 = Label(root, compound=CENTER, image=img1)

    w2 = Label(root, compound=CENTER, image=img2)

    w3 = Label(root, compound=CENTER, image=img3)

    label1.grid(row=0, column=0)
    button2.grid(row=1, column=0)
    button1.grid(row=2, column=0)
    label2.grid(row=3)
    w1.grid(row=4)
    w2.grid(row=5)
    w3.grid(row=6)
    root.mainloop()
    ###############gui-end############################

    blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN(
    )  # attempt KNN training

    if blnKNNTrainingSuccessful == False:  # if KNN training was not successful
        print(
            "\nerror: KNN traning was not successful\n")  # show error message
        return  # and exit program
    # end if
    imagename = root.filename
    imgOriginalScene = cv2.imread(imagename)  # open image

    if imgOriginalScene is None:  # if image was not read successfully
        print("\nerror: image not read from file \n\n"
              )  # print error message to std out
        os.system("pause")  # pause so user can see error message
        return  # and exit program
    # end if

    listOfPossiblePlates = DetectPlates.detectPlatesInScene(
        imgOriginalScene)  # detect plates

    listOfPossiblePlates = DetectChars.detectCharsInPlates(
        listOfPossiblePlates)  # detect chars in plates

    cv2.imshow("imgOriginalScene", imgOriginalScene)  # show scene image

    if len(listOfPossiblePlates) == 0:  # if no plates were found
        print("\nno license plates were detected\n"
              )  # inform user no plates were found
    else:  # else
        # if we get in here list of possible plates has at leat one plate

        # sort the list of possible plates in DESCENDING order (most number of chars to least number of chars)
        listOfPossiblePlates.sort(
            key=lambda possiblePlate: len(possiblePlate.strChars),
            reverse=True)

        # suppose the plate with the most recognized chars (the first plate in sorted by string length descending order) is the actual plate
        licPlate = listOfPossiblePlates[0]

        cv2.imshow(
            "imgPlate",
            licPlate.imgPlate)  # show crop of plate and threshold of plate
        cv2.imshow("imgThresh", licPlate.imgThresh)

        if len(licPlate.strChars) == 0:  # if no chars were found in the plate
            print("\nno characters were detected\n\n")  # show message
            return  # and exit program
        # end if

        drawRedRectangleAroundPlate(
            imgOriginalScene, licPlate)  # draw red rectangle around plate

        print("\nlicense plate read from image = " + licPlate.strChars +
              "\n")  # write license plate text to std out
        print("----------------------------------------")

        writeLicensePlateCharsOnImage(
            imgOriginalScene,
            licPlate)  # write license plate text on the image

        cv2.imshow("imgOriginalScene", imgOriginalScene)  # re-show scene image

        cv2.imwrite("imgOriginalScene.png",
                    imgOriginalScene)  # write image out to file

        #################################  Database work   ################
        db = pymysql.connect("localhost", "root", "", "testdb")
        cursor = db.cursor()
        sql = "SELECT * FROM plate_info"

        try:
            cursor.execute(sql)
            results = cursor.fetchall()
            #print(results)
        except:
            print("error from database")

        print("       INFORMATION FROM DATABSE")
        print("----------------------------------------")

        for i in range(0, 10):
            if results[i][0] == licPlate.strChars:
                print(results[i])

        db.close()
        ############################## db work end ######################################
    # end if else

    cv2.waitKey(0)  # hold windows open until user presses a key

    return
    def cbPose(self, image_msg):
        
        narr = np.fromstring(image_msg.data, np.uint8)
        image = cv2.imdecode(narr, cv2.CV_LOAD_IMAGE_COLOR)

##############################################################################################
	# module level variables ##########################################################################
	SCALAR_BLACK = (0.0, 0.0, 0.0)
	SCALAR_WHITE = (255.0, 255.0, 255.0)
	SCALAR_YELLOW = (0.0, 255.0, 255.0)
	SCALAR_GREEN = (0.0, 255.0, 0.0)
	SCALAR_RED = (0.0, 0.0, 255.0)

	showSteps = False	
	
	blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN()         # attempt KNN training

	if blnKNNTrainingSuccessful == False:                               # if KNN training was not successful
		print "\nerror: KNN traning was not successful\n"               # show error message
		return                                                          # and exit program
	    # end if

	imgOriginalScene  = image  #cv2.imread("1.png")               # open image

	#if imgOriginalScene is None:                            # if image was not read successfully
		#print "\nerror: image not read from file \n\n"      # print error message to std out
		#os.system("pause")                                  # pause so user can see error message
		#return                                              # and exit program
		# end if

	listOfPossiblePlates = DetectPlates.detectPlatesInScene(imgOriginalScene)           # detect plates

	listOfPossiblePlates = DetectChars.detectCharsInPlates(listOfPossiblePlates)        # detect chars in plates

	cv2.imshow("imgOriginalScene", imgOriginalScene)            # show scene image

	if len(listOfPossiblePlates) == 0:                          # if no plates were found
		print "\nno license plates were detected\n"             # inform user no plates were found
	else:                                                       # else
		# if we get in here list of possible plates has at leat one plate
		# sort the list of possible plates in DESCENDING order (most number of chars to least number of chars)
		listOfPossiblePlates.sort(key = lambda possiblePlate: len(possiblePlate.strChars), reverse = True)

		# suppose the plate with the most recognized chars (the first plate in sorted by string length descending order) is the actual plate
		licPlate = listOfPossiblePlates[0]

		cv2.imshow("imgPlate", licPlate.imgPlate)           # show crop of plate and threshold of plate
		cv2.imshow("imgThresh", licPlate.imgThresh)

		if len(licPlate.strChars) == 0:                     # if no chars were found in the plate
		    print "\nno characters were detected\n\n"       # show message
		    return                                          # and exit program
		# end if

		drawRedRectangleAroundPlate(imgOriginalScene, licPlate)             # draw red rectangle around plate

		print "\nlicense plate read from image = " + licPlate.strChars + "\n"       # write license plate text to std out
		print "----------------------------------------"

		writeLicensePlateCharsOnImage(imgOriginalScene, licPlate)           # write license plate text on the image

		cv2.imshow("imgOriginalScene", imgOriginalScene)                # re-show scene image

		#cv2.imwrite("imgOriginalScene.png", imgOriginalScene)           # write image out to file
		image = imgOriginalScene

	    # end if else

##############################################################################################

#        print "Found {0} faces!".format(len(faces))
        
#        for (x, y, w, h) in faces:
#           cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)
        #   cv2.imshow("preview", image)
        #   cv2.waitKey(0)
        #   cv2.destroyAllWindows()
        

	#cv2.rectangle(image, (100, 100), (120, 140), (0, 255, 0), 2)
        #image_msg_out = self.bridge.cv2_to_imgmsg(mask, "mono8")
        image_msg_out = self.bridge.cv2_to_imgmsg(image, "bgr8")
        image_msg_out.header.stamp = image_msg.header.stamp
        self.pub_image_original.publish(image_msg_out)
        #image_msg_out = self.bridge.cv2_to_imgmsg(gray, "bgr8")
        #image_msg_out.header.stamp = image_msg.header.stamp
        #self.pub_image_gray.publish(image_msg_out)
        #face_cascade = cv2.CascadeClassifier('~/haarcascade_frontalface_default.xml')
        #eye_cascade = cv2.CascadeClassifier('~/haarcascade_eye.xml')
        #gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        #faces = face_cascade.detectMultiScale(gray, 1.3, 5)
        #for (x,y,w,h) in faces:
        #    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
        #    roi_gray = gray[y:y+h, x:x+w]
        #    roi_color = img[y:y+h, x:x+w]
        #    self.eyes = eye_cascade.detectMultiScale(roi_gray)
        #for (ex,ey,ew,eh) in self.eyes:
        #    cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
        #    cv2.imwrite('hard.png',img)
        #    cv2.destroyAllWindows()

        car_control_msg = Twist2DStamped()