比如拿到一张图片,包含图片中所有人物的坐标,这时,需要在Web网页上显示该图并选中坐标包含的目标人物
第一步: 先确定好坐标是(x1,y1,x2,y2) 还是(x1,y1,w,h)格式,如果是第二种,稍微多点计算,这里就以第二种方式为例
//获取原图坐标 Coors cor = new Coors(); int m_X = Convert.ToInt32(item.Coordinate_X.ToString()); int m_Y = Convert.ToInt32(item.Coordinate_Y.ToString()); int m_W = Convert.ToInt32(item.Coordinate_W.ToString()); int m_H = Convert.ToInt32(item.Coordinate_H.ToString()); //拼接FTP地址 //var url = string.Format("ftp://{0}:{1}@{2}/{3}", linuxFtpUser, linuxFtpPwd, linuxIp, path); var Url = item.imgpath.Replace("ftp:", "ftp:/"); byte[] buffer = new WebClient().DownloadData(Url); //byte[] 转内存流 MemoryStream ms = new MemoryStream(buffer); Image img = Image.FromStream(ms, true); //流用完要及时关闭 ms.Close(); //加载图片 Bitmap bmp = new Bitmap(img); System.Drawing.Image tempimage = bmp; //原图宽、高 var imagewidth = tempimage.Width;//宽 var imageheight = tempimage.Height;//高 //原图目标坐标 var x1 = m_X; var y1 = m_Y; var x2 = x1 + m_W; var y2 = y1 + m_H; //画布宽高 double divWid = Convert.ToDouble(topCavWidth); double divHig = Convert.ToDouble(topCavHeight); //宽比例 double CompareWid = divWid / imagewidth; //高比例 double CompareHig = divHig / imageheight; //界面中坐标 cor.NewX1 = x1 * CompareWid; cor.NewY1 = y1 * CompareHig; cor.NewX2 = x2 * CompareWid; cor.NewY2 = y2 * CompareHig;
其实就是 先将坐标(x1,y1,W,H)转为两点式(x1,y1,x1+w,y1+h),再拿到 web界面的上的宽高/原图的宽高的比例,按照各自对应的比例进行乘法便可得到web界面上图片对应的坐标。
当我们拿到两组坐标,需要算重叠率时候,先将坐标转换为 Rectangle(
int
x,
int
y,
int
width,
int
height)
类型,再进行比较
public static float ComputRectJoinUnion(Rectangle rc1, Rectangle rc2) { Point p1 = new Point(); Point p2 = new Point(); ; //p1为相交位置的左上角坐标,p2为相交位置的右下角坐标 p1.X = Math.Max(rc1.X, rc2.X); p1.Y = Math.Max(rc1.Y, rc2.Y); p2.X = Math.Min(rc1.X + rc1.Width, rc2.X + rc2.Width); p2.Y = Math.Min(rc1.Y + rc1.Height, rc2.Y + rc2.Height); float AJoin = 0; if (p2.X > p1.X && p2.Y > p1.Y) //判断是否相交 { AJoin = (p2.X - p1.X) * (p2.Y - p1.Y); //如果先交,求出相交面积 } float A1 = rc1.Width * rc1.Height; float A2 = rc2.Width * rc2.Height; float AUnion = (A1 + A2 - AJoin); //两者组合的面积 if (AUnion > 0) return (AJoin / AUnion); //相交面积与组合面积的比例 else return 0; }