如何在C#中读取并显示转换后的像素坐标(基于Emgu.Cv)
解决Emgu.Cv中旋转坐标可视化与绘制问题
一、将旋转后的Point列表转换为InputArray获取包围矩形
CvInvoke.BoundingRectangle需要InputArray类型参数,可将Point数组包装成Mat来满足要求:
// 假设rotatedPoints是你得到的旋转后坐标列表 Point[] rotatedPointsArray = rotatedPoints.ToArray(); // 创建Mat存储坐标数据,格式为N行1列,32位整数,2通道(对应X、Y坐标) Mat pointsMat = new Mat(rotatedPointsArray.Length, 1, DepthType.Cv32S, 2); for (int i = 0; i < rotatedPointsArray.Length; i++) { pointsMat.SetData(i, 0, new int[] { rotatedPointsArray[i].X, rotatedPointsArray[i].Y }); } // 获取所有旋转后坐标的包围矩形 Rectangle boundingRect = CvInvoke.BoundingRectangle(pointsMat);
二、在图像上绘制旋转后坐标对应的矩形
无需依赖BoundingRectangle,可直接根据旋转后的坐标计算矩形位置并绘制:
// 加载原始图像 Image<Bgr, byte> originalImage = new Image<Bgr, byte>("your_image_path.png"); // 克隆图像避免修改原图 Image<Bgr, byte> drawCanvas = originalImage.Clone(); // 假设圆形半径为10,根据实际场景调整 int circleRadius = 10; foreach (Point center in rotatedPoints) { // 构造以旋转后中心为原点的矩形 Rect targetRect = new Rect( center.X - circleRadius, center.Y - circleRadius, 2 * circleRadius, 2 * circleRadius ); // 绘制红色矩形,线宽2 CvInvoke.Rectangle(drawCanvas, targetRect, new Bgr(Color.Red).MCvScalar, 2); } // 显示绘制结果 CvInvoke.Imshow("Visualization of Rotated Coordinates", drawCanvas); CvInvoke.WaitKey(0);
三、正确使用WarpAffine实现图像旋转
绕自定义原点(最大物体中心)旋转图像,需正确构造旋转矩阵并执行变换:
// originPoint是你设定的原点(最大物体中心) Point originPoint = new Point(/* 你的原点坐标 */); // rotationAngle是算法计算出的旋转角度 double rotationAngle = /* 你的旋转角度 */; Size imageSize = originalImage.Size; // 构造旋转矩阵,指定旋转中心、角度、缩放因子 Mat rotationMatrix = CvInvoke.GetRotationMatrix2D(originPoint, rotationAngle, 1.0); // 创建输出图像,尺寸与原图一致 Image<Bgr, byte> rotatedImage = new Image<Bgr, byte>(imageSize); // 执行仿射变换,采用双线性插值避免锯齿 CvInvoke.WarpAffine( originalImage, rotatedImage, rotationMatrix, imageSize, Inter.Cubic, BorderType.Constant, new Bgr(Color.Black).MCvScalar ); // 在旋转后的图像上绘制坐标 foreach (Point center in rotatedPoints) { Rect targetRect = new Rect(center.X - circleRadius, center.Y - circleRadius, 2 * circleRadius, 2 * circleRadius); CvInvoke.Rectangle(rotatedImage, targetRect, new Bgr(Color.Blue).MCvScalar, 2); } CvInvoke.Imshow("Rotated Image with Markers", rotatedImage); CvInvoke.WaitKey(0);
内容的提问来源于stack exchange,提问作者elcapo
相关产品推荐
相关产品推荐

