我有一个叫BasePoint的类
BasePoint
{
public:
BasePoint();
//BasePoint(const BasePoint& bp);
uint id;
float avgVal;
float varVal;
float avgLas;
float varLas;
cv::Mat invariants;// Type : 32FC1
int status;
};并拥有这类的两个对象:
BasePoint previousBasePoint;
BasePoint currentBasePoint;在我执行的每一次迭代中
const float norm_factor = 1.0;
currentBasePoint.invariants = totalInvariants / norm_factor; // Problem is here
currentBasePoint.id = image_counter;
if(previousBasePoint.id == 0)
{
previousBasePoint = currentBasePoint;
currentPlace->members.push_back(currentBasePoint);
wholebasepoints.push_back(currentBasePoint);
}
else
{
//some code here
}代码的问题是,当我执行totalInvariants / norm_factor;而不是使用totalInvariants时,previousBasePoint与currentBasePoint一样。但是,如果我不把它分开的话,一切都很好。这里有什么问题吗?
编辑:
const float norm_factor = 1.0;
currentBasePoint.invariants = totalInvariants;
currentBasePoint.invariants = currenBasePoint.invariants / norm_factor也能用,但我还是想知道这个部门有什么问题
发布于 2017-08-13 14:40:35
我通过重载=操作符解决了这个问题。
class A{
public:
cv::Mat matrix;
A(){
this->matrix = cv::Mat();
}
A(const A& otherA){
std::cout << "Copy Called" << std::endl;
this->matrix = otherA.matrix.clone();
}
void operator = (const A& otherA){
std::cout << "Operator overlad called" << std::endl;
this->matrix = otherA.matrix.clone();
}
};
int main()
{
A a1,a2;
cv::Mat anotherMat = cv::Mat::ones(3,3,CV_32FC1);
a1.matrix = cv::Mat::zeros(3,3,CV_32FC1);
// a2 = a1;
a2 = a1;
std::cout << a2.matrix << std::endl;
a1.matrix = anotherMat / 5; // Division, type MatExpr
std::cout << a2.matrix << std::endl;
return 0;
}没有运算符overloading1的输出
[0, 0, 0; [0.2, 0.2, 0.2;
0, 0, 0; 0.2, 0.2, 0.2;
0, 0, 0] 0.2, 0.2, 0.2]带有操作符overloading2的输出
[0, 0, 0; [0, 0, 0;
0, 0, 0; 0, 0, 0;
0, 0, 0] 0, 0, 0]无division3输出
[0, 0, 0; [0, 0, 0;
0, 0, 0; 0, 0, 0;
0, 0, 0] 0, 0, 0]在OpenCV文档中:
C++:Mat& Mat::operator=(康斯特·马特& m) C++:Mat& Mat::operator=(const & expr) M-分配,右手边矩阵。矩阵分配是一个O(1)运算。这意味着没有复制数据,但是数据是共享的,引用计数器(如果有的话)会增加。在分配新数据之前,将通过Mat::Before ()取消对旧数据的引用。 扩展分配的矩阵表达式对象。与赋值操作的第一种形式相反,第二种形式可以重用已经分配的矩阵,如果它具有合适的大小和类型以适应矩阵表达式的结果。它由将矩阵表达式扩展到的实函数自动处理。例如,C=A+B被扩展为add(A,B,C),add()负责自动C重新分配。
因此出现了这个问题,因为/操作符返回MatExpr对象,它导致共享数据可以被其他矩阵重用。但是我希望output1和output3也是一样的。
发布于 2017-08-13 05:00:14
您正在cv::Mat上使用cv::Mat选项器,该操作使用浅拷贝操作。所以它们都有相同的内存地址,您需要使用clone()操作的cv::Mat。
此外,您还需要重载BasePoint的操作符,因为previousBasePoint = currentBasePoint;上的默认运算符也会执行内部invariant的浅拷贝。
https://stackoverflow.com/questions/45655974
复制相似问题