Я надеюсь, что кто-то может помочь мне с этой проблемой, я делаю код, который захватывает изображение, позволяет пользователю рисовать линии, а затем сохранять эти координаты в файл, который будет использоваться в другой программе. Я могу взять изображение нарисовать линии и сохранить их. Проблема, с которой я сталкиваюсь, заключается в том, что линия даже не начинается с того места, где я ее щелкаю.
Вложение: как видно из прикрепленных изображений, зеленая линия показывает линию, которую я создал, а стрелка показывает, где я на самом деле нажал на изображение. Зеленая линия не соответствует стрелке пользователя. Я знаю, что координаты неверны, но, похоже, не могу решить проблему.

Настройки: Ниже приведены настройки, которые мой Qlabel имеет в GUI
- минимальный и максимальный размер = 861 x 530
- Gemorty = 10 x 20
Код:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <stddef.h>
#include <QString>
#include <opencv4/opencv2/opencv.hpp>
#include <opencv4/opencv2/core/core.hpp>
#include <opencv4/opencv2/highgui/highgui.hpp>
#include <opencv4/opencv2/imgproc/imgproc.hpp>
#include <opencv4/opencv2/imgcodecs/imgcodecs.hpp>
#include "ueye.h"
#include <QString>
#include <QFileDialog>
#include <QTimer>
#include <QDebug>
#include <QFile>
#include <QLabel>
using namespace std;
using namespace cv;
HIDS hCam = 0; // 0 for the next available camera. 1-254 to access by ID
SENSORINFO sInfo;
HWND hWndDisplay;
char* pcImageMemory;
int DisplayWidth, DisplayHeight;
Mat img;
cv::Point P3;
cv::Point P4;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
cout << "Lets Begin" << endl;
CaptureImage();
//Timer = new QTimer(this);
//connect(Timer, SIGNAL(timeout()), this, SLOT(DisplayImage()));
//Timer->start(); //Will start the timer
ui->display_image->setMouseTracking(true);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::CaptureImage(){
cout << "Capture Image" << endl;
is_InitCamera(&hCam, hWndDisplay);
// You can query information about the sensor type used in the camera
is_GetSensorInfo(hCam, &sInfo);
// Saving the information about the max. image proportions in variables
DisplayWidth = sInfo.nMaxWidth;
DisplayHeight = sInfo.nMaxHeight;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Need to find out the memory size of the pixel and the colour mode
int nColorMode;
int nBitsPerPixel = 24;
if (sInfo.nColorMode == IS_COLORMODE_BAYER)
{
// For color camera models use RGB24 mode
nColorMode = IS_CM_BGR8_PACKED;
nBitsPerPixel = 24;
}
else if (sInfo.nColorMode == IS_COLORMODE_CBYCRY)
{
// For CBYCRY camera models use RGB32 mode
nColorMode = IS_CM_BGRA8_PACKED;
nBitsPerPixel = 32;
}
else
{
// For monochrome camera models use Y8 mode
nColorMode = IS_CM_MONO8;
nBitsPerPixel = 24;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int nMemoryId;
// Assigns a memory for the image and sets it active
is_AllocImageMem(hCam, DisplayWidth, DisplayHeight, nBitsPerPixel, &pcImageMemory, &nMemoryId);
is_SetImageMem(hCam, pcImageMemory, nMemoryId);
// Acquires a single image from the camera
is_FreezeVideo(hCam, IS_WAIT);
// Parameter definition for saving the image file
IMAGE_FILE_PARAMS ImageFileParams;
ImageFileParams.pwchFileName = L"./TestImage.bmp"; /// <-- Insert name and location of the image
ImageFileParams.pnImageID = NULL;
ImageFileParams.ppcImageMem = NULL;
ImageFileParams.nQuality = 0;
ImageFileParams.nFileType = IS_IMG_BMP;
// Saves the image file
if (is_ImageFile(hCam, IS_IMAGE_FILE_CMD_SAVE, (void*)&ImageFileParams, sizeof(ImageFileParams)) == IS_SUCCESS)
{
cout << "An Image was saved" << endl;
}
else
{
cout << "something went wrong" << endl;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Releases an image memory that was allocated
is_FreeImageMem(hCam, pcImageMemory, nMemoryId);
// Disables the hCam camera handle and releases the data structures and memory areas taken up by the uEye camera
is_ExitCamera(hCam);
//return -1;
DisplayImage();
}
void MainWindow::DisplayImage(){
//cout << "Display image" << endl;
cv::Point hold_1;
cv::Point hold_2;
//cv::Point p1(100,100), p2(200,100);
cv::Scalar colorLine(0,255,0); // Green
int thicknessLine = 2;
//Mat img;
img = imread("./TestImage.bmp");
cv::resize(img, img, Size(861, 530), 0, 0, INTER_LINEAR);//530
cv::cvtColor(img,img,cv::COLOR_RGB2BGR); //Qt reads in RGB whereas CV in BGR
//cout << P3 << endl;
std::ifstream file("Data.txt");
std::string line;
while(std::getline(file, line))
{
std::stringstream linestream(line);
std::string data;
std::string item1;
std::string item2;
std::string item3;
std::string item4;
std::getline(linestream, item1, ',');
std::getline(linestream, item2, ']');
std::getline(linestream, item3, ']');
item4 = item3;
//item1.erase(item1.find('['));
item1.erase(std::find(item1.begin(), item1.end(), '['));
item2.erase(std::find(item2.begin(), item2.end(), ' '));
item3.erase(std::find(item3.begin(), item3.end(), '['));
item3 = item3.substr(0, item3.find(",", 0));
item3.erase(std::find(item3.begin(), item3.end(), ' '));
item4 = item4.substr(item4.find(",") + 1);
item4.erase(std::find(item4.begin(), item4.end(), ' '));
int first_cor = std::stoi(item1);
int second_cor = std::stoi(item2);
int third_cor = std::stoi(item3);
int fourth_cor = std::stoi(item4);
if(linestream) // true if there were no errors reading the stream
{
// cout << "[" << first_cor << ", " << item2 << "]" << "," << "[" << item3 << ", " << item4 << "]" << '\n';
// std::cout << item4 << '\n';
hold_1 = cv::Point(first_cor, second_cor);
hold_2 = cv::Point(third_cor, fourth_cor);
// cout << hold_1 << hold_2 << endl;
cv::line(img, hold_1, hold_2, colorLine, thicknessLine);
}
}
cv::line(img, P3, P4, colorLine, thicknessLine);
QImage imdisplay((uchar*)img.data, img.cols, img.rows, img.step, QImage::Format_RGB888); //Converts the CV image into Qt standard format
//ui->display_image->mapFrom(this, event->pos());
//ui->display_image->setGeometry(200, 200, 200, 200);
ui->display_image->setPixmap(QPixmap::fromImage(imdisplay));//display the image in label that is created earlier
}
void MainWindow::mouseMoveEvent(QMouseEvent* event)
{
//qDebug() << "Mouse move.." << event->pos() << "---> " << event->pos().x() << "," << event->pos().y(); // these printing same values
P4 = cv::Point(event->pos().x(), event->pos().y());
DisplayImage();
}
void MainWindow::mousePressEvent(QMouseEvent* event)
{
qDebug() << "Mouse press.." << event->pos() << "---> " << event->pos().x() << "," << event->pos().y(); // these printing same values
P3 = cv::Point(event->pos().x(), event->pos().y());
}
void MainWindow::mouseReleaseEvent(QMouseEvent *event)
{
qDebug() << "Mouse release.." << event->pos() << "---> " << event->pos().x() << "," << event->pos().y(); // these printing same values
/*ofstream file("Data.txt");
file<< P3 << " " << P4<< ";" << endl;
file.close();*/
std::ofstream outfile;
outfile.open("Data.txt", std::ios_base::app); // append instead of overwrite
outfile << P3 << " " << P4<< ";" << endl;
outfile.close();
//return 0;
cout << P3 << P4 << ";" << endl;
DisplayImage();
}
выше - мой код, и я не могу понять, почему координаты отключены, я думаю, что это как-то связано с cv::resize(img, img, Size(861, 530), 0, 0, INTER_LINEAR);
, однако пробовал многие вещи просто не мог заставить его работать, раздражает, потому что это почти последний часть моего кодирования.
Спасибо