写了个程序需要先读出图片的宽度和高度,刚开始发现读出的长宽死活都是0。后来考虑是不是因为在文件中读出路径的时候是不是有换行符,所以才导致路径不对imread
的时候是空的,发现果然是这样的。
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <Windows.h>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int rtrim_n_z(char* s)
{
int s_len = strlen(s);
int x = 0;
for (int i = s_len - 1; i >= 0; i--)
{
if (i == s_len - 1 && s[i] == '\n')
{
s[i] = '\0';
break;
}
x = 1;
break;
}
if (x == 0)
rtrim_n_z(s);
return 1;
}
void readFile()
{
FILE *fp;
char str[128];
if ((fp = fopen("tmp.txt", "r")) == NULL) {
printf("cannot open file/n"); exit(1);
}
while (!feof(fp)) {
if (fgets(str, 128, fp) != NULL)
{
rtrim_n_z(str);
printf("%s\n", str);
Mat fileImage = imread(str);
printf("cols = %d, rows = %d\n", fileImage.cols, fileImage.rows);
Sleep(1500);
}
}
fclose(fp);
}
int main()
{
readFile();
system("pause");
return 0;
}
运行结果:
img/1-0001.png
cols = 114, rows = 114
img/1-0002.png
cols = 386, rows = 386
img/1-0003.png
cols = 321, rows = 321
img/1-0004.png
cols = 224, rows = 224
img/1-0005.png
cols = 212, rows = 212
img/1-0006.png
cols = 197, rows = 197