我大概可以在我的編程風格上使用一些指針(最近在OpenCV/C++中自學),但手頭的問題與我的裁剪程序中的繪圖有關。裁剪程序在每個循環中繪製兩個矩形openCV
我點擊圖像上的一個點,它繪製一個矩形,然後我可以調整矩形大小並點擊「z」裁剪並將圖像保存到目標文件夾中。但是每當我點擊程序中的任何地方時,它會繪製一個新的矩形,但保留最近一次的矩形。所以我總是有兩個矩形。我認爲這可能與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;
}
看看示例應用程序[opencv_annotation.cpp](https://github.com/Itseez/opencv/blob/master/apps/annotation/opencv_annotation.cpp)。 – sturkmen