opencv imread图片为空很可能是换行符的原因

写了个程序需要先读出图片的宽度和高度,刚开始发现读出的长宽死活都是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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值