how to read images from my home directory and resize it

Viewed 593

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'
3 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.

Using glob module:

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

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

the error here is that you are giving a directory to cv2.imread but it only accepts image-path as input else it throws the error.

so we can do is parse all the files in a folder using os module and then read the images one by one and than resize and do other operations on them.

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

also i here consider that you only have images in that folder. if you have other types of files or other folders inside it you can put a check before the os.path.join line.

Hope this helps.

Related