如何从我的主目录读取图像并调整其大小 [英] how to read images from my home directory and resize it

查看:93
本文介绍了如何从我的主目录读取图像并调整其大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试读取图像并调整主目录文件中的图像大小,但是没有用,请帮助您如何读取图像并调整大小.

I am trying to read the images and resize the image in my home directory file but didn't work please help how to read images and resize it.

    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'

推荐答案

要读取特定扩展名的所有图片,例如"* .png",可以使用cv::glob功能

To read all images of particular extension, e.g. "*.png", one can use cv::glob function

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);

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

And then resize each image in buffer

for (auto& it : imgs)
{
    cv::resize(it, it, cv::Size{WIDTH, HEIGHT});
}

应该很容易将其重写为python,因为几乎所有函数/数据类型在python中都具有等效功能.

It should be easy to rewrite to python since almost all functions / data types have equivalents in python.

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

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

代码被分成几部分,而不是单行代码,因为至少对于我来说,它更具可读性.

The code is divided to parts instead of one-liner because it is more readable, at least for me.

这篇关于如何从我的主目录读取图像并调整其大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆