如何调整文件夹中的多张图像,将它们转换为灰度并将它们保存到另一个文件夹中?
How to resize multiple images from a folder, convert them into grayscale and save them into another folder?
我在 Python 中编写了一些代码,用于从文件夹调整图像大小并将其转换为灰度图像,并希望将它们保存在另一个文件夹中。当我编译代码时,它没有显示输出也没有给出错误。我正在分享到目前为止我编写的全部代码,以便找到我的错误。这是我的第一个问题。
from PIL import Image # to load images
from IPython.display import display # to display images
import cv2
import os
import glob
import numpy as np
img_path = r"C:\Users\usama\Documents\FYP-Data\FYP Project Data\hamza\h1.png"
im= Image.open(img_path)
print('{}'.format(im.format))
print('Size: {}'.format(im.size))
print('image mode:{}'.format(im.mode))
im.show()
img_list = []
resized_list = []
for filename in glob.glob(r'C:\Users\usama\Documents\FYP-Data\FYP Project Data\hamza\*.png'):
print(filename)
img=Image.open(filename)
img_list.append(img)
img_list=img_list[:2000]
for image in resized_list:
if image not in resized_list:
resized_list.append(img)
resized_list=(resized_list[:2000])
img=image.resize((500,500))
rl=cv2.imread('resized_list')
gray_image = cv2.cvtColor(rl, cv2.COLOR_BGR2GRAY)
cv2.imwrite('resized images *.png', gray_image)
尝试以下操作:
import cv2
import glob
for filename in glob.glob(r'your\path\*.png'):
print(filename)
img=cv2.imread(filename)
rl=cv2.resize(img, (500,500))
gray_image = cv2.cvtColor(rl, cv2.COLOR_BGR2GRAY)
cv2.imwrite(f'{filename}.resized.png', gray_image)
我在 Python 中编写了一些代码,用于从文件夹调整图像大小并将其转换为灰度图像,并希望将它们保存在另一个文件夹中。当我编译代码时,它没有显示输出也没有给出错误。我正在分享到目前为止我编写的全部代码,以便找到我的错误。这是我的第一个问题。
from PIL import Image # to load images
from IPython.display import display # to display images
import cv2
import os
import glob
import numpy as np
img_path = r"C:\Users\usama\Documents\FYP-Data\FYP Project Data\hamza\h1.png"
im= Image.open(img_path)
print('{}'.format(im.format))
print('Size: {}'.format(im.size))
print('image mode:{}'.format(im.mode))
im.show()
img_list = []
resized_list = []
for filename in glob.glob(r'C:\Users\usama\Documents\FYP-Data\FYP Project Data\hamza\*.png'):
print(filename)
img=Image.open(filename)
img_list.append(img)
img_list=img_list[:2000]
for image in resized_list:
if image not in resized_list:
resized_list.append(img)
resized_list=(resized_list[:2000])
img=image.resize((500,500))
rl=cv2.imread('resized_list')
gray_image = cv2.cvtColor(rl, cv2.COLOR_BGR2GRAY)
cv2.imwrite('resized images *.png', gray_image)
尝试以下操作:
import cv2
import glob
for filename in glob.glob(r'your\path\*.png'):
print(filename)
img=cv2.imread(filename)
rl=cv2.resize(img, (500,500))
gray_image = cv2.cvtColor(rl, cv2.COLOR_BGR2GRAY)
cv2.imwrite(f'{filename}.resized.png', gray_image)