def test_one(image):
    FOLDER_NAME = "-KNN Approach-"
    test = Extractor.ImageToMatrix(image)

    Hop.go_to_approach("/" + FOLDER_NAME)

    best_score = 100
    optimal_number = -1

    grayscale = Extractor.ImageToMatrix(image)
    r = np.zeros((grayscale.shape[0], grayscale.shape[1]), dtype=int)

    lr = KNN_Trainer.read_image(grayscale)
    lean = KNN_Trainer.record_left_right(lr)
    segments = KNN_Trainer.record_segment(lr)
    outside = KNN_Trainer.inside_outside(lr, grayscale)

    neighbors = open("save.txt")

    for line in neighbors:
        match = "line ([0-9]*): lean\(([0-9].[0-9]*)\) segment\(([0-9].[0-9]*)\) outside\(([0-9].[0-9]*)\) class\(([0-9])\)"
        string = re.match(match, line)
        train_line, train_lean, train_segments, train_outside, train_number = string.group(
            1), string.group(2), string.group(3), string.group(
                4), string.group(5)
        score = abs(lean - float(train_lean)) + abs(segments -
                                                    float(train_segments))
        if score < best_score:
            best_score = score
            optimal_number = train_number
    return optimal_number
def test(answer_array, index, filename):
    NN = 3
    count = 0

    STOP = 100

    test_image = Extractor.getImage(filename)
    test_image = Manipulate_Image.crop_image(test_image)
    test = Extractor.ImageToMatrix(test_image)
    os.chdir('..')
    os.chdir(os.getcwd() + "/" + "train_images_sorted" + "/")

    scores = {
        0: [],
        1: [],
        2: [],
        3: [],
        4: [],
        5: [],
        6: [],
        7: [],
        8: [],
        9: []
    }
    for x in range(10):
        os.chdir(os.getcwd() + "/" + str(x) + "/")
        for filename in os.listdir(os.getcwd()):
            if count == STOP: break
            trained_image = Extractor.getImage(filename)
            trained_image = Manipulate_Image.crop_image(trained_image)
            trained_image = ImageOps.fit(trained_image,
                                         (len(test[0]), len(test)),
                                         Image.ANTIALIAS)
            trained = Extractor.ImageToMatrix(trained_image)
            scores = add_score(scores, x, matching_score(test, trained), NN)
            #print("done a file")
            count += 1
        count = 0
        os.chdir('..')

    # print(scores)
    os.chdir('..')
    os.chdir(os.getcwd() + "/test_images/")

    guess = predict(scores)
    #print("Actual: "+str(answer_array[index])+" Best: "+str(guess))
    if answer_array[index] == guess:
        return 1
    return 0
Пример #3
0
def darken(img):
    
    matrix = Extractor.ImageToMatrix(img)
    #print(matrix)
    #print("===========================")
    matrix.setflags(write=1)
    darkest = 255
    for row in range(len(matrix)):
        for col in range(len(matrix[row])):
            if matrix[row][col] < darkest:
                darkest = matrix[row][col]
    # enhace the image
    constant = 255//darkest
    for row in range(len(matrix)):
        for col in range(len(matrix[row])):
            if matrix[row][col]!=255:
                # Linear Fit                
                matrix[row][col] = 255 - matrix[row][col] * constant
                
                # root Fit
                #a,b = root_fit(darkest)[0], root_fit(darkest)[1]
                #matrix[row][col] = int(math.sqrt((matrix[row][col] + b)/ a))
    #print(matrix)            
    new_img = Image.fromarray(matrix.astype(np.uint8))
    new_img.save("enhanced.tif") 
    return new_img
Пример #4
0
def train_images():
    FOLDER_NAME = "/-Averaged Approach-"

    os.chdir('..')
    root = os.getcwd()
    try:
        new_dir = root + FOLDER_NAME + "/trained_digits/"
        os.makedirs(new_dir)
        for x in range(10):
            os.chdir(root + "/train_images_sorted/" + str(x))
            i = 0
            total = []
            for filename in os.listdir(os.getcwd()):
                i += 1
                image = Extractor.getImage(filename)
                matrix = Extractor.ImageToMatrix(image)
                data = black_percentage(matrix)
                if len(total) == len(data):
                    total = add_grayscale(data, total)
                else:
                    total = data
            array = average_percentage(total, i)
            print("Digit " + str(x) + " is complete")

            os.chdir(new_dir)
            img = Image.fromarray(array.astype(np.uint8))
            img.save(str(x) + ".tif")
    except Exception as e:
        print("trained_digits directory already exists")
def crop_image(image):
    matrix = Extractor.ImageToMatrix(image)
    # print(matrix)
    top,bottom,left,right = get_image_bounds(matrix)
    # print(get_image_bounds(matrix))
    img = image.crop((left, top, right + 1, bottom + 1))
       
    return img  
def test_one(img):
    FOLDER_NAME = "-Averaged Approach-"
    test = Extractor.ImageToMatrix(img)
    os.chdir('..')
    os.chdir(os.getcwd() + "/" + FOLDER_NAME + "/")
    os.chdir(os.getcwd() + "/trained_digits/")
    scores = []
    for x in range(10):
        trained_filename = str(x) + ".tif"

        trained_image = Extractor.getImage(trained_filename)
        trained = Extractor.ImageToMatrix(trained_image)

        scores.append(matching_score(test, trained))

    guess = scores.index(min(scores))
    confidence = (1 - min(scores) / (255 * 28 * 28)) * 100
    os.chdir('..')
    os.chdir('..')
    return guess
def load_image(network, s):
    """
    Generates a random number between 1 and 60000 and set's the network's input
    """
    img_num = random.randint(1, 60000)
    num_zeros = 5 - len(str(img_num))
    zeros = '0' * num_zeros
    filename = zeros + str(img_num) + ".tif"
    #img_num = 11534
    #filename = str(img_num)+".tif"

    #print(filename)
    image = Extractor.getImage(filename)
    matrix = Extractor.ImageToMatrix(image)
    data = np.asarray(matrix).flatten()
    """
    count = 0
    for item in data:
        if count>=28:
            count = 0
            print()
        print(str(item)+(3-len(str(item)))*" "+" ",end="")
        count+=1
    print()
    print()
    """
    data = scale_data(data)
    #print()
    """
    count = 0
    for item in data:
        if count>=28:
            count = 0
            print()
        print(str(round(item,1))+(3-len(str(item)))*" "+" ",end="")
        count+=1
    print()
    print()
    """
    #exit()

    network.set_inputs(data)
    return (network, img_num)
        pickle.dump((network, batches), open("network.p", "wb"))

    if test:
        correct = 0
        total = 0
        percent = 0
        os.chdir('..')
        answer_array = []
        answers = open("mnist-test-labels.txt", "r")
        index = 0
        for line in answers:
            answer_array.append(int(line.strip()))
        os.chdir(os.getcwd() + '/test_images')
        for filename in os.listdir(os.getcwd()):
            image = Extractor.getImage(filename)
            matrix = Extractor.ImageToMatrix(image)
            data = np.asarray(matrix).flatten()
            data = scale_data(data)
            #print(answer_array[total])
            if run_test(network, data) == answer_array[total]:
                correct += 1
            total += 1
            if total % ((10000) / 100) == 0:
                percent += 1
                print(str(percent) + "%")

            #network.show(2,2)
            if total == stop_at:
                break
        print(str(correct) + "/" + str(total))