Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to read images from my home directory and resize it

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'
like image 210
marton mar suri Avatar asked Dec 02 '25 13:12

marton mar suri


1 Answers

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

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.

like image 119
kocica Avatar answered Dec 04 '25 03:12

kocica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!