how to read images from my home directory and resize it

馋奶兔 提交于 2020-02-03 10:14:49

问题


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'

回答1:


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.




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/53849669/how-to-read-images-from-my-home-directory-and-resize-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!