使用python OpenCV在循环中进行图像缩放

使用python OpenCV在循环中进行图像缩放,python,loops,opencv,io,path,Python,Loops,Opencv,Io,Path,我是Python新手,我很难弄清楚如何将我在这里得到的东西转换成循环。正如你在这里看到的,我正在做一个基本的图像缩放到3个不同的图像(从mask_0001.png到mask_0003.png),但是我以后会有100多个图像,所以我想我必须在一个循环中完成。(从0004.png到0150.png) 以下是我刚刚编写的代码: import cv2 import numpy as np img = cv2.imread("C://Users//user//Desktop//research//ima

我是Python新手,我很难弄清楚如何将我在这里得到的东西转换成循环。正如你在这里看到的,我正在做一个基本的图像缩放到3个不同的图像(从mask_0001.png到mask_0003.png),但是我以后会有100多个图像,所以我想我必须在一个循环中完成。(从0004.png到0150.png)

以下是我刚刚编写的代码:

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) 

谢谢

这将
i
从1循环到150,将掩码设置为
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

不要使用
str(i).zfill(4)
,请尝试
format(i,'04d')


您应该验证该行为,特别是我在
cv2.imwrite中使用
i
时,以确保它能解决您的问题

这会将
i
从1循环到150,将掩码设置为
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

不要使用
str(i).zfill(4)
,请尝试
format(i,'04d')


您应该验证行为,尤其是我在
cv2.imwrite中使用
i
时,以确保它能解决您的问题

谢谢!但我有一个问题:根据你的代码,第十幅图像将是00010.png,然而,正确的路径应该是0010。不知道它是否还能用,谢谢!但我有一个问题:根据你的代码,第十幅图像将是00010.png,然而,正确的路径应该是0010。不确定它是否仍然有效。