resizing images from 64x64 to 224x224 for the VGG model

2024/11/9 1:53:45

Can we resize an image from 64x64 to 256x256 without affecting the resolution is that a way to add zero on new row and column in the new resized output I m working on vgg and I get an error while adding my 64x64 input image because vggface is a pertrained model that include an input size of 224

code:

from keras.models import Model, Sequential
from keras.layers import Input, Convolution2D, ZeroPadding2D, MaxPooling2D, Flatten, Dense, Dropout, Activation
from PIL import Image
import numpy as np
from keras.preprocessing.image import load_img, save_img, img_to_array
from keras.applications.imagenet_utils import preprocess_input
from keras.preprocessing import image
import matplotlibmatplotlib.use('TkAgg')import matplotlib.pyplot as plt# from sup5 import X_test, Y_test
from sklearn.metrics import roc_curve, aucfrom keras.models import Model, Sequential
from keras.layers import Input, Convolution2D, ZeroPadding2D, MaxPooling2D, Flatten, Dense, Dropout, Activation
from PIL import Image
import numpy as np
from keras.preprocessing.image import load_img, save_img, img_to_array
from keras.applications.imagenet_utils import preprocess_input
from keras.preprocessing import image
import matplotlib.pyplot as plt# from sup5 import X_test, Y_test
from sklearn.metrics import roc_curve, auc
from keras.applications.vgg16 import VGG16
from keras.preprocessing import image
from keras.applications.vgg16 import preprocess_input
import numpy as npmodel = VGG16(weights='imagenet', include_top=False)from keras.models import model_from_jsonvgg_face_descriptor = Model(inputs=model.layers[0].input, outputs=model.layers[-2].output)
# import  pandas as pd
# test_x_predictions = deep.predict(X_test)
# mse = np.mean(np.power(X_test - test_x_predictions, 2), axis=1)
# error_df = pd.DataFrame({'Reconstruction_error': mse,
#                         'True_class': Y_test})
# error_df.describe()
from PIL import Imagedef preprocess_image(image_path):img = load_img(image_path, target_size=(224, 224))img = img_to_array(img)img = np.expand_dims(img, axis=0)img = preprocess_input(img)return imgdef findCosineSimilarity(source_representation, test_representation):a = np.matmul(np.transpose(source_representation), test_representation)b = np.sum(np.multiply(source_representation, source_representation))c = np.sum(np.multiply(test_representation, test_representation))return 1 - (a / (np.sqrt(b) * np.sqrt(c)))def findEuclideanDistance(source_representation, test_representation):euclidean_distance = source_representation - test_representationeuclidean_distance = np.sum(np.multiply(euclidean_distance, euclidean_distance))euclidean_distance = np.sqrt(euclidean_distance)return euclidean_distancevgg_face_descriptor = Model(inputs=model.layers[0].input, outputs=model.layers[-2].output)# for encod epsilon = 0.004
epsilon = 0.16
# epsilon = 0.095
retFalse,ret_val, euclidean_distance = verifyFace(str(i)+"test.jpg", str(j)+"train.jpg", epsilon)verifyFace1(str(i) + "testencod.jpg", str(j) + "trainencod.jpg")

Error : ValueError: operands could not be broadcast together with remapped shapes [original->remapped]: (512,14,14)->(512,newaxis,newaxis) (14,14,512)->(14,newaxis,newaxis) and requested shape (14,512)

Answer

I'm not sure what you mean, here is my solution for you. First method, if i understand clearly what you mean, for adding pad with zero value you need to use numpy.pad for each layer of image.

I use this image for take example, its shape is 158x84x3

I use this image for take example, its shape is 158x84x3

import numpy as np
import cv2
from matplotlib import pyplot as mlt
image = cv2.imread('zero.png')
shape = image.shape
add_x = int((256-shape[0])/2)
add_y = int((256-shape[1])/2)
temp_img = np.zeros((256,256,3),dtype = int)
for i in range(3):temp_img[:,:,i] = np.pad(image[:,:,i],((add_x,add_x),(add_y,add_y)),'constant', constant_values = (0))
mlt.imshow(temp_img)

By this code i can add padding into picture and have the result like this.

enter image description here

Now its shape is 256x256x3 like you want. Or another method for you is use Image of Pillow library. By using that, you can resize the picture without losing too much information with very simple code.

from PIL import Image
image = Image.fromarray(image)
img = image.resize((256, 256), Image.BILINEAR) 
mlt.imshow(img)

That code will give you this solution

enter image description here

Hope my answer can help you solve the problem!

https://en.xdnf.cn/q/120556.html

Related Q&A

Python slicing explained [duplicate]

This question already has answers here:How slicing in Python works(38 answers)Closed 6 years ago.OK I understand the basics, but can someone explain code copied from Gregs answer here:a[1::-1] # the …

Comparison between string characters within a list [duplicate]

This question already has an answer here:How to compare characters of strings that are elements of a list? [duplicate](1 answer)Closed 2 years ago.Having a Python list, containing same length strings,…

Pyspark filling missing dates by group and filling previous values

Spark version 3.0. I have two dataframes. I create one dataframe with date columns using pandas date range. I have a 2nd spark dataframe contains the company name, dates and value. I want to merge the …

How to loop in the opposite order?

I am a beginner programmer. Here is my code:n = int(input()) from math import* for i in range(n):print(n, "\t", log10(n))i = i + 1n = n - 1Its output is:10 1.0 9 0.9542425094393249 8 …

Override methods with same name in Python programming [duplicate]

This question already has answers here:Closed 12 years ago.Possible Duplicate: How do I use method overloading in Python?I am new to Python programming, and I like to write multiple methods with the …

TypeError: function object is not subscriptable in Python 3.4.3?

I have a food menu and the stock and prices are in separate dictionaries.Food Stock:Food_Stock = {Chips : 15,Bagels : 27,Cookies : 25}#Food Stock.Food Prices:Food_Prices = {#Food Prices.Chips : 1,Bagel…

Insert a value in date format dd-mm-yyyy in dictionary in python

I am creating a dictionary having some values including a date of birth of a person. But when I run my code, it is giving an error "datetime.datetime has no attribute datetime" . Here is my …

Collisions arent registering with Python Turtles

Im creating a simple 2D shooter following an online tutorial, and the enemy sprites (except 1, there are 5 total) are not abiding by my collision code. Everything works except the bullet object that th…

Function should clean data to half the size, instead it enlarges it by an order of magnitude

This has been driving me nuts all week weekend. I am trying merge data for different assets around a common timestamp. Each assets data is a value in dictionary. The data of interest is stored in lists…

is it possible to add colors to python output? [duplicate]

This question already has answers here:How do I print colored text to the terminal?(66 answers)Closed 10 years ago.so i made a small password strength tester for me, my friends and my family, as seen …