def searching(imgOriginalScene, loop): licenses = "" if imgOriginalScene is None: # if image was not read successfully print("error: image not read from file \n" ) # print error message to std out os.system("pause") # pause so user can see error message return # end if listOfPossiblePlates = DetectPlates.detectPlatesInScene( imgOriginalScene) # detect plates #time.sleep(0.02) listOfPossiblePlates = DetectChars.detectCharsInPlates( listOfPossiblePlates) # detect chars in plates #time.sleep(0.05) if (loop == False): cv2.imshow("imgOriginalScene", imgOriginalScene) if len(listOfPossiblePlates) == 0: if (loop == False): # if no plates were found print("no 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 (loop == False): 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 if (loop == False): print("no characters were detected\n") return # show message # end if drawRedRectangleAroundPlate(imgOriginalScene, licPlate) writeLicensePlateCharsOnImage(imgOriginalScene, licPlate) licenses = licPlate.strChars if (loop == False): print("license plate read from image = " + licenses + "\n") # write license plate text to std out # write license plate text on the image if (loop == False): cv2.imshow("imgOriginalScene", imgOriginalScene) # re-show scene image cv2.imwrite("imgOriginalScene.png", imgOriginalScene) return imgOriginalScene, licenses
def __car_detection(self, autonomous_states_queue): """ Detect the possible car in front of our car Store useful data states """ list_of_possible_plates = DetectPlates.detectPlatesInScene( self.__current_frame) list_of_possible_plates = DetectChars.detectCharsInPlates( list_of_possible_plates) list_of_possible_plates.sort(key=lambda possiblePlate: len(possiblePlate.strChars), \ reverse=True) if len(list_of_possible_plates) > 0: #at least one car lic_plate = list_of_possible_plates[0] frame_shape = self.__current_frame.shape self.__plate_coords = cv2.boxPoints( lic_plate.rrLocationOfPlateInScene) self.__distance_to_car = frame_shape[0] - self.__plate_coords[3][ 1] # in pixels self.__distance_to_car = self.__distance_to_car self.__distance_to_car = float("{0:.2f}".format( self.__distance_to_car)) self.__cruise_ndf_contor = 0 else: # make sure that the algoritm doesn't fail for a specific frame self.__cruise_ndf_contor = self.__cruise_ndf_contor + 1 if self.__cruise_ndf_contor > 5: self.__distance_to_car = 1000 self.__cruise_ndf_contor = 0
def main(np_img): blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN() if blnKNNTrainingSuccessful == False: print("\nerror: KNN traning was not successful\n") imgOriginalScene = np_img 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: return {"number_of_plates": 0, "plate_number": ""} else: listOfPossiblePlates.sort( key=lambda possiblePlate: len(possiblePlate.strChars), reverse=True) licPlate = listOfPossiblePlates[0] py_img = cv2.cvtColor(licPlate.imgPlate, cv2.COLOR_BGR2RGB) im_pil = Image.fromarray(py_img) drawRedRectangleAroundPlate(imgOriginalScene, licPlate) return { "number_of_plates": len(listOfPossiblePlates), "plate_number": pytesseract.image_to_string(im_pil) }
def main(): imgOriginalScene = cv2.imread( "LicPlateImages/WhatsApp Image 2019-07-27 at 1.37.30 PM.jpeg" ) # open image if imgOriginalScene is None: print("\nerror: image not read from file \n\n") os.system("pause") return listOfPossiblePlates = DetectPlates.detectPlatesInScene(imgOriginalScene) cv2.imshow("imgOriginalScene", imgOriginalScene) if len(listOfPossiblePlates) == 0: print("\nno license plates were detected\n") else: licPlate = listOfPossiblePlates[0] cv2.imshow("imgPlate", licPlate.imgPlate) drawRedRectangleAroundPlate(imgOriginalScene, licPlate) cv2.imshow("imgOriginalScene", imgOriginalScene) cv2.imwrite("imgOriginalScene.png", imgOriginalScene) cv2.waitKey(0) return
def main_detect (imgOriginalScene, k,number_finded ): blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN() # attempt KNN training if blnKNNTrainingSuccessful == False: # if KNN training was not successful print "\nerror: KNN traning was not successful\n" listOfPossiblePlates=DetectPlates.detectPlatesInScene(imgOriginalScene) listOfPossiblePlates = DetectChars.detectCharsInPlates(listOfPossiblePlates) if len(listOfPossiblePlates) == 0: if number_finded == False : return False else: listOfPossiblePlates.sort(key = lambda possiblePlate: len(possiblePlate.strChars), reverse = True) licPlate = listOfPossiblePlates[0] len_plate = len (licPlate.strChars) if len_plate < 9 and len_plate>0: number_finded = True if filter_list.count(licPlate)>0 : index_list[k] +=1 else : filter_list[k] = licPlate index_list[k] = k k+=1 return True
def main(image): CnnClassifier = CharacterDetection.loadCNNClassifier() if CnnClassifier == False: print("\nerror: CNN traning was not successful\n") return imgOriginalScene = cv2.imread(image) h, w = imgOriginalScene.shape[:2] imgOriginalScene = cv2.resize(imgOriginalScene, (0, 0), fx=1.4, fy=1.4, interpolation=cv2.INTER_LINEAR) if imgOriginalScene is None: print("\nerror: image not read from file \n\n") os.system("pause") return listOfPossiblePlates = DetectPlates.detectPlatesInScene(imgOriginalScene) listOfPossiblePlates = CharacterDetection.detectCharsInPlates( listOfPossiblePlates) # detect chars in plates if showSteps == True: cv2.imshow("imgOriginalScene", imgOriginalScene) if len(listOfPossiblePlates) == 0: # if no plates were found print("\nno license plates were detected\n") response = ' ' return response, imgOriginalScene else: listOfPossiblePlates.sort( key=lambda possiblePlate: len(possiblePlate.strChars), reverse=True) licPlate = listOfPossiblePlates[0] if showSteps == True: cv2.imshow("imgPlate", licPlate.imgPlate) cv2.waitKey(0) if len(licPlate.strChars) == 0: # if no chars were found in the plate print("\nno characters were detected\n\n") return ' ', imgOriginalScene drawRedRectangleAroundPlate( imgOriginalScene, licPlate) # draw red rectangle around plate print("\nlicense plate read from ", image, " :", licPlate.strChars, "\n") print("*******************************************") if showSteps == True: writeLicensePlateCharsOnImage( imgOriginalScene, licPlate) # write license plate text on the image cv2.imshow("imgOriginalScene", imgOriginalScene) cv2.imwrite("imgOriginalScene.png", imgOriginalScene) # write image out to file cv2.waitKey(0) return licPlate.strChars, licPlate.imgPlate
def get_plate(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 listOfPossiblePlates = DetectPlates.detectPlatesInScene(imgOriginalScene) # detect plates listOfPossiblePlates = DetectChars.detectCharsInPlates(listOfPossiblePlates) # detect chars in plates if len(listOfPossiblePlates) == 0: return None else: listOfPossiblePlates = list(filter(check_plate, listOfPossiblePlates)) listOfPossiblePlates.sort(key = lambda possiblePlate: len(possiblePlate.strChars), reverse = True) return [x.imgPlate for x in listOfPossiblePlates]
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("LicPlateImages/200.jpg") # open image imgOriginalScene = cv2.resize(imgOriginalScene,(640,480)) 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 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.imwrite('imgPlate.png', licPlate.imgPlate) 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 imgAfter = imgOriginalScene drawRedRectangleAroundPlate(imgAfter, licPlate) # draw red rectangle around plate print("\nlicense plate read from image = " + licPlate.strChars + "\n") # write license plate text to std out print("----------------------------------------") writeLicensePlateCharsOnImage(imgAfter, licPlate) # write license plate text on the image cv2.imshow("imgAfter", imgAfter) # re-show scene image #cv2.imwrite("imgAfter.png", imgAfter) # write image out to file # end if else cv2.waitKey(0) # hold windows open until user presses a key return
def main(): print("Yes") crt() blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN() if blnKNNTrainingSuccessful == False: print "\nerror: KNN traning was not successful\n" return # end if imgOriginalScene = cv2.imread(filename) 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 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) cv2.imshow("imgOriginalScene", imgOriginalScene) cv2.imwrite("imgOriginalScene.png", imgOriginalScene) # end if else cv2.waitKey(0) return
def main(): imgOriginalScene = cv2.imread("LicPlateImages/tablica7.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) licPlate = listOfPossiblePlates[0] cv2.imshow("imgThresh", licPlate.imgThresh) cv2.imshow("imgOriginalScene", imgOriginalScene) cv2.waitKey(0) return
def main(): KNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN() if KNNTrainingSuccessful == False: # if KNN training was not successful print("\nerror: KNN traning was not successful\n") return imgOriginalScene = cv2.imread("LicPlateImages/car3.jpg") # open image 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] 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) # 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) 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
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
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()
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
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
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()
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(): imgOriginalScene = cv2.imread("LicPlateImages/1.jpg") # imgOriginalScene = cv2.resize(imgOriginalScene,(1400,1230)) 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] # cv2.imshow("imgPlate", licPlate.imgPlate) # cv2.imshow("imgThresh", licPlate.imgThresh) if len(licPlate.strChars) == 0: print("\nno characters were detected\n\n") return global licPlateNumber licPlateNumber = finalPolish(licPlate.strChars) print("\nlicense plate read from image = " + licPlateNumber + "\n") print("----------------------------------------") cv2.imwrite("imgOriginalScene.png", imgOriginalScene) databaseconstant = FireDatabase.retrieve(licPlateNumber) if (databaseconstant == None): print( "The Vehicle has not been booked for any parking space in this parking station: ACCESS DENIED" ) else: eoe = FireDatabase.checkforentryorexit(licPlateNumber) if (eoe == None): print( "The Vehicle has not been booked for any parking space in this parking station: ACCESS DENIED" ) global status status = -1 elif (eoe == 'entry'): print("**********Access Granted**********") status = 1 elif (eoe == 'exit'): print('**********Drive Safely**********') status = 0 return
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
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}'
def main(conn): url = 'http://2weeks.ipdisk.co.kr:8000/apps/xe/write_DB.php' while (True): img = conn.recv() imgOriginalScene = img 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 text = '0' requests.post(url, data={'number': '1', 'car': text}).text 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("imgPlate.png", licPlate.imgPlate) cv2.imwrite("imgThresh.png", licPlate.imgThresh) if len(licPlate.strChars ) == 0: # if no chars were found in the plate print("\nno characters were detected\n\n") # show message licPlate.strChars = '0' # end if print("text = " + licPlate.strChars) requests.post(url, data={ 'number': '1', 'car': licPlate.strChars }).text cv2.imwrite("imgOriginalScene.png", imgOriginalScene) # write image out to file
def main(): imgOriginalScene = cv2.imread("48.jpg") # open image startTime = datetime.datetime.now() 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 cropped_img = listOfPossiblePlates[0:500, 0:500] cv2.imshow("cropped", cropped_img) cv2.waitKey(0) # 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 licPlate1 = listOfPossiblePlates[0] #licPlate2 = listOfPossiblePlates[1] #cv2.imshow("imgPlate", licPlate.imgPlate) # show crop of plate and threshold of plate #cv2.imshow("imgThresh", licPlate.imgThresh) drawRedRectangleAroundPlate( imgOriginalScene, licPlate1) # draw red rectangle around plate #drawRedRectangleAroundPlate(imgOriginalScene, licPlate2) # draw red rectangle around plate ################################################## ################################################## endTime = datetime.datetime.now() runningTime = endTime - startTime #print(runningTime) #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
def main(): blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN() if blnKNNTrainingSuccessful == False: print("\nerror: KNN traning was not successful\n") return imgOriginalScene = cv2.imread( "C:\\Users\\anil\\Desktop\\OpenCV_3_License_Plate_Recognition_Python-master\\9.png" ) # open image 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] 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) print("\nlicense plate read from image = " + licPlate.strChars + "\n") print("----------------------------------------") writeLicensePlateCharsOnImage(imgOriginalScene, licPlate) cv2.imshow("imgOriginalScene", imgOriginalScene) cv2.imwrite("imgOriginalScene.png", imgOriginalScene) cv2.waitKey(0) return
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
def extract_char(img): image = DetectPlates.extract(img) img_gray, thresh = Preprocess.preprocess(image) listOfPossibleChars = [] imgContours, contours, npaHierarchy = cv2.findContours( thresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) def sort_contours(cnts, method="left-to-right"): # initialize the reverse flag and sort index reverse = False i = 0 # handle if we need to sort in reverse if method == "right-to-left" or method == "bottom-to-top": reverse = True # handle if we are sorting against the y-coordinate rather than # the x-coordinate of the bounding box if method == "top-to-bottom" or method == "bottom-to-top": i = 1 # construct the list of bounding boxes and sort them from top to # bottom boundingBoxes = [cv2.boundingRect(c) for c in cnts] (cnts, boundingBoxes) = zip(*sorted( zip(cnts, boundingBoxes), key=lambda b: b[1][i], reverse=reverse)) # return the list of sorted contours and bounding boxes return (cnts, boundingBoxes) (contours, boundingBoxes) = sort_contours(contours) for i in range(len(contours)): #check xem contours tim duoc co kha nang la char hay khong if checkIfPossibleChar_(contours[i]): listOfPossibleChars.append(contours[i]) idx = 0 for i in range(len(contours)): # tra ve vi tri chieu rong, cao cho moi duowng vien x, y, w, h = cv2.boundingRect(contours[i]) #crop and save idx += 1 new_img = image[y - 2:y + h + 2, x - 1:x + w + 1] img_gray = cv2.cvtColor(new_img, cv2.COLOR_BGR2GRAY) #new_img = 1- new_img _, img_threshold = cv2.threshold(img_gray, 150, 255, cv2.THRESH_BINARY) new_img = img_threshold
def rafa(frame): car_image = frame[y1:y2, x1:x2, :] imgOriginalScene = cv2.resize(car_image, (0, 0), fx=1.4, fy=1.4, interpolation=cv2.INTER_CUBIC) listOfPossiblePlates = DetectPlates.detectPlatesInScene(imgOriginalScene) if len(listOfPossiblePlates) > 0: points = cv2.boxPoints( listOfPossiblePlates[0].rrLocationOfPlateInScene) (xlp1, ylp1) = tuple(points[1]) (xlp2, ylp2) = tuple(points[2]) (xlp3, ylp3) = tuple(points[3]) (xlp0, ylp0) = tuple(points[0]) hb = 20 vb = 20 points[1] = (xlp1 - hb, ylp1 - vb) points[2] = (xlp2 + hb, ylp2 - vb) points[3] = (xlp3 + hb, ylp3 + vb) points[0] = (xlp0 - hb, ylp0 + vb) (xlp1, ylp1) = tuple(points[1]) (xlp2, ylp2) = tuple(points[2]) (xlp3, ylp3) = tuple(points[3]) (xlp0, ylp0) = tuple(points[0]) xlp1 = max(0, xlp1) xlp0 = max(0, xlp0) xlp2 = min(xlp2, frame.shape[1]) xlp3 = min(xlp3, frame.shape[1]) ylp1 = max(0, ylp1) ylp2 = max(0, ylp2) ylp0 = min(ylp0, frame.shape[1]) ylp3 = min(ylp3, frame.shape[1]) """"said asdf""" cv2.line(imgOriginalScene, tuple(points[0]), tuple(points[1]), (0, 255, 0), 2) cv2.line(imgOriginalScene, tuple(points[1]), tuple(points[2]), (0, 255, 0), 2) cv2.line(imgOriginalScene, tuple(points[2]), tuple(points[3]), (0, 255, 0), 2) cv2.line(imgOriginalScene, tuple(points[3]), tuple(points[0]), (0, 255, 0), 2) lp_image = imgOriginalScene[int(ylp1):int(ylp3), int(xlp1):int(xlp3), :] return True, lp_image else: return False, None
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
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
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 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
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
def license_plate_recognition(self): training_successful = DetectChars.load_and_train() if not training_successful: print("\nerror: KNN training was not successful\n") return file = ''.join(self.plate_image_file[0]) img_original_scene = cv2.imread(file) if img_original_scene is None: msg = QtWidgets.QErrorMessage() msg.showMessage("Can't open Image from file") exit(-1) return list_of_possible_plates = DetectPlates.detect_plates_in_scene( img_original_scene) list_of_possible_plates = DetectChars.detect_chars_in_plates( list_of_possible_plates) if len(list_of_possible_plates) == 0: msg = QtWidgets.QErrorMessage() msg.showMessage("No license plate were detected") else: list_of_possible_plates.sort( key=lambda possible_plate: len(possible_plate.strChars), reverse=True) lic_plate = list_of_possible_plates[0] if len(lic_plate.strChars) == 0: msg = QtWidgets.QErrorMessage() msg.showMessage("No characters were detected") return draw_rectangle_around_plate(img_original_scene, lic_plate) f = open('Plates.txt', 'a') f.write(lic_plate.strChars) f.close() write_license_plate_chars_on_image(img_original_scene, lic_plate) cv2.imwrite("img_original_scene.png", img_original_scene) pixmap = QtGui.QPixmap("img_original_scene.png") self.label.setPixmap(pixmap)
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
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()