gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:16:47 24 4
gpt4 key购买 nike

我是 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 以确保它能解决你的问题

关于python - 使用 python OpenCV 在循环中缩放图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37821769/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com