#plakaTespit.py kodları import cv2 import numpy as np import math import giris1 import random import hazirlik import KarakterTespiti import olasiPlaka import olasiKarakter PLATE_WIDTH_PADDING_FACTOR = 1.3 PLATE_HEIGHT_PADDING_FACTOR = 1.5 def plaka_tespit_et(imgOriginalScene): listOfPossiblePlates = [] # this will be the return value height, width, numChannels = imgOriginalScene.shape imgGrayscaleScene = np.zeros((height, width, 1), np.uint8) imgThreshScene = np.zeros((height, width, 1), np.uint8) imgContours = np.zeros((height, width, 3), np.uint8) cv2.destroyAllWindows() if giris1.adimleri_goster == True: # show steps ####################################################### cv2.imshow("0", imgOriginalScene) # end if # show steps ######################################################################### imgGrayscaleScene, imgThreshScene = hazirlik.onhazirlikislemi(imgOriginalScene) # preprocess to get grayscale and threshold images if giris1.adimleri_goster == True: # show steps ####################################################### cv2.imshow("1a", imgGrayscaleScene) cv2.imshow("1b", imgThreshScene) # end if # show steps ######################################################################### # find all possible chars in the scene, # this function first finds all contours, then only includes contours that could be chars (without comparison to other chars yet) listOfPossibleCharsInScene = findPossibleCharsInScene(imgThreshScene) if giris1.adimleri_goster == True: # show steps ####################################################### print("step 2 - len(listOfPossibleCharsInScene) = " + str( len(listOfPossibleCharsInScene))) # 131 with MCLRNF1 image imgContours = np.zeros((height, width, 3), np.uint8) contours = [] for possibleChar in listOfPossibleCharsInScene: contours.append(possibleChar.contour) # end for cv2.drawContours(imgContours, contours, -1, giris1.beyaz) cv2.imshow("2b", imgContours) # end if # show steps ######################################################################### # given a list of all possible chars, find groups of matching chars # in the next steps each group of matching chars will attempt to be recognized as a plate listOfListsOfMatchingCharsInScene = KarakterTespiti.findListOfListsOfMatchingChars(listOfPossibleCharsInScene) if giris1.adimleri_goster == True: # show steps ####################################################### print("step 3 - listOfListsOfMatchingCharsInScene.Count = " + str( len(listOfListsOfMatchingCharsInScene))) # 13 with MCLRNF1 image imgContours = np.zeros((height, width, 3), np.uint8) for listOfMatchingChars in listOfListsOfMatchingCharsInScene: intRandomBlue = random.randint(0, 255) intRandomGreen = random.randint(0, 255) intRandomRed = random.randint(0, 255) contours = [] for matchingChar in listOfMatchingChars: contours.append(matchingChar.contour) # end for cv2.drawContours(imgContours, contours, -1, (intRandomBlue, intRandomGreen, intRandomRed)) # end for cv2.imshow("3", imgContours) # end if # show steps ######################################################################### for listOfMatchingChars in listOfListsOfMatchingCharsInScene: # for each group of matching chars possiblePlate = extractPlate(imgOriginalScene, listOfMatchingChars) # attempt to extract plate if possiblePlate.imgPlate is not None: # if plate was found listOfPossiblePlates.append(possiblePlate) # add to list of possible plates # end if # end for print("\n" + str(len(listOfPossiblePlates)) + " possible plates found") # 13 with MCLRNF1 image if giris1.adimleri_goster == True: # show steps ####################################################### print("\n") cv2.imshow("4a", imgContours) for i in range(0, len(listOfPossiblePlates)): p2fRectPoints = cv2.boxPoints(listOfPossiblePlates[i].rrLocationOfPlateInScene) cv2.line(imgContours, tuple(p2fRectPoints[0]), tuple(p2fRectPoints[1]), giris1.kirmizi, 2) cv2.line(imgContours, tuple(p2fRectPoints[1]), tuple(p2fRectPoints[2]), giris1.kirmizi, 2) cv2.line(imgContours, tuple(p2fRectPoints[2]), tuple(p2fRectPoints[3]), giris1.kirmizi, 2) cv2.line(imgContours, tuple(p2fRectPoints[3]), tuple(p2fRectPoints[0]), giris1.kirmizi, 2) cv2.imshow("4a", imgContours) print("possible plate " + str(i) + ", click on any image and press a key to continue . . .") cv2.imshow("4b", listOfPossiblePlates[i].imgPlate) cv2.waitKey(0) # end for print("\nPlaka tespiti tamamlandı, herhangi bir resme tıkla ve bir tuşa tıkla ve karakter tanımayı başlat . . .\n") cv2.waitKey(0) # end if # show steps ######################################################################### return listOfPossiblePlates # end function ################################################################################################### def findPossibleCharsInScene(imgThresh): listOfPossibleChars = [] # this will be the return value intCountOfPossibleChars = 0 imgThreshCopy = imgThresh.copy() #imgContours, contours, npaHierarchy = cv2.findContours(imgThreshCopy, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) # find all contours contours, npaHierarchy = cv2.findContours(imgThreshCopy, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) height, width = imgThresh.shape imgContours = np.zeros((height, width, 3), np.uint8) for i in range(0, len(contours)): # for each contour if giris1.adimleri_goster == True: # show steps ################################################### cv2.drawContours(imgContours, contours, i, giris1.beyaz) # end if # show steps ##################################################################### possibleChar = olasiKarakter.PossibleChar(contours[i]) if KarakterTespiti.checkIfPossibleChar(possibleChar): # if contour is a possible char, note this does not compare to other chars (yet) . . . intCountOfPossibleChars = intCountOfPossibleChars + 1 # increment count of possible chars listOfPossibleChars.append(possibleChar) # and add to list of possible chars # end if # end for if giris1.adimleri_goster == True: # show steps ####################################################### print("\nstep 2 - len(contours) = " + str(len(contours))) # 2362 with MCLRNF1 image print("step 2 - intCountOfPossibleChars = " + str(intCountOfPossibleChars)) # 131 with MCLRNF1 image cv2.imshow("2a", imgContours) # end if # show steps ######################################################################### return listOfPossibleChars # end function ################################################################################################### def extractPlate(imgOriginal, listOfMatchingChars): possiblePlate = olasiPlaka.PossiblePlate() # this will be the return value listOfMatchingChars.sort(key = lambda matchingChar: matchingChar.intCenterX) # sort chars from left to right based on x position # calculate the center point of the plate fltPlateCenterX = (listOfMatchingChars[0].intCenterX + listOfMatchingChars[len(listOfMatchingChars) - 1].intCenterX) / 2.0 fltPlateCenterY = (listOfMatchingChars[0].intCenterY + listOfMatchingChars[len(listOfMatchingChars) - 1].intCenterY) / 2.0 ptPlateCenter = fltPlateCenterX, fltPlateCenterY # calculate plate width and height intPlateWidth = int((listOfMatchingChars[len(listOfMatchingChars) - 1].intBoundingRectX + listOfMatchingChars[len(listOfMatchingChars) - 1].intBoundingRectWidth - listOfMatchingChars[0].intBoundingRectX) * PLATE_WIDTH_PADDING_FACTOR) intTotalOfCharHeights = 0 for matchingChar in listOfMatchingChars: intTotalOfCharHeights = intTotalOfCharHeights + matchingChar.intBoundingRectHeight # end for fltAverageCharHeight = intTotalOfCharHeights / len(listOfMatchingChars) intPlateHeight = int(fltAverageCharHeight * PLATE_HEIGHT_PADDING_FACTOR) # calculate correction angle of plate region fltOpposite = listOfMatchingChars[len(listOfMatchingChars) - 1].intCenterY - listOfMatchingChars[0].intCenterY fltHypotenuse = KarakterTespiti.distanceBetweenChars(listOfMatchingChars[0], listOfMatchingChars[len(listOfMatchingChars) - 1]) fltCorrectionAngleInRad = math.asin(fltOpposite / fltHypotenuse) fltCorrectionAngleInDeg = fltCorrectionAngleInRad * (180.0 / math.pi) # pack plate region center point, width and height, and correction angle into rotated rect member variable of plate possiblePlate.rrLocationOfPlateInScene = ( tuple(ptPlateCenter), (intPlateWidth, intPlateHeight), fltCorrectionAngleInDeg ) # final steps are to perform the actual rotation # get the rotation matrix for our calculated correction angle rotationMatrix = cv2.getRotationMatrix2D(tuple(ptPlateCenter), fltCorrectionAngleInDeg, 1.0) height, width, numChannels = imgOriginal.shape # unpack original image width and height imgRotated = cv2.warpAffine(imgOriginal, rotationMatrix, (width, height)) # rotate the entire image imgCropped = cv2.getRectSubPix(imgRotated, (intPlateWidth, intPlateHeight), tuple(ptPlateCenter)) possiblePlate.imgPlate = imgCropped # copy the cropped plate image into the applicable member variable of the possible plate return possiblePlate # end function #olasiPlaka.py kodlarıi import cv2 import numpy as np ################################################################################################### class PossiblePlate: # constructor ################################################################################# def __init__(self): self.imgPlate = None self.imgGrayscale = None self.imgThresh = None self.rrLocationOfPlateInScene = None self.strChars = "" # end constructor # end class # olasiKarakter.py kodları import math import cv2 ################################################################################################### class PossibleChar: # constructor ################################################################################# def __init__(self, _contour): self.contour = _contour self.boundingRect = cv2.boundingRect(self.contour) [intX, intY, intWidth, intHeight] = self.boundingRect self.intBoundingRectX = intX self.intBoundingRectY = intY self.intBoundingRectWidth = intWidth self.intBoundingRectHeight = intHeight self.intBoundingRectArea = self.intBoundingRectWidth * self.intBoundingRectHeight self.intCenterX = (self.intBoundingRectX + self.intBoundingRectX + self.intBoundingRectWidth) / 2 self.intCenterY = (self.intBoundingRectY + self.intBoundingRectY + self.intBoundingRectHeight) / 2 self.fltDiagonalSize = math.sqrt((self.intBoundingRectWidth ** 2) + (self.intBoundingRectHeight ** 2)) self.fltAspectRatio = float(self.intBoundingRectWidth) / float(self.intBoundingRectHeight) # end constructor # end class # KarakterTespitEt.py kodlari import os import cv2 import numpy as np import math import random import giris1 import hazirlik import olasiKarakter # module level variables ########################################################################## kNearest = cv2.ml.KNearest_create() # constants for checkIfPossibleChar, this checks one possible char only (does not compare to another char) MIN_PIXEL_WIDTH = 2 MIN_PIXEL_HEIGHT = 8 MIN_ASPECT_RATIO = 0.25 MAX_ASPECT_RATIO = 1.0 MIN_PIXEL_AREA = 80 # constants for comparing two chars MIN_DIAG_SIZE_MULTIPLE_AWAY = 0.3 MAX_DIAG_SIZE_MULTIPLE_AWAY = 5.0 MAX_CHANGE_IN_AREA = 0.5 MAX_CHANGE_IN_WIDTH = 0.8 MAX_CHANGE_IN_HEIGHT = 0.2 MAX_ANGLE_BETWEEN_CHARS = 12.0 # other constants MIN_NUMBER_OF_MATCHING_CHARS = 3 RESIZED_CHAR_IMAGE_WIDTH = 20 RESIZED_CHAR_IMAGE_HEIGHT = 30 MIN_CONTOUR_AREA = 100 ################################################################################################### def KNN_verisi_yukle_KNN_ogren(): allContoursWithData = [] # declare empty lists, validContoursWithData = [] # we will fill these shortly try: npaClassifications = np.loadtxt("classifications.txt", np.float32) # read in training classifications except: # if file could not be opened print("hata, sınıflandırmalar.txt açılamıyor, programdan çıkılıyor\n") # show error message os.system("pause") return False # and return False # end try try: npaFlattenedImages = np.loadtxt("classifications.txt", np.float32) # read in training images except: # if file could not be opened print("error, unable to open flattened_images.txt, exiting program\n") # show error message os.system("pause") return False # and return False # end try npaClassifications = npaClassifications.reshape((npaClassifications.size, 1)) # reshape numpy array to 1d, necessary to pass to call to train kNearest.setDefaultK(1) # set default K to 1 kNearest.train(npaFlattenedImages, cv2.ml.ROW_SAMPLE, npaClassifications) # train KNN object return True # if we got here training was successful so return true # end function ################################################################################################### def plakada_karakter_tespit_et(listOfPossiblePlates): intPlateCounter = 0 imgContours = None contours = [] if len(listOfPossiblePlates) == 0: # if list of possible plates is empty return listOfPossiblePlates # return # end if # at this point we can be sure the list of possible plates has at least one plate for possiblePlate in listOfPossiblePlates: # for each possible plate, this is a big for loop that takes up most of the function possiblePlate.imgGrayscale, possiblePlate.imgThresh = hazirlik.onhazirlikislemi(possiblePlate.imgPlate) # preprocess to get grayscale and threshold images if giris1.adimleri_goster == True: # show steps ################################################### cv2.imshow("5a", possiblePlate.imgPlate) cv2.imshow("5b", possiblePlate.imgGrayscale) cv2.imshow("5c", possiblePlate.imgThresh) # end if # show steps ##################################################################### # increase size of plate image for easier viewing and char detection possiblePlate.imgThresh = cv2.resize(possiblePlate.imgThresh, (0, 0), fx = 1.6, fy = 1.6) # threshold again to eliminate any gray areas thresholdValue, possiblePlate.imgThresh = cv2.threshold(possiblePlate.imgThresh, 0.0, 255.0, cv2.THRESH_BINARY | cv2.THRESH_OTSU) if giris1.adimleri_goster == True: # show steps ################################################### cv2.imshow("5d", possiblePlate.imgThresh) # end if # show steps ##################################################################### # find all possible chars in the plate, # this function first finds all contours, then only includes contours that could be chars (without comparison to other chars yet) listOfPossibleCharsInPlate = findPossibleCharsInPlate(possiblePlate.imgGrayscale, possiblePlate.imgThresh) if giris1.adimleri_goster == True: # show steps ################################################### height, width, numChannels = possiblePlate.imgPlate.shape imgContours = np.zeros((height, width, 3), np.uint8) del contours[:] # clear the contours list for possibleChar in listOfPossibleCharsInPlate: contours.append(possibleChar.contour) # end for cv2.drawContours(imgContours, contours, -1, giris1.beyaz) cv2.imshow("6", imgContours) # end if # show steps ##################################################################### # given a list of all possible chars, find groups of matching chars within the plate listOfListsOfMatchingCharsInPlate = findListOfListsOfMatchingChars(listOfPossibleCharsInPlate) if giris1.adimleri_goster == True: # show steps ################################################### imgContours = np.zeros((height, width, 3), np.uint8) del contours[:] for listOfMatchingChars in listOfListsOfMatchingCharsInPlate: intRandomBlue = random.randint(0, 255) intRandomGreen = random.randint(0, 255) intRandomRed = random.randint(0, 255) for matchingChar in listOfMatchingChars: contours.append(matchingChar.contour) # end for cv2.drawContours(imgContours, contours, -1, (intRandomBlue, intRandomGreen, intRandomRed)) # end for cv2.imshow("7", imgContours) # end if # show steps ##################################################################### if (len(listOfListsOfMatchingCharsInPlate) == 0): # if no groups of matching chars were found in the plate if giris1.adimleri_goster == True: # show steps ############################################### print("chars found in plate number " + str( intPlateCounter) + " = (none), click on any image and press a key to continue . . .") intPlateCounter = intPlateCounter + 1 cv2.destroyWindow("8") cv2.destroyWindow("9") cv2.destroyWindow("10") cv2.waitKey(0) # end if # show steps ################################################################# possiblePlate.strChars = "" continue # go back to top of for loop # end if for i in range(0, len(listOfListsOfMatchingCharsInPlate)): # within each list of matching chars listOfListsOfMatchingCharsInPlate[i].sort(key = lambda matchingChar: matchingChar.intCenterX) # sort chars from left to right listOfListsOfMatchingCharsInPlate[i] = removeInnerOverlappingChars(listOfListsOfMatchingCharsInPlate[i]) # and remove inner overlapping chars # end for if giris1.adimleri_goster == True: # show steps ################################################### imgContours = np.zeros((height, width, 3), np.uint8) for listOfMatchingChars in listOfListsOfMatchingCharsInPlate: intRandomBlue = random.randint(0, 255) intRandomGreen = random.randint(0, 255) intRandomRed = random.randint(0, 255) del contours[:] for matchingChar in listOfMatchingChars: contours.append(matchingChar.contour) # end for cv2.drawContours(imgContours, contours, -1, (intRandomBlue, intRandomGreen, intRandomRed)) # end for cv2.imshow("8", imgContours) # end if # show steps ##################################################################### # within each possible plate, suppose the longest list of potential matching chars is the actual list of chars intLenOfLongestListOfChars = 0 intIndexOfLongestListOfChars = 0 # loop through all the vectors of matching chars, get the index of the one with the most chars for i in range(0, len(listOfListsOfMatchingCharsInPlate)): if len(listOfListsOfMatchingCharsInPlate[i]) > intLenOfLongestListOfChars: intLenOfLongestListOfChars = len(listOfListsOfMatchingCharsInPlate[i]) intIndexOfLongestListOfChars = i # end if # end for # suppose that the longest list of matching chars within the plate is the actual list of chars longestListOfMatchingCharsInPlate = listOfListsOfMatchingCharsInPlate[intIndexOfLongestListOfChars] if giris1.adimleri_goster == True: # show steps ################################################### imgContours = np.zeros((height, width, 3), np.uint8) del contours[:] for matchingChar in longestListOfMatchingCharsInPlate: contours.append(matchingChar.contour) # end for cv2.drawContours(imgContours, contours, -1, giris1.beyaz) cv2.imshow("9", imgContours) # end if # show steps ##################################################################### possiblePlate.strChars = recognizeCharsInPlate(possiblePlate.imgThresh, longestListOfMatchingCharsInPlate) if giris1.adimleri_goster == True: # show steps ################################################### print("chars found in plate number " + str( intPlateCounter) + " = " + possiblePlate.strChars + ", click on any image and press a key to continue . . .") intPlateCounter = intPlateCounter + 1 cv2.waitKey(0) # end if # show steps ##################################################################### # end of big for loop that takes up most of the function if giris1.adimleri_goster == True: print("\nchar detection complete, click on any image and press a key to continue . . .\n") cv2.waitKey(0) # end if return listOfPossiblePlates # end function ################################################################################################### def findPossibleCharsInPlate(imgGrayscale, imgThresh): listOfPossibleChars = [] # this will be the return value contours = [] imgThreshCopy = imgThresh.copy() # find all contours in plate #imgContours, contours, npaHierarchy = cv2.findContours(imgThreshCopy, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) contours, npaHierarchy = cv2.findContours(imgThreshCopy, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) for contour in contours: # for each contour possibleChar = olasiKarakter.PossibleChar(contour) if checkIfPossibleChar(possibleChar): # if contour is a possible char, note this does not compare to other chars (yet) . . . listOfPossibleChars.append(possibleChar) # add to list of possible chars # end if # end if return listOfPossibleChars # end function ################################################################################################### def checkIfPossibleChar(possibleChar): # this function is a 'first pass' that does a rough check on a contour to see if it could be a char, # note that we are not (yet) comparing the char to other chars to look for a group if (possibleChar.intBoundingRectArea > MIN_PIXEL_AREA and possibleChar.intBoundingRectWidth > MIN_PIXEL_WIDTH and possibleChar.intBoundingRectHeight > MIN_PIXEL_HEIGHT and MIN_ASPECT_RATIO < possibleChar.fltAspectRatio and possibleChar.fltAspectRatio < MAX_ASPECT_RATIO): return True else: return False # end if # end function ################################################################################################### def findListOfListsOfMatchingChars(listOfPossibleChars): # with this function, we start off with all the possible chars in one big list # the purpose of this function is to re-arrange the one big list of chars into a list of lists of matching chars, # note that chars that are not found to be in a group of matches do not need to be considered further listOfListsOfMatchingChars = [] # this will be the return value for possibleChar in listOfPossibleChars: # for each possible char in the one big list of chars listOfMatchingChars = findListOfMatchingChars(possibleChar, listOfPossibleChars) # find all chars in the big list that match the current char listOfMatchingChars.append(possibleChar) # also add the current char to current possible list of matching chars if len(listOfMatchingChars) < MIN_NUMBER_OF_MATCHING_CHARS: # if current possible list of matching chars is not long enough to constitute a possible plate continue # jump back to the top of the for loop and try again with next char, note that it's not necessary # to save the list in any way since it did not have enough chars to be a possible plate # end if # if we get here, the current list passed test as a "group" or "cluster" of matching chars listOfListsOfMatchingChars.append(listOfMatchingChars) # so add to our list of lists of matching chars listOfPossibleCharsWithCurrentMatchesRemoved = [] # remove the current list of matching chars from the big list so we don't use those same chars twice, # make sure to make a new big list for this since we don't want to change the original big list listOfPossibleCharsWithCurrentMatchesRemoved = list(set(listOfPossibleChars) - set(listOfMatchingChars)) recursiveListOfListsOfMatchingChars = findListOfListsOfMatchingChars(listOfPossibleCharsWithCurrentMatchesRemoved) # recursive call for recursiveListOfMatchingChars in recursiveListOfListsOfMatchingChars: # for each list of matching chars found by recursive call listOfListsOfMatchingChars.append(recursiveListOfMatchingChars) # add to our original list of lists of matching chars # end for break # exit for # end for return listOfListsOfMatchingChars # end function ################################################################################################### def findListOfMatchingChars(possibleChar, listOfChars): # the purpose of this function is, given a possible char and a big list of possible chars, # find all chars in the big list that are a match for the single possible char, and return those matching chars as a list listOfMatchingChars = [] # this will be the return value for possibleMatchingChar in listOfChars: # for each char in big list if possibleMatchingChar == possibleChar: # if the char we attempting to find matches for is the exact same char as the char in the big list we are currently checking # then we should not include it in the list of matches b/c that would end up double including the current char continue # so do not add to list of matches and jump back to top of for loop # end if # compute stuff to see if chars are a match fltDistanceBetweenChars = distanceBetweenChars(possibleChar, possibleMatchingChar) fltAngleBetweenChars = angleBetweenChars(possibleChar, possibleMatchingChar) fltChangeInArea = float(abs(possibleMatchingChar.intBoundingRectArea - possibleChar.intBoundingRectArea)) / float(possibleChar.intBoundingRectArea) fltChangeInWidth = float(abs(possibleMatchingChar.intBoundingRectWidth - possibleChar.intBoundingRectWidth)) / float(possibleChar.intBoundingRectWidth) fltChangeInHeight = float(abs(possibleMatchingChar.intBoundingRectHeight - possibleChar.intBoundingRectHeight)) / float(possibleChar.intBoundingRectHeight) # check if chars match if (fltDistanceBetweenChars < (possibleChar.fltDiagonalSize * MAX_DIAG_SIZE_MULTIPLE_AWAY) and fltAngleBetweenChars < MAX_ANGLE_BETWEEN_CHARS and fltChangeInArea < MAX_CHANGE_IN_AREA and fltChangeInWidth < MAX_CHANGE_IN_WIDTH and fltChangeInHeight < MAX_CHANGE_IN_HEIGHT): listOfMatchingChars.append(possibleMatchingChar) # if the chars are a match, add the current char to list of matching chars # end if # end for return listOfMatchingChars # return result # end function ################################################################################################### # use Pythagorean theorem to calculate distance between two chars def distanceBetweenChars(firstChar, secondChar): intX = abs(firstChar.intCenterX - secondChar.intCenterX) intY = abs(firstChar.intCenterY - secondChar.intCenterY) return math.sqrt((intX ** 2) + (intY ** 2)) # end function ################################################################################################### # use basic trigonometry (SOH CAH TOA) to calculate angle between chars def angleBetweenChars(firstChar, secondChar): fltAdj = float(abs(firstChar.intCenterX - secondChar.intCenterX)) fltOpp = float(abs(firstChar.intCenterY - secondChar.intCenterY)) if fltAdj != 0.0: # check to make sure we do not divide by zero if the center X positions are equal, float division by zero will cause a crash in Python fltAngleInRad = math.atan(fltOpp / fltAdj) # if adjacent is not zero, calculate angle else: fltAngleInRad = 1.5708 # if adjacent is zero, use this as the angle, this is to be consistent with the C++ version of this program # end if fltAngleInDeg = fltAngleInRad * (180.0 / math.pi) # calculate angle in degrees return fltAngleInDeg # end function ################################################################################################### # if we have two chars overlapping or to close to each other to possibly be separate chars, remove the inner (smaller) char, # this is to prevent including the same char twice if two contours are found for the same char, # for example for the letter 'O' both the inner ring and the outer ring may be found as contours, but we should only include the char once def removeInnerOverlappingChars(listOfMatchingChars): listOfMatchingCharsWithInnerCharRemoved = list(listOfMatchingChars) # this will be the return value for currentChar in listOfMatchingChars: for otherChar in listOfMatchingChars: if currentChar != otherChar: # if current char and other char are not the same char . . . # if current char and other char have center points at almost the same location . . . if distanceBetweenChars(currentChar, otherChar) < (currentChar.fltDiagonalSize * MIN_DIAG_SIZE_MULTIPLE_AWAY): # if we get in here we have found overlapping chars # next we identify which char is smaller, then if that char was not already removed on a previous pass, remove it if currentChar.intBoundingRectArea < otherChar.intBoundingRectArea: # if current char is smaller than other char if currentChar in listOfMatchingCharsWithInnerCharRemoved: # if current char was not already removed on a previous pass . . . listOfMatchingCharsWithInnerCharRemoved.remove(currentChar) # then remove current char # end if else: # else if other char is smaller than current char if otherChar in listOfMatchingCharsWithInnerCharRemoved: # if other char was not already removed on a previous pass . . . listOfMatchingCharsWithInnerCharRemoved.remove(otherChar) # then remove other char # end if # end if # end if # end if # end for # end for return listOfMatchingCharsWithInnerCharRemoved # end function ################################################################################################### # this is where we apply the actual char recognition def recognizeCharsInPlate(imgThresh, listOfMatchingChars): strChars = "" # this will be the return value, the chars in the lic plate height, width = imgThresh.shape imgThreshColor = np.zeros((height, width, 3), np.uint8) listOfMatchingChars.sort(key = lambda matchingChar: matchingChar.intCenterX) # sort chars from left to right cv2.cvtColor(imgThresh, cv2.COLOR_GRAY2BGR, imgThreshColor) # make color version of threshold image so we can draw contours in color on it for currentChar in listOfMatchingChars: # for each char in plate pt1 = (currentChar.intBoundingRectX, currentChar.intBoundingRectY) pt2 = ((currentChar.intBoundingRectX + currentChar.intBoundingRectWidth), (currentChar.intBoundingRectY + currentChar.intBoundingRectHeight)) cv2.rectangle(imgThreshColor, pt1, pt2, giris1.yesil, 2) # draw green box around the char # crop char out of threshold image imgROI = imgThresh[currentChar.intBoundingRectY : currentChar.intBoundingRectY + currentChar.intBoundingRectHeight, currentChar.intBoundingRectX : currentChar.intBoundingRectX + currentChar.intBoundingRectWidth] imgROIResized = cv2.resize(imgROI, (RESIZED_CHAR_IMAGE_WIDTH, RESIZED_CHAR_IMAGE_HEIGHT)) # resize image, this is necessary for char recognition npaROIResized = imgROIResized.reshape((1, RESIZED_CHAR_IMAGE_WIDTH * RESIZED_CHAR_IMAGE_HEIGHT)) # flatten image into 1d numpy array npaROIResized = np.float32(npaROIResized) # convert from 1d numpy array of ints to 1d numpy array of floats retval, npaResults, neigh_resp, dists = kNearest.findNearest(npaROIResized, k = 1) # finally we can call findNearest !!! strCurrentChar = str(chr(int(npaResults[0][0]))) # get character from results strChars = strChars + strCurrentChar # append current char to full string # end for if giris1.adimleri_goster == True: # show steps ####################################################### cv2.imshow("10", imgThreshColor) # end if # show steps ######################################################################### return strChars # end function #islem.py kodlari import function as func def image(): try: sec = input("Resim Adı:") if(sec!=""): #Seçilen dosya adı null değilse img=func.resimAc(sec) #Resim Açma İşlemi img_gray=func.griyecevir(img) #griye cevirme fonk gurultuazalt=func.gurultuAzalt(img_gray) #Gurultu azaltma fonksiyonu h_esitleme=func.histogramEsitleme(gurultuazalt) #Histogram Eşitleme morfolojik_resim=func.morfolojikIslem(h_esitleme) #Morfolojik islem goruntucikarma=func.goruntuCikarma(h_esitleme,morfolojik_resim) #Goruntu Çıkarma İşlemi goruntuesikleme=func.goruntuEsikle(goruntucikarma) ##Goruntu Eşikleme İşlemi cannedge_goruntu=func.cannyEdge(goruntuesikleme) #Canny_Edge İşlemi gen_goruntu=func.genisletmeIslemi(cannedge_goruntu) #Dilated (Genişletme İşlemi) screenCnt=func.konturIslemi(img,gen_goruntu) #Kontur İşlemi yeni_goruntu=func.maskelemeIslemi(img_gray,img,screenCnt) #Maskeleme İşlemi func.plakaIyilestir(yeni_goruntu) #Maskelenmiş görüntü üzerinde işlemler. func.cv2.waitKey() #Bir tuşa basarsan pencereyi kapatır. except : print("Lütfen Resim adını kontrol ediniz...") #hazirlik.py dosya kodlari import cv2 import numpy as np # module level variables ########################################################################## GAUSSIAN_SMOOTH_FILTER_SIZE = (5, 5) ADAPTIVE_THRESH_BLOCK_SIZE = 19 ADAPTIVE_THRESH_WEIGHT = 9 ################################################################################################### def hazirlikislemi(orjinalresim): gri_ton_resim = extractValue(orjinalresim) imgMaxContrastGrayscale = maximizeContrast(gri_ton_resim) height, width = gri_ton_resim.shape imgBlurred = np.zeros((height, width, 1), np.uint8) imgBlurred = cv2.GaussianBlur(imgMaxContrastGrayscale, GAUSSIAN_SMOOTH_FILTER_SIZE, 0) imgThresh = cv2.adaptiveThreshold(imgBlurred, 255.0, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, ADAPTIVE_THRESH_BLOCK_SIZE, ADAPTIVE_THRESH_WEIGHT) return gri_ton_resim, imgThresh # end function ################################################################################################### def extractValue(imgOriginal): height, width, numChannels = imgOriginal.shape imgHSV = np.zeros((height, width, 3), np.uint8) imgHSV = cv2.cvtColor(imgOriginal, cv2.COLOR_BGR2HSV) imgHue, imgSaturation, imgValue = cv2.split(imgHSV) return imgValue # end function ################################################################################################### def maximizeContrast(imgGrayscale): height, width = imgGrayscale.shape imgTopHat = np.zeros((height, width, 1), np.uint8) imgBlackHat = np.zeros((height, width, 1), np.uint8) structuringElement = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) imgTopHat = cv2.morphologyEx(imgGrayscale, cv2.MORPH_TOPHAT, structuringElement) imgBlackHat = cv2.morphologyEx(imgGrayscale, cv2.MORPH_BLACKHAT, structuringElement) imgGrayscalePlusTopHat = cv2.add(imgGrayscale, imgTopHat) imgGrayscalePlusTopHatMinusBlackHat = cv2.subtract(imgGrayscalePlusTopHat, imgBlackHat) return imgGrayscalePlusTopHatMinusBlackHat # end function #giris.py kodlari import cv2 import numpy as np import os import KarakterTespiti import plakaTespit import olasiPlaka # module level variables ########################################################################## siyah = (0.0, 0.0, 0.0) beyaz = (255.0, 255.0, 255.0) sari = (0.0, 255.0, 255.0) yesil = (0.0, 255.0, 0.0) kirmizi = (0.0, 0.0, 255.0) adimleri_goster = False ################################################################################################### def giris1(): KNN_Ogrenme_basarisi = KarakterTespiti.KNN_verisi_yukle_KNN_ogren() # attempt KNN training if KNN_Ogrenme_basarisi == False: # if KNN training was not successful print("\nhata: KNN başarılı uygulanamadı\n") # show error message return # and exit program # end if orijinal_resim = cv2.imread("arac_listesi/3.jpg") # open image if orijinal_resim is None: # if image was not read successfully print("\nhata: dosyadan resim okunamadı \n\n") # print error message to std out os.system("pause") # pause so user can see error message return # and exit program # end if ihtimal_plaka_listeleri = plakaTespit.plaka_tespit_et(orijinal_resim) # detect plates ihtimal_plaka_listeleri = KarakterTespiti.plakada_karakter_tespit_et(ihtimal_plaka_listeleri) # detect chars in plates cv2.imshow("orijinal_resim", orijinal_resim) # show scene image if len(ihtimal_plaka_listeleri) == 0: # if no plates were found print("\nPlaka tespit edilemedi\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) ihtimal_plaka_listeleri.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 Plaka = ihtimal_plaka_listeleri[0] cv2.imshow("imgPlate", Plaka.imgPlate) # show crop of plate and threshold of plate cv2.imshow("imgThresh", Plaka.imgThresh) if len(Plaka.strChars) == 0: # if no chars were found in the plate print("\nkarakter tespit edilemedi.\n\n") # show message return # and exit program # end if PlakaCevresineKirmiziDortgenCiz(orijinal_resim, Plaka) # draw red rectangle around plate print("\nresimden okunan plaka = " + Plaka.strChars + "\n") # write license plate text to std out print("----------------------------------------") resimePlakalariIsle(orijinal_resim, Plaka) # write license plate text on the image cv2.imshow("orijinal_resim", orijinal_resim) # re-show scene image cv2.imwrite("orijinal_resim.png", orijinal_resim) # write image out to file # end if else cv2.waitKey(0) # hold windows open until user presses a key return # end main ################################################################################################### def PlakaCevresineKirmiziDortgenCiz(imgOriginalScene, licPlate): p2fRectPoints = cv2.boxPoints(licPlate.rrLocationOfPlateInScene) # get 4 vertices of rotated rect cv2.line(imgOriginalScene, tuple(p2fRectPoints[0]), tuple(p2fRectPoints[1]), kirmizi, 2) # draw 4 red lines cv2.line(imgOriginalScene, tuple(p2fRectPoints[1]), tuple(p2fRectPoints[2]), kirmizi, 2) cv2.line(imgOriginalScene, tuple(p2fRectPoints[2]), tuple(p2fRectPoints[3]), kirmizi, 2) cv2.line(imgOriginalScene, tuple(p2fRectPoints[3]), tuple(p2fRectPoints[0]), kirmizi, 2) # end function ################################################################################################### def resimePlakalariIsle(imgOriginalScene, licPlate): ptCenterOfTextAreaX = 0 # this will be the center of the area the text will be written to ptCenterOfTextAreaY = 0 ptLowerLeftTextOriginX = 0 # this will be the bottom left of the area that the text will be written to ptLowerLeftTextOriginY = 0 sceneHeight, sceneWidth, sceneNumChannels = imgOriginalScene.shape plateHeight, plateWidth, plateNumChannels = licPlate.imgPlate.shape intFontFace = cv2.FONT_HERSHEY_SIMPLEX # choose a plain jane font fltFontScale = float(plateHeight) / 30.0 # base font scale on height of plate area intFontThickness = int(round(fltFontScale * 1.5)) # base font thickness on font scale textSize, baseline = cv2.getTextSize(licPlate.strChars, intFontFace, fltFontScale, intFontThickness) # call getTextSize # unpack roatated rect into center point, width and height, and angle ( (intPlateCenterX, intPlateCenterY), (intPlateWidth, intPlateHeight), fltCorrectionAngleInDeg ) = licPlate.rrLocationOfPlateInScene intPlateCenterX = int(intPlateCenterX) # make sure center is an integer intPlateCenterY = int(intPlateCenterY) ptCenterOfTextAreaX = int(intPlateCenterX) # the horizontal location of the text area is the same as the plate if intPlateCenterY < (sceneHeight * 0.75): # if the license plate is in the upper 3/4 of the image ptCenterOfTextAreaY = int(round(intPlateCenterY)) + int(round(plateHeight * 1.6)) # write the chars in below the plate else: # else if the license plate is in the lower 1/4 of the image ptCenterOfTextAreaY = int(round(intPlateCenterY)) - int(round(plateHeight * 1.6)) # write the chars in above the plate # end if textSizeWidth, textSizeHeight = textSize # unpack text size width and height ptLowerLeftTextOriginX = int(ptCenterOfTextAreaX - (textSizeWidth / 2)) # calculate the lower left origin of the text area ptLowerLeftTextOriginY = int(ptCenterOfTextAreaY + (textSizeHeight / 2)) # based on the text area center, width, and height # write the text on the image cv2.putText(imgOriginalScene, licPlate.strChars, (ptLowerLeftTextOriginX, ptLowerLeftTextOriginY), intFontFace, fltFontScale, sari, intFontThickness) # end function ################################################################################################### if __name__ == "__giris1__": giris1() #giris.py kodlari import islem import camera print(""" ############################################## # # ###------ PLAKA TANIMA SİSTEMİ------### # # ############################################## """) print("Resimden plaka tanıma işlemi yapmak için 1'e") print("Kamera'dan plaka tanıma işlemi yapmak için 2'ye") try: secim = int(input("Seçiminiz:")) if secim == 1: islem.image() elif secim == 2: camera.camera() else: exit() except ValueError: print("Hatalı seçim Lütfen menüden seçim yapınız.") #function2.py kodlari import cv2 # Opencv Kütüphanesini Projeme Dahil ediyorum. import numpy as np #Numpy kütühanesi dahil etme işlemi // Maskeleme işlemlerinde kullanılacak def resimAc(sec): # Dosyadan resim okumak için dosyamın yolunu seciyoruz. img = cv2.imread("Resim/" + sec) cv2.namedWindow("1-Orjinal Resim", cv2.WINDOW_NORMAL) # resm göstermek için bir pencere oluşturma cv2.imshow("1-Orjinal Resim", img) # Ekranda resim gösterme işlemi return img # RGB uzayından Gri seviyeli resme dönüş işlemi def griyecevir(img): img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) cv2.namedWindow("2-Griye Donusturme İslemi", cv2.WINDOW_NORMAL) # Pencre Oluştur cv2.imshow("2-Griye Donusturme İslemi", img_gray) # Resmi Göster return img_gray #2. Gauss Filtreleme , Medyan ortalama ile aynı işi yapan fonk. ## gürültü azaltıcı yumuşatma işlemi #Her pikselin yoğunluğunu, yakındaki piksellerin yoğunluk ortalamasının ağırlıklı ortalaması ile değiştirir #Diğer üç filtre kenarları pürüzsüz hale getirirken sesleri kaldırır, ancak bu filtre, kenar #koruyarak görüntünün gürültüyü azaltabilir. def gurultuAzalt(img_gray): gurultuazalt = cv2.bilateralFilter(img_gray, 9, 75, 75) cv2.namedWindow("3-Gürültü Temizleme islemi", cv2.WINDOW_NORMAL) cv2.imshow("3-Gürültü Temizleme islemi", gurultuazalt) return gurultuazalt # Daha iyi sonuç elde etmek için histogram eşitleme işlemi yapıyoruz def histogramEsitleme(gurultuazalt): histogram_e = cv2.equalizeHist(gurultuazalt) cv2.namedWindow("4-Histogram esitleme islemi", cv2.WINDOW_NORMAL) cv2.imshow("4-Histogram esitleme islemi", histogram_e) return histogram_e # Açma İşlemi(Opening): #Aşındırma ile küçük parçalar yok edildikten sonra dilation ile görüntü tekrar genişletilerek küçük parçaların kaybolması sağlanır. #gürültülerin etkisi azaltılır. def morfolojikIslem(h_esitleme): kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)) morfolojikresim = cv2.morphologyEx(h_esitleme, cv2.MORPH_OPEN, kernel, iterations=15) cv2.namedWindow("5-Morfolojik acilim", cv2.WINDOW_NORMAL) cv2.imshow("5-Morfolojik acilim", morfolojikresim) return morfolojikresim #Resim üzerinde düzensiz bölümleri dengelemek. # veya iki resim arasındaki değişiklikleri saptamak için görüntü çıkarma kullanılır.(Image subtraction). def goruntuCikarma(h_esitleme,morfolojik_resim): # Görüntü çıkarma (Morph görüntüsünü histogram eşitlenmiş görüntüsünden çıkarmak) gcikarilmisresim = cv2.subtract(h_esitleme, morfolojik_resim) cv2.namedWindow("6-Goruntu cikarma", cv2.WINDOW_NORMAL) cv2.imshow("6-Goruntu cikarma", gcikarilmisresim) return gcikarilmisresim # görüntüdeki her pikseli siyah bir piksel ile değiştirir; Formul var ona göre yapıyor # görüntü yoğunluğu bu sabitten büyükse beyaz bir piksel def goruntuEsikle(goruntucikarma): ret, goruntuesikle = cv2.threshold(goruntucikarma, 0, 255, cv2.THRESH_OTSU) cv2.namedWindow("7-Goruntu Esikleme", cv2.WINDOW_NORMAL) cv2.imshow("7-Goruntu Esikleme", goruntuesikle) return goruntuesikle #Görüntünün kenarlarını algılamak için canny edge kullandım def cannyEdge(goruntuesikleme): canny_goruntu = cv2.Canny(goruntuesikleme, 250, 255) cv2.namedWindow("8-Canny Edge", cv2.WINDOW_NORMAL) cv2.imshow("8-Canny Edge", canny_goruntu) canny_goruntu = cv2.convertScaleAbs(canny_goruntu) return canny_goruntu #Dilatasyon operatörü, girdi olarak iki veri alanını alır. # Birincisi dilate edilecek olan resimdir. İkincisi, yapılandırma unsuru cekirdek #Dilate, Büyümek, Genişletmek def genisletmeIslemi(cannedge_goruntu): # Kenarları güçlendirmek için genleşme cekirdek = np.ones((3, 3), np.uint8) # Genişletme için çekirdek oluşturma gen_goruntu = cv2.dilate(cannedge_goruntu, cekirdek, iterations=1) cv2.namedWindow("9-Genisletme", cv2.WINDOW_NORMAL) cv2.imshow("9-Genisletme", gen_goruntu) return gen_goruntu def konturIslemi(img,gen_goruntu): # Kenarlara dayanan resimdeki Konturları Bulma new, contours, hierarchy = cv2.findContours(gen_goruntu, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) contours = sorted(contours, key=cv2.contourArea, reverse=True)[:10] # Rakamları alana göre sıralama, böylece sayı plakası ilk 10 konturda olacak screenCnt = None # kontur dng işlemi for c in contours: # yaklaşık çizgi belirliyoruz peri = cv2.arcLength(c, True) approx = cv2.approxPolyDP(c, 0.06 * peri, True) # % 6 hata ile yaklaşıklık # Yaklaşık konturuzun dört noktası varsa, o zaman # ----Plakamızı yaklaşık olarak bulduğumuzu varsayabiliriz. if len(approx) == 4: # Konturu 4 köşeli olarak seçiyoruz screenCnt = approx break final = cv2.drawContours(img, [screenCnt],-1, (9, 236, 255), 3) # KARENİN RENGİ VE ÇİZİMİ # Seçilen konturun orijinal resimde çizilmesi cv2.namedWindow("10-Konturlu Goruntu", cv2.WINDOW_NORMAL) cv2.imshow("10-Konturlu Goruntu", final) return screenCnt ##Belirnenen alan dışında kalan yerleri maskeleme def maskelemeIslemi(img_gray,img,screenCnt): # Numara plakası dışındaki kısmı maskeleme mask = np.zeros(img_gray.shape, np.uint8) yeni_goruntu = cv2.drawContours(mask, [screenCnt], 0, 255, -1, ) yeni_goruntu = cv2.bitwise_and(img, img, mask=mask) cv2.namedWindow("11-Plaka", cv2.WINDOW_NORMAL) cv2.imshow("11-Plaka", yeni_goruntu) return yeni_goruntu def plakaIyilestir(yeni_goruntu): # Daha fazla işlem için numara plakasını geliştirmek için histogram eşitleme y, cr, cb = cv2.split(cv2.cvtColor(yeni_goruntu, cv2.COLOR_RGB2YCrCb)) # Görüntüyü YCrCb modeline dönüştürme ve 3 kanalı bölme y = cv2.equalizeHist(y) # Histogram eşitleme uygulama son_resim = cv2.cvtColor(cv2.merge([y, cr, cb]), cv2.COLOR_YCrCb2RGB) # 3 kanalı birleştirme #cv2.namedWindow("Gelismis_plaka_no", cv2.WINDOW_NORMAL) #cv2.imshow("Gelismis_plaka_no", son_resim) return son_resim #function.py kodlari import cv2 # Opencv Kütüphanesini Projeme Dahil ediyorum. import numpy as np # Numpy kütühanesi dahil etme işlemi // Maskeleme işlemlerinde kullanılacak def resimAc(sec): # Dosyadan resim okumak için dosyamın yolunu seciyoruz. img = cv2.imread("Resim/" + sec) # cv2.namedWindow("Orjinal Resim", cv2.WINDOW_NORMAL) # resm göstermek için bir pencere oluşturma # cv2.imshow("Orjinal Resim", img) # Ekranda resim gösterme işlemi return img # RGB uzayından Gri seviyeli resme dönüş işlemi def griyecevir(img): img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) # cv2.namedWindow("Gray Converted Image", cv2.WINDOW_NORMAL) # Pencre Oluştur # cv2.imshow("Gray Converted Image", img_gray) # Resmi Göster return img_gray # 2. Gauss Filtreleme , Medyan ortalama ile aynı işi yapan fonk. ## gürültü azaltıcı yumuşatma işlemi # Her pikselin yoğunluğunu, yakındaki piksellerin yoğunluk ortalamasının ağırlıklı ortalaması ile değiştirir # Diğer üç filtre kenarları pürüzsüz hale getirirken sesleri kaldırır, ancak bu filtre, kenar #koruyarak görüntünün gürültüyü azaltabilir. def gurultuAzalt(img_gray): gurultuazalt = cv2.bilateralFilter(img_gray, 9, 75, 75) # cv2.namedWindow("Gürültü Temizleme islemi", cv2.WINDOW_NORMAL) # cv2.imshow("Gürültü Temizleme islemi", gurultuazalt) return gurultuazalt # Daha iyi sonuç elde etmek için histogram eşitleme işlemi yapıyoruz def histogramEsitleme(gurultuazalt): histogram_e = cv2.equalizeHist(gurultuazalt) # cv2.namedWindow("Histogram esitleme islemi", cv2.WINDOW_NORMAL) # cv2.imshow("Histogram esitleme islemi", histogram_e) return histogram_e # Açma İşlemi(Opening): # Aşındırma ile küçük parçalar yok edildikten sonra dilation ile görüntü tekrar genişletilerek küçük parçaların kaybolması sağlanır. # gürültülerin etkisi azaltılır. def morfolojikIslem(h_esitleme): kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)) morfolojikresim = cv2.morphologyEx(h_esitleme, cv2.MORPH_OPEN, kernel, iterations=15) # cv2.namedWindow("Morfolojik acilim", cv2.WINDOW_NORMAL) # cv2.imshow("Morfolojik acilim", morfolojikresim) return morfolojikresim # Resim üzerinde düzensiz bölümleri dengelemek. # veya iki resim arasındaki değişiklikleri saptamak için görüntü çıkarma kullanılır.(Image subtraction). def goruntuCikarma(h_esitleme, morfolojik_resim): # Görüntü çıkarma (Morph görüntüsünü histogram eşitlenmiş görüntüsünden çıkarmak) gcikarilmisresim = cv2.subtract(h_esitleme, morfolojik_resim) # cv2.namedWindow("Goruntu cikarma", cv2.WINDOW_NORMAL) # cv2.imshow("Goruntu cikarma", gcikarilmisresim) return gcikarilmisresim # görüntüdeki her pikseli siyah bir piksel ile değiştirir; Formul var ona göre yapıyor # görüntü yoğunluğu bu sabitten büyükse beyaz bir piksel def goruntuEsikle(goruntucikarma): ret, goruntuesikle = cv2.threshold(goruntucikarma, 0, 255, cv2.THRESH_OTSU) # cv2.namedWindow("Goruntu Esikleme", cv2.WINDOW_NORMAL) # cv2.imshow("Goruntu Esikleme", goruntuesikle) return goruntuesikle # Görüntünün kenarlarını algılamak için canny edge kullandım def cannyEdge(goruntuesikleme): canny_goruntu = cv2.Canny(goruntuesikleme, 250, 255) # cv2.namedWindow("Canny Edge", cv2.WINDOW_NORMAL) # cv2.imshow("Canny Edge", canny_goruntu) canny_goruntu = cv2.convertScaleAbs(canny_goruntu) return canny_goruntu # Dilatasyon operatörü, girdi olarak iki veri alanını alır. # Birincisi dilate edilecek olan resimdir. İkincisi, yapılandırma unsuru cekirdek # Dilate, Büyümek, Genişletmek def genisletmeIslemi(cannedge_goruntu): # Kenarları güçlendirmek için genleşme cekirdek = np.ones((3, 3), np.uint8) # Genişletme için çekirdek oluşturma gen_goruntu = cv2.dilate(cannedge_goruntu, cekirdek, iterations=1) # cv2.namedWindow("Genisletme", cv2.WINDOW_NORMAL) # cv2.imshow("Genisletme", gen_goruntu) return gen_goruntu def konturIslemi(img, gen_goruntu): # Kenarlara dayanan resimdeki Konturları Bulma new, contours, hierarchy = cv2.findContours(gen_goruntu, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) contours = sorted(contours, key=cv2.contourArea, reverse=True)[:10] # Rakamları alana göre sıralama, böylece sayı plakası ilk 10 konturda olacak screenCnt = None # kontur dng işlemi for c in contours: # yaklaşık çizgi belirliyoruz peri = cv2.arcLength(c, True) approx = cv2.approxPolyDP(c, 0.06 * peri, True) # % 6 hata ile yaklaşıklık # Yaklaşık konturuzun dört noktası varsa, o zaman # ----Plakamızı yaklaşık olarak bulduğumuzu varsayabiliriz. if len(approx) == 4: # Konturu 4 köşeli olarak seçiyoruz screenCnt = approx break final = cv2.drawContours(img, [screenCnt], -1, (9, 236, 255), 3) # KARENİN RENGİ VE ÇİZİMİ # Seçilen konturun orijinal resimde çizilmesi # cv2.namedWindow("Konturlu Goruntu", cv2.WINDOW_NORMAL) # cv2.imshow("Konturlu Goruntu", final) return screenCnt ##Belirnenen alan dışında kalan yerleri maskeleme def maskelemeIslemi(img_gray, img, screenCnt): # Numara plakası dışındaki kısmı maskeleme mask = np.zeros(img_gray.shape, np.uint8) yeni_goruntu = cv2.drawContours(mask, [screenCnt], 0, 255, -1, ) yeni_goruntu = cv2.bitwise_and(img, img, mask=mask) cv2.namedWindow("Son_resim", cv2.WINDOW_NORMAL) cv2.imshow("Son_resim", yeni_goruntu) return yeni_goruntu def plakaIyilestir(yeni_goruntu): # Daha fazla işlem için numara plakasını geliştirmek için histogram eşitleme y, cr, cb = cv2.split(cv2.cvtColor(yeni_goruntu, cv2.COLOR_RGB2YCrCb)) # Görüntüyü YCrCb modeline dönüştürme ve 3 kanalı bölme y = cv2.equalizeHist(y) # Histogram eşitleme uygulama son_resim = cv2.cvtColor(cv2.merge([y, cr, cb]), cv2.COLOR_YCrCb2RGB) # 3 kanalı birleştirme # cv2.namedWindow("Gelismis_plaka_no", cv2.WINDOW_NORMAL) # cv2.imshow("Gelismis_plaka_no", son_resim) return son_resim #camera.py kodlari def camera(): import numpy as np import cv2 cap = cv2.VideoCapture(0) # harici bir kamerada i=0 yerine i=1,2,3..vs kullanabiliriz while (True): # Çerçeveler halinde görüntü yakalar ret, frame = cap.read() # Üzerinde işlem yapacağımız çerçeve buraya gelsin gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) ##Gürültü Temizleme islemi noise_removal = cv2.bilateralFilter(gray, 9, 75, 75) # Daha iyi sonuç elde etmek için histogram eşitleme yapıldı equal_histogram = cv2.equalizeHist(noise_removal) # Dikdörtgen yapı elemanı ile morfolojik açılım kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)) morph_image = cv2.morphologyEx(equal_histogram, cv2.MORPH_OPEN, kernel, iterations=15) # Görüntü çıkarma (Morph görüntüsünü histogram eşitlenmiş görüntüsünden çıkarmak) sub_morp_image = cv2.subtract(equal_histogram, morph_image) # Görüntüyü eşikleme ret, thresh_image = cv2.threshold(sub_morp_image, 0, 255, cv2.THRESH_OTSU) # Canny Edge algılama uygulanması canny_image = cv2.Canny(thresh_image, 250, 255) # Display Image canny_image = cv2.convertScaleAbs(canny_image) # Kenarları güçlendirmek için genleşme kernel = np.ones((3, 3), np.uint8) # Genişletme için çekirdek oluşturma dilated_image = cv2.dilate(canny_image, kernel, iterations=1) # Sonuç Çerçeveyi Görüntüleme: cv2.imshow('Son_Hal', dilated_image) if cv2.waitKey(1) & 0xFF == ord('q'): # q ile çıkış yapabilirsiniz break cap.release() cv2.destroyAllWindows() #classifications.txt metin dosyası içeriği 9.000000000000000000e+01 8.400000000000000000e+01 8.200000000000000000e+01 8.000000000000000000e+01 7.700000000000000000e+01 7.000000000000000000e+01 6.900000000000000000e+01 6.800000000000000000e+01 6.600000000000000000e+01 6.500000000000000000e+01 8.900000000000000000e+01 8.800000000000000000e+01 8.700000000000000000e+01 8.600000000000000000e+01 8.500000000000000000e+01 8.300000000000000000e+01 8.100000000000000000e+01 7.900000000000000000e+01 7.800000000000000000e+01 7.600000000000000000e+01 7.500000000000000000e+01 7.400000000000000000e+01 7.300000000000000000e+01 7.200000000000000000e+01 7.100000000000000000e+01 6.700000000000000000e+01 5.700000000000000000e+01 5.600000000000000000e+01 5.500000000000000000e+01 5.400000000000000000e+01 5.300000000000000000e+01 5.100000000000000000e+01 5.000000000000000000e+01 4.800000000000000000e+01 5.200000000000000000e+01 4.900000000000000000e+01 8.200000000000000000e+01 8.000000000000000000e+01 7.700000000000000000e+01 6.800000000000000000e+01 6.600000000000000000e+01 6.500000000000000000e+01 9.000000000000000000e+01 8.900000000000000000e+01 8.800000000000000000e+01 8.700000000000000000e+01 8.600000000000000000e+01 8.500000000000000000e+01 8.400000000000000000e+01 8.300000000000000000e+01 8.100000000000000000e+01 7.900000000000000000e+01 7.800000000000000000e+01 7.600000000000000000e+01 7.500000000000000000e+01 7.400000000000000000e+01 7.300000000000000000e+01 7.200000000000000000e+01 7.100000000000000000e+01 7.000000000000000000e+01 6.900000000000000000e+01 6.700000000000000000e+01 5.200000000000000000e+01 4.900000000000000000e+01 5.700000000000000000e+01 5.600000000000000000e+01 5.500000000000000000e+01 5.400000000000000000e+01 5.300000000000000000e+01 5.100000000000000000e+01 5.000000000000000000e+01 4.800000000000000000e+01 9.000000000000000000e+01 8.900000000000000000e+01 8.800000000000000000e+01 8.700000000000000000e+01 8.600000000000000000e+01 8.500000000000000000e+01 8.400000000000000000e+01 8.300000000000000000e+01 8.200000000000000000e+01 8.100000000000000000e+01 8.000000000000000000e+01 7.900000000000000000e+01 7.800000000000000000e+01 7.700000000000000000e+01 7.600000000000000000e+01 7.500000000000000000e+01 7.400000000000000000e+01 7.300000000000000000e+01 7.200000000000000000e+01 7.100000000000000000e+01 7.000000000000000000e+01 6.900000000000000000e+01 6.800000000000000000e+01 6.700000000000000000e+01 6.600000000000000000e+01 6.500000000000000000e+01 4.900000000000000000e+01 5.700000000000000000e+01 5.600000000000000000e+01 5.500000000000000000e+01 5.400000000000000000e+01 5.300000000000000000e+01 5.200000000000000000e+01 5.100000000000000000e+01 5.000000000000000000e+01 4.800000000000000000e+01 9.000000000000000000e+01 8.900000000000000000e+01 8.800000000000000000e+01 8.700000000000000000e+01 8.600000000000000000e+01 8.500000000000000000e+01 8.400000000000000000e+01 8.200000000000000000e+01 8.000000000000000000e+01 7.800000000000000000e+01 7.700000000000000000e+01 7.600000000000000000e+01 7.500000000000000000e+01 7.400000000000000000e+01 7.300000000000000000e+01 7.200000000000000000e+01 7.000000000000000000e+01 6.900000000000000000e+01 6.800000000000000000e+01 6.600000000000000000e+01 6.500000000000000000e+01 8.300000000000000000e+01 8.100000000000000000e+01 7.900000000000000000e+01 7.100000000000000000e+01 6.700000000000000000e+01 5.500000000000000000e+01 5.100000000000000000e+01 5.000000000000000000e+01 4.900000000000000000e+01 5.700000000000000000e+01 5.600000000000000000e+01 5.400000000000000000e+01 5.300000000000000000e+01 5.200000000000000000e+01 4.800000000000000000e+01 8.200000000000000000e+01 8.000000000000000000e+01 7.700000000000000000e+01 6.800000000000000000e+01 6.600000000000000000e+01 6.500000000000000000e+01 9.000000000000000000e+01 8.900000000000000000e+01 8.800000000000000000e+01 8.700000000000000000e+01 8.600000000000000000e+01 8.500000000000000000e+01 8.400000000000000000e+01 8.300000000000000000e+01 8.100000000000000000e+01 7.900000000000000000e+01 7.800000000000000000e+01 7.600000000000000000e+01 7.500000000000000000e+01 7.400000000000000000e+01 7.300000000000000000e+01 7.200000000000000000e+01 7.100000000000000000e+01 7.000000000000000000e+01 6.900000000000000000e+01 6.700000000000000000e+01 5.500000000000000000e+01 5.300000000000000000e+01 5.200000000000000000e+01 5.700000000000000000e+01 5.600000000000000000e+01 5.400000000000000000e+01 5.100000000000000000e+01 5.000000000000000000e+01 4.900000000000000000e+01 4.800000000000000000e+01 bu kod satirini giris.py kod satiri ile çalıştırıyorum ardından terminalde Resimden plaka tanıma işlemi yapmak için 1'e Kamera'dan plaka tanıma işlemi yapmak için 2'ye Seçenekleri görüyor burada iki tür problem yaşıyorum birinci 1’ bastığımdan resim adini girdikten sonra “[ WARN:0@52.245] global loadsave.cpp:248 cv::findDecoder imread_('Resim/b'): can't open/read file: check file path/integrity Lütfen Resim adını kontrol ediniz...” hatasını alıyorum bunun sebebi ve çözümü nedir. 2. aldığım hata 2’ye bastığımda kamera açılıyor fakat kamera bir daha kapanmıyor ve sürekli açık kalıyor