How to shift a 20x20 image to a 28x28 image?

Viewed 30

I have to write a Python script that takes an image, downscales it to 20x20, normalizes it and calculates te center of mass of the image. I then have to shift the 20x20 image such that the CoM of the 20x20 image aligns w2ith the CoM of the 28x28 image. So far, I've scaled the image, normalized it, and calculated its center of mass. I'm struggling with understanding what I can do to shift the image into a 28x28 image while also aligning the CoMs. Is there any way I could do it using OpenCV? I'm using ndi for calculating the CoM.

Here's what I have so far:

import glob
from mimetypes import init  
from skimage import io
import os
from PIL import Image
import cv2 as cv

import numpy as np
import scipy.ndimage as ndi
import sys
import pandas as pd
import csv

#Get path of current directory
path = os.path.dirname(os.path.abspath(__file__))
#To access all files in that directory
path = path + "\*"
#print(path)


file_list = glob.glob(path)


#print(file_list)
#rescale img to 20x20
#normalize valuesfrom 0 to 255
#compute CoM
#change img into 28x28 img
#output as a csv

flat_list = []
for file in file_list:
    name, ext = os.path.splitext(file)
    #If file is in png / pgm format
    if ext == '.pgm' or ext == '.png':
        return_arr = []

        number = name[-1]
        #to store number from filename

        new_size = (20,20)
        img = cv.imread(file)
            
        img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
        print("Img shape b4 resizing: ",img.shape)

        #resizing TO 20 X 20 img
        res = cv.resize(img, new_size, interpolation=cv.INTER_NEAREST)
        print("Img shape after resizing: ",res.shape)

        #Normalization
        print("Res: ",res)
        norm = np.zeros((20,20))
        normalized_img = cv.normalize(res, norm, 0,255,cv.NORM_MINMAX)
        print("Norm: ",normalized_img)
        #Compute CoM 
        centermass = ndi.center_of_mass(res)
        print("CM: ",centermass)

        #resizing to 28x28 img
        size_28 = (28,28)
        img_28 = cv.resize(res, size_28, interpolation=cv.INTER_CUBIC)
        img_28 = img_28.ravel()
        centermass_28 = ndi.center_of_mass(img_28)
        print("centermass_28: ",centermass_28)
        

        #add number from filename (actual digit) and then the image array to list.
        img_28 = img_28.tolist()
        init_arr = []
        return_arr.append(number)
        return_arr.append(img_28)
        
        #Flatten array of the image
        for sublist in return_arr:
            for num in sublist:
                init_arr.append(int(num))
        
        #append that image's array to flat_list
        flat_list.append(init_arr)

#Insert the list of lists into a csv file, row major order.
with open("output.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(flat_list)
0 Answers
Related