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'
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With