我正在尝试读取图像并调整主目录文件中图像的大小,但无法正常工作,请帮助如何读取图像并调整大小。
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
函数
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);
然后调整缓冲区中每个图像的大小
for (auto& it : imgs)
{
cv::resize(it, it, cv::Size{WIDTH, HEIGHT});
}
重写为python应该很容易,因为几乎所有函数/数据类型在python中都具有等效功能。
filenames = glob("/home/img/*.png").sort()
images = [cv2.imread(img) for img in filenames]
for img in images:
cv2.resize(img, (WIDTH, HEIGHT))
该代码分为几部分,而不是单行代码,因为至少对于我来说,它更具可读性。
关于python - 如何从我的主目录读取图像并调整其大小,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53849669/