[英]Call cv::VideoCapture constructor conditionally
I want to call the cv::VideoCapture
constructor conditionally. 我想有条件地调用
cv::VideoCapture
构造函数。 If argc == 2
, then the user has specified a video file and I want to load that. 如果
argc == 2
,那么用户已经指定了一个视频文件,我想加载它。 Otherwise use the default camera. 否则,请使用默认相机。
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
int main(int argc, char* argv[])
{
VideoCapture cap(argc == 2 ? argv[1] : 0);
return 0;
}
I compile and run it 我编译并运行它
$ g++ -g -Wall -o main main.cpp `pkg-config opencv --cflags --libs`
$ ./main
But sadly it doesn't seem to work and I get 但是可悲的是它似乎没有用,我明白了
OpenCV: Couldn't read movie file ""
The ternary operator returns a string in one case and an integer in another. 三元运算符在一种情况下返回字符串,在另一种情况下返回整数。 I reckon this won't work because of some idiosyncrasy of C++ constructors I'm not aware of.
我认为这是行不通的,因为我不了解C ++构造函数的某些特质。
What's the cleanest way to do what I want? 做我想做的最干净的方法是什么? Can I do it without using
new
so that I don't have to free memory myself at the end of the program? 我可以在不使用
new
这样做吗,这样我就不必在程序结束时释放内存了吗?
You're over-complicating this. 您太复杂了。 Use
open
: 使用
open
:
VideoCapture cap;
if(argc == 2) {
cap.open(argv[1]); // calls: open(const String& filename)
} else {
cap.open(0); // calls: open(int index)
}
In the ternary operator the two operands must be of the same type . 在三元运算符中,两个操作数必须具有相同的类型 。 See here for details.
有关详细信息,请参见此处 。 But yours have type
int
and char*
, so, even of the code may compile, it can result in runtime errors. 但是您的类型为
int
和char*
,因此,即使代码可以编译,也可能导致运行时错误。
Expression A ? B : C
表达式
A ? B : C
A ? B : C
has a return type of B
and C
must be implicitly convertible to B
. A ? B : C
的返回类型为B
并且C
必须隐式转换为B
Some compilers will not compile (best behavior), some will. 有些编译器将不编译(最佳行为),有些编译器将不编译。 In your case,
B = char *
and C = int
. 在您的情况下,
B = char *
和C = int
。 I believe 0
is interpreted as pointer to address 0 or NULL
whose byte equal '\\0'
ie null-termination character that marks the end of a C-style string hence the empty string. 我相信
0
被解释为指向地址0或NULL
的指针,其字节等于'\\0'
即以空终止符表示C样式字符串的结尾,因此为空字符串。
If you insist on a one-liner, then: 如果您坚持采用单线运输,则:
std::unique_ptr<VideoCapture> capture = (argc == 2 ? std::make_unique<VideoCapture>(argv[1]) : std::make_unique<VideoCapture>(0));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.