0

I have a picture box in a windows forms project, the picture box has the size property set to Stretch. I figured that clicking on a point on the picture box would mirror a click on the same exact co-ordinate on the image nested inside that picture box, but when I click on a point on the picture box, the calculation does not accurately mirror that point on the image. I capture the point clicked using the picture box's MouseClick event handler, then I perform calculations on point to draw over on the image and then I draw a circle over that point on the original image. The point drawn on the image is a little to the left and top of the actual position I clicked on the picture box. I need to get the point right so my user can click on any section of the image and add a watermark. Here is my code

private void PictureBox1_MouseClick(object sender, MouseEventArgs e){
  //calculate the point on the image
  var imageX = e.X *(pictureBox1.Image.Width/pictureBox1.Width);
  var imageY = e.Y * (pictureBox1.Image.Height/pictureBox1.Height);
  var point = new Point(imageX, imageY);
 //draw a circle on that point
  var circle = new CircleF(point, 5);
  var path = paths[index];
  var image = new Image<Bgr, byte>(path);
  image.Draw(circle, new Bgr(Color.Red),5);
  pictureBox1.Image = ToBitmap(image);
}

The circle is draw some distance to the left and some distance to the top of the actual position I clicked on the picture box. How can I fix this?

Son of Man
  • 1,213
  • 2
  • 7
  • 27
  • What are you doing inside `image.Draw` method ? Are you using GDI+ to draw the circle ? – Mad hatter Aug 17 '23 at 09:17
  • @Madhatter, I am using emgu Cv. Image is an emgu cv type – Son of Man Aug 17 '23 at 09:24
  • You might experience inaccuracy cause you are manipulating integers during your point interpolation. Is that better with `var imageX = e.X *(1.0f * pictureBox1.Image.Width/pictureBox1.Width);` ? – Mad hatter Aug 17 '23 at 09:34
  • ... Or you can remove parenthesis and do `var imageX = e.X * pictureBox1.Image.Width/pictureBox1.Width;` – Mad hatter Aug 17 '23 at 09:46
  • @Madhatter, you are a genius. I did the same for imageY and it worked. Thanks. Your the best – Son of Man Aug 17 '23 at 09:47
  • You know you can use [GDI to draw on images](https://learn.microsoft.com/en-us/windows/win32/api/gdiplusgraphics/nf-gdiplusgraphics-graphics-fromimage)? No need to reload the image from disk, or to introduce an emguCV dependency. – JonasH Aug 17 '23 at 09:59
  • [Translate Rectangle Position in a Picturebox in Zoom Mode](https://stackoverflow.com/q/53800328/7444103) – Jimi Aug 17 '23 at 10:40
  • @JonasH, Emgu CV needs me to reload the image from disk every time I perform an action. For this problem, it was a math issue in the point interpolation. Now it's working fine – Son of Man Aug 17 '23 at 11:28

0 Answers0