I'm practice with emgu libraries, trying to crop and image to later apply another filtesre or search, the problem is I select a rectangle with the mouse, in the ImageBox(Emgu component) I selected zoom in the SizeMode property, and load the crop picture in another imagebox but the result is always a bit up of the area I selected.
I check the calculation with GIMP and I can see that the rectangle is ok, so I dont know what can be the problem
Point f1=scaleCalculation(firstPoint, pIma.Size, imOri.Size);
Point f2= scaleCalculation(secondPoint, pIma.Size, imOri.Size);
imGray.ROI = new Rectangle(Math.Min(f1.X, f2.X), Math.Min(f1.Y, f2.Y)
, Math.Abs(f1.X - f2.X), Math.Abs(f1.Y-f2.Y));
imOri.ROI = imGray.ROI;
pRec.Image = imOri.Copy();
imOri.ROI = new Rectangle();
And here is the function
private Point scaleCalculation(Point real, Size pBox, Size imCalc) {
double scale, spare;
try {
if (imCalc.Height > imCalc.Width){
scale = (double) imCalc.Height/ pBox.Height ;
spare = pBox.Width-((imCalc.Width / scale));
var x = ((real.X * scale) -(spare/4));
x = (x < 0) ? 0 : x;
return new Point((int) x, (int)(real.Y * scale));
}
else {
scale = (double) imCalc.Width/ pBox.Width ;
spare = pBox.Height - ((imCalc.Height / scale));
var y = ((real.Y * scale) - (spare /4));
y = (y < 0) ? 0 : y;
return new Point((int)(real.X * scale), (int) y);
}
}
catch (Exception ex) {
return new Point();
}
}
After look for a while I see that the problem it was in the scalecalculation function.
private Point scaleCalculation(Point real, Size pBox, Size imCalc) {
double scale, spare;
try {
if (imCalc.Height > imCalc.Width){
scale = (double)imCalc.Height / pBox.Height;
spare = (pBox.Width - (imCalc.Width / scale)) / 2;
var x = (real.X - spare);
x = (x < 0) ? 0 : x;
return new Point((int)(x * scale), (int)(real.Y * scale));
}
else {
scale = (double)imCalc.Width / pBox.Width;
spare = (pBox.Height - (imCalc.Height/scale))/2;
var y = (real.Y - spare);
y = (y < 0) ? 0 : y;
return new Point((int)(real.X * scale),(int) (y *scale));
}
}
catch (Exception ex) {
return new Point();
}
}
I going to try to explain it here with the help of the picture.
(Xr,Yr): Coordinate that we want to know. (Xm,Ym): Coordinate of the mouse. (Wi,Hi): Size of the picture. (Wp,Hp): Size of the ImageBox. S: Space form the edge of the Imagebox to the picture.
Xr = (Xm * scale)
S = [Hp -(Hi/scale)]/2
Yr = (Ym-S)
(This explanation is when width is bigger than height)
The first I do is calculate the scale using width or height depend which is the bigger.
To calculate S (spare) the height of the Image have to scale to the height of the Imagebox, substract it from the Imagebox height and divide for 2 the result to have the value of only one size.
From Ym (Real.Y) is substract the spare to calculate the y. and check if the result is negative.
Finally the result is Xm and y multiply for scale respectively