Home > OS >  How to change the size in pixels only of those images that do not have a certain width and height of
How to change the size in pixels only of those images that do not have a certain width and height of

Time:12-10

I have a folder called 'p' and within it there are 60 .png images, what I would need is to change the size in pixels only to those images that are not 113 x 222 px

import cv2
import numpy as np
import glob

img_files = glob.glob("p/*.png")

for img_file in img_files:
    if(): #The condition that verify the dimentions
        img = cv2.imread(img_file)
        res = cv2.resize(img, dsize=(113, 222), interpolation=cv2.INTER_CUBIC)

I think that with a for loop I could go through the images inside that directory, but I'm not sure how to do the validation of the size in pixels of those images that must be resized and which ones should not.

It is important that the rest of the images that do have 113 x 222 px do not modify them, and only replace with their resized versions those that did not previously have those dimensions.

CodePudding user response:

Finally I could make this code:

import cv2
import numpy as np
import glob

img_files = glob.glob("imgs/*.png")

for img_file in img_files:
    print(img_file)
    img = cv2.imread(img_file)
    print(img.shape)
    if( img.shape != (222, 113, 3) ):
        print("Esta imagen no coincide con las dimensiones deseadas! La redimensionaré!")
        res = cv2.resize(img, dsize=(113, 222), interpolation=cv2.INTER_CUBIC)
        #cv2.imwrite(img_file, res) #Reemplaza por la nueva imagen ya redimensionada
        print("Imagen: "   str(img_file)   " redimensionada "   "--->"   str(res.shape))
    print("\n-------\n")
  • Related