I’m working on adding image drawing and erasing capabilities using OpenCV in C++. But the problem is that it’s not fluid at all, the drawing only appears when I release the mouse and it appears very straight, as you can see in this video
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
Mat originalImage;
Mat currentImage;
Mat tempImage;
bool isDrawing = false;
bool isErasing = false;
Point startPoint;
void updateImage() {
addWeighted(originalImage, 1.0, tempImage, 1.0, 0.0, currentImage);
imshow("Drawing", currentImage);
}
static void drawCallback(int event, int x, int y, int flags, void* param) {
switch (event) {
case EVENT_LBUTTONDOWN:
if (flags & EVENT_FLAG_CTRLKEY) {
isErasing = true;
startPoint = Point(x, y);
}
else {
isDrawing = true;
startPoint = Point(x, y);
}
break;
case EVENT_MOUSEMOVE:
if (isDrawing) {
line(tempImage, startPoint, Point(x, y), Scalar(0, 0, 255), 8);
startPoint = Point(x, y);
updateImage();
}
else if (isErasing) {
line(tempImage, startPoint, Point(x, y), Scalar(0, 0, 0), 8);
startPoint = Point(x, y);
updateImage();
}
break;
case EVENT_LBUTTONUP:
isDrawing = false;
isErasing = false;
break;
}
}
int main()
{
string imagePath = "C:/Users/Yuri/Pictures/space.jpg";
originalImage = imread(imagePath, IMREAD_COLOR);
resize(originalImage, originalImage, { 1000, 500 }, 0, 0, INTER_NEAREST);
currentImage = Mat::zeros(originalImage.size(), originalImage.type());
tempImage = currentImage.clone();
namedWindow("Drawing");
updateImage();
setMouseCallback("Drawing", drawCallback, nullptr);
while (1) {
imshow("Drawing", currentImage);
if (waitKey(0) == 27)
break;
}
destroyAllWindows();
return 0;
}
I’m looking to speed things up and make the drawing and erasing smoother. Any tips or tricks on optimizing my code or using specific OpenCV features would be awesome.
When I don’t use any images I don’t need to use addWeighted
, and so it becomes extremely fluid, but the idea is to draw in images and I believe that using addWeighted
is what is causing the slowness, but I haven’t found ways to do what I need without it
Yuri de Melo Zorzorli Nunes is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.