我可能会在我的编程风格上使用一些指针(最近在OpenCV / C ++中自学),但手头的问题与我的裁剪程序中的绘图有关。
我单击图像中的一个点,它绘制一个矩形,然后我可以调整矩形的大小并点击“z”来裁剪并将图像保存在目标文件夹中。但每当我点击程序中的任何地方时,它会绘制一个新的矩形但保留最近的前一个矩形。所以我总是不断绘制2个矩形。我想这可能与setMousecallback的工作方式有关,但我不确定。打击是我的代码
#include "opencv2/opencv.hpp"
#include <iostream>
#include <string>
#include <stdio.h>
#include <fstream>
using namespace cv;
using namespace std;
Mat img;
string * strPtr;
int width, height;
void matResize(Mat& img){
if(width > 600 && height > 600){
int scale = width/600;
width = width/scale;
height = height/scale;
resize(img, img, Size(width, height));
}
}
void onMouse(int evt, int x, int y, int flags, void* param) {
if(evt == CV_EVENT_LBUTTONDOWN) {
img = imread(*strPtr);
transpose(img,img);
flip(img, img, 1);
width = img.cols;
height = img.rows;
matResize(img);
Point* ptPtr = (Point*)param;
ptPtr->x = x;
ptPtr->y = y;
}
}
int main(int argc, char* argv[])
{
ifstream file("/home/willem/Desktop/Training/ThumbsUp/img4resize/files.txt");
//Read each file location into a vector array
string str;
vector<string> fileLocations;
while (getline(file, str)){
fileLocations.push_back(str);
}
//Loop to process each Image
for(int i = 0; i < fileLocations.size(); ++i){
//Square Properties
Point2i pt(0,0);
int X, Y;
int hlen = 0;
Rect rect;
//Image name and rotation
int found = fileLocations[i].find_last_of("/");
int len = fileLocations[i].length();
string tempstr = fileLocations[i].substr(found+1,len-1);
namedWindow(tempstr);
img = imread(fileLocations[i]);
transpose(img,img);
flip(img, img, 1);
strPtr = &fileLocations[i];
//resize to scale
width = img.cols;
height = img.rows;
matResize(img);
//Mouse Properties
setMouseCallback(tempstr, onMouse, (void*)&pt);
//Image update loop
while(1){
//Update MouseClick Position
X = pt.x;
Y = pt.y;
//Set square properties
if(X == 0){
if(height > width)
hlen = (int)(height*(1.0/3));
else
hlen = (int)(width*(1.0/3));
rect = Rect(X-hlen,Y-hlen,2*hlen,2*hlen);
}
int waitKeyVar = waitKey(10);
if(waitKeyVar % 255 == 129 || waitKeyVar == 133){
//"q"
//Skip image
destroyWindow(tempstr);
break;
}
cout << waitKeyVar % 255 << endl;
if(waitKeyVar == 119 || waitKeyVar % 255 == 135){
//"w"
//Resize rect -5%
hlen = hlen*0.95;
}
if(waitKeyVar == 101 || waitKeyVar % 255 == 117){
//"e"
//resize rect +5%
hlen = hlen*1.05;
}
if(waitKeyVar == 122 || waitKeyVar % 255 == 138){
//"z"
//crop and save image
Mat cropped = img(Rect(X-hlen,Y-hlen, 2*hlen, 2*hlen));
string destination = "/home/willem/Desktop/AdMobilize/Training/ThumbsUp/New Positives/"; //Configure output here
string final = destination + tempstr;
imwrite(final, cropped);
destroyWindow(tempstr);
break;
}
//draw Rectangle
rectangle(img, Rect(X-hlen,Y-hlen, 2*hlen, 2*hlen), Scalar(255,255,255), 2,8,0);
//display Image
imshow(tempstr, img);
}
}
return 0;
}
答案 0 :(得分:2)
只需在while循环和put之外声明并初始化int waitKeyVar = 0;
在waitKeyVar = waitKey(10);
之后将imshow(tempstr, img);
放在底部。
最后一个矩形可能会出现,因为您正在显示图像并将waitKey
放在不同的位置。