如何从主目录中读取图像并调整大小

2024-10-03 06:20:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图读取图像和调整我的主目录文件中的图像,但没有工作请帮助如何读取图像和调整大小。在

    import cv2
    from PIL import Image
    img = cv2.resize(cv2.read('C://Users//NanduCn//jupter1//train-scene classification//train"', (28, 28)))


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-103-dab0f11a9e2d> in <module>()
      1 import cv2
      2 from PIL import Image
----> 3 img = cv2.resize(cv2.read('C://Users//NanduCn//jupter1//train-scene classification//train"', (28, 28)))

AttributeError: module 'cv2.cv2' has no attribute 'read'

Tags: from图像imageimportimgreadpiltrain
3条回答

使用glob的模块:

dpath = "C:/your_path/"
fmt = "png"    
size = (28, 28)

imgs = [cv2.resize(cv2.imread(fpath), size) for fpath in glob.glob("{}/*.{}".format(dpath, fmt))]

这里的错误是您给cv2.imread一个目录,但它只接受图像路径作为输入,否则会抛出错误。在

所以我们可以做的就是使用操作系统模块解析文件夹中的所有文件,然后逐个读取图像,然后调整大小并对其执行其他操作。在

import os
import cv2
from PIL import Image
size = (28, 28)
imagesPath = "C://Users//NanduCn//jupter1//train-scene classification//train"

for imageName in os.listdir(imagesPath):

    imageFullPath = os.path.join(imagesPath,imageName)
    img = cv2.resize(cv2.imread(imageFullPath), size)
    #do your processing here

另外,我认为你在这个文件夹里只有图像。如果里面有其他类型的文件或其他文件夹,可以在os.path.join操作系统行。在

希望这有帮助。在

要读取特定扩展名的所有图像,例如“*.png”,可以使用cv::glob函数

void loadImages(const std::string& ext, const std::string& path, std::vector<cv::Mat>& imgs, const int& mode)
{
    std::vector<cv::String> strBuffer;
    cv::glob(cv::String{path} + cv::String{"/*."} + cv::String{ext}, strBuffer, false);

    for (auto& it : strBuffer)
    {
        imgs.push_back(cv::imread(it, mode));
    }
}

std::vector<cv::Mat> imgs;
loadImages("*.png", "/home/img", imgs, cv::IMREAD_COLOR);

然后调整缓冲区中每个图像的大小

^{pr2}$

重写为python应该很容易,因为几乎所有函数/数据类型在python中都有等价的。在

filenames = glob("/home/img/*.png").sort()
images = [cv2.imread(img) for img in filenames]

for img in images:
    cv2.resize(img, (WIDTH, HEIGHT))

代码被分为多个部分,而不是一个行程序,因为它更具可读性,至少对我来说是这样。在

相关问题 更多 >