[Python] How to resize image to 20x20 and flatten it into a single row with 400 pixels

Discussão em 'Python' iniciado por Stack, Janeiro 21, 2025.

  1. Stack

    Stack Membro Participativo

    I'm working on a project to read a handwritten digit from an image by OCR. I used this OpenCV source to try if it works: https://docs.opencv.org/4.x/d8/d4b/tutorial_py_knn_opencv.html.

    The code from the documentation worked so far:

    import numpy as np
    import cv2 as cv

    img = cv.imread('digits.png')
    gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)

    # Now we split the image to 5000 cells, each 20x20 size
    cells = [np.hsplit(row,100) for row in np.vsplit(gray,50)]

    ...

    # Now we check the accuracy of classification
    # For that, compare the result with test_labels and check which are wrong
    matches = result==test_labels
    correct = np.count_nonzero(matches)
    accuracy = correct*100.0/result.size
    print( accuracy )


    In the documentation the text says: "Each digit is a 20x20 image. So our first step is to split this image into 5000 different digit images. Then for each digit (20x20 image), we flatten it into a single row with 400 pixels."

    Now I'm trying to run this code in order to resize/rescale my images to fit into the trained model to predict which handwritten number is on each image. The reason is that my images have sizes of 70x51, 63x48 or 69x49. It variates for each image.

    So this is what I got so far:

    img_resized = cv.resize(img, (20, 20), interpolation=cv.INTER_AREA)
    img_flatten = img_resized.reshape(-1, 400).astype(np.float32)

    with np.load(knn_data_path) as data:
    train = data['train']
    train_labels = data['train_labels']

    knn = cv.ml.KNearest_create()
    knn.train(train, cv.ml.ROW_SAMPLE, train_labels)

    ret, result, neighbours, dist = knn.findNearest(img_flatten, k=5)

    return int(result[0][0])


    But I can't resize it because in the end I get this output [​IMG] Something is not working correctly. How can I resize my images in order to run the knn? Please help!

    Continue reading...

Compartilhe esta Página