if-else循环不循环c ++ opencv visualstudio

时间:2013-10-12 14:37:10

标签: c++ opencv

我正在寻找创建一个循环,用户必须输入一些数字才能转售图像。如果用户输入限制范围内的内容,但是当他们输入一个代码中断的数字时,重新缩放就会起作用。

#include <opencv2\core\core.hpp>
#include <opencv2\highgui\highgui.hpp>
#include <opencv2\imgproc\imgproc.hpp>
#include <iostream>
#include <cstdlib>
#include <cctype>

using namespace std;
using namespace cv;

int main()
{
float Sx = 0;
float Sy = 0;
float NewX;
float NewY;

Mat img, ScaledImg;
img = imread("C:/Jakob/tower.jpg");

do
{
    cout << "The current image size is: " << img.rows << "x" << img.cols << endl;
    cout << "First enter the new width for the image: ";
    cin >> NewX;
    cout << "Seond enter the new height for the image: ";
    cin >> NewY;
    if ((NewX >= 1) && (NewX <= 2000))
        if ((NewY >=1) && (NewY <= 2000))
        {
            Sx = (NewX/img.rows); 
            cout << "You entered " << NewX << " For Width" << endl; 
            Sy = (NewY/img.cols);
            cout << "You entered " << NewY << " For Height" << endl;
        }
        else
        {
            cout << "The number you entered does not match the requirements " << endl;
            cout << "Please start over " << endl;
        }   

}
while (NewX < 1 && NewX >= 2000 && NewY < 1 && NewY >= 2000);

cout << "Sx = " << Sx << endl;
cout << "Sy = " << Sy << endl;

resize(img, ScaledImg, Size(img.cols*Sx,img.rows*Sy));
imwrite("C:/Jakob/ScaledImage.jpg", ScaledImg);

cout << "Rows: " << ScaledImg.rows << " and Cols: " << ScaledImg.cols << endl;

imshow("Original", img);
imshow("Scaled Image", ScaledImg);
/*system("PAUSE");*/
waitKey(0);
return 0;

}

运行此代码后得到的错误是Sx正在使用而未初始化。仅当数字不在1-2000

范围内时才会发生这种情况

2 个答案:

答案 0 :(得分:3)

是的,因为默认情况下,C ++中的变量是用垃圾初始化的。 做类似的事情:

float Sx = 0.0;
float Sy = 0.0;

这一行:

resize(img, ScaledImg, Size(img.cols*Sx,img.rows*Sy));

只有当Sx和Sy当然不是0时才有效,所以如果你的其他参数超出2000范围,你必须将它们初始化为对你有用的东西。

答案 1 :(得分:1)

你必须初始化声明的变量才能使用它们

因此您需要初始化变量SxSy以避免此错误

替换

float Sx;
float Sy;

float Sx=0;
float Sy=0;

你在做条件时遇到问题

将其更改为

while ((NewX < 1 || NewX >= 2000) && (NewY < 1 || NewY >= 2000));