TAGS :Viewed: 2 - Published at: a few seconds ago

[ image scaling in loop using python OpenCV ]

I am new to Python and I am having a really hard time figuring out how to transform what I got here into a loop. As you can see here I am doing a basic image scaling to 3 different images (from mask_0001.png to mask_0003.png), but I will have more than 100 to go later on, so I will have to do it in a loop I guess. (from 0004.png to 0150.png )

Here is the code I just wrote:

import cv2
import numpy as np

img = cv2.imread("C://Users//user//Desktop//research//images//Mask//set1//set1_mask_0001.png")
res = cv2.resize(img,None,fx=0.5, fy=0.5, interpolation = cv2.INTER_CUBIC)
cv2.imwrite('0.25_mask_set1_0001.png', res)


img = cv2.imread("C://Users//user//Desktop//research//images//Mask//set1//set1_mask_0002.png")
res = cv2.resize(img,None,fx=0.5, fy=0.5, interpolation = cv2.INTER_CUBIC)
cv2.imwrite('0.25_mask_set1_0002.png', res)


img = cv2.imread("C://Users//user//Desktop//research//images//Mask//set1//set1_mask_0003.png")
res = cv2.resize(img,None,fx=0.5, fy=0.5, interpolation = cv2.INTER_CUBIC)
cv2.imwrite('0.25_mask_set1_0003.png', res) 

Thanks!

Answer 1


This loops i from 1 to 150, setting the mask to i.

Python 2

for i in range(1,151):
    img = cv2.imread("C://Users//user//Desktop//research//images//Mask//set1//set1_mask_" + str(i).zfill(4) +".png")
    res = cv2.resize(img,None,fx=0.5, fy=0.5, interpolation = cv2.INTER_CUBIC)
    cv2.imwrite('0.25_mask_set1_' + str(i).zfill(4) + '.png', res)

Python 3

Instead of using str(i).zfill(4), try format(i, '04d')

You should verify the behaviour, particularly with my use of i in cv2.imwrite to make sure it works with your problem