代码如下:
1 Mat src1 = Cv2.ImRead(@"C:\Users\sa\Pictures\Saved Pictures\3.png"); 2 Mat src2 = Cv2.ImRead(@"C:\Users\sa\Pictures\Saved Pictures\4.png"); 3 Cv2.ImShow("src1", src1); 4 Cv2.ImShow("src2", src2); 5 6 SURF surf = SURF.Create(2000, upright: true); 7 KeyPoint[] kp1, kp2; 8 Mat dst1 = new Mat(), dst2 = new Mat(); 9 surf.DetectAndCompute(src1, null, out kp1, dst1); 10 surf.DetectAndCompute(src2, null, out kp2, dst2); 11 12 FlannBasedMatcher flann = new FlannBasedMatcher(); 13 DMatch[][] dm = flann.KnnMatch(dst1, dst2, 2); 14 15 var dmWhere = dm.Where(x => x[0].Distance < 0.7 * x[1].Distance).ToArray(); 16 Point2f[] goodPoints1 = dmWhere.Select(i => kp1[i[0].QueryIdx].Pt).ToArray(); 17 Point2f[] goodPoints2 = dmWhere.Select(i => kp2[i[0].TrainIdx].Pt).ToArray(); 18 19 //List<Point2f> goodPoints3 = new List<Point2f>(); 20 //List<Point2f> goodPoints4 = new List<Point2f>(); 21 //for (int i = 0; i < dm.Length; i++) 22 //{ 23 // if (dm[i][0].Distance < 0.7 * dm[i][1].Distance) 24 // { 25 // goodPoints3.Add(kp1[dm[i][0].QueryIdx].Pt); 26 // goodPoints4.Add(kp2[dm[i][0].TrainIdx].Pt); 27 // } 28 //} 29 30 Mat mask12 = new Mat(); 31 Mat homography12 = Cv2.FindHomography(InputArray.Create(goodPoints2.ToArray()), InputArray.Create(goodPoints1.ToArray()), HomographyMethods.Ransac, 5, mask12); 32 33 OpenCvSharp.Size size = new OpenCvSharp.Size(src1.Width + src2.Width, src1.Height); 34 Mat result = new Mat(size, MatType.CV_8UC3); 35 Cv2.WarpPerspective(src2, result, homography12, new OpenCvSharp.Size(src1.Width + src2.Width, src1.Height)); 36 37 ImageFusion(src1, result, 100); 38 39 src1.CopyTo(result[new OpenCvSharp.Rect(0, 0, src1.Width, src1.Height)]); 40 Cv2.ImShow("Result", result);
1 /// <summary> 2 /// 图像交界处平滑处理 3 /// </summary> 4 /// <param name="src1"></param> 5 /// <param name="src2"></param> 6 /// <param name="width"></param> 7 private void ImageFusion(Mat src1, Mat src2, int width) 8 { 9 float widthF = width; 10 int height = src1.Height; 11 int start = src1.Cols - width; 12 float alpha = 0f; 13 unsafe 14 { 15 for (int i = 0; i < height; i++) 16 { 17 var ptr1 = (byte*)src1.Ptr(i); 18 var ptr2 = (byte*)src2.Ptr(i); 19 for (int j = start; j < src1.Cols; j++) 20 { 21 if (ptr2[j * 3] == 0 && ptr2[j * 3 + 1] == 0 && ptr2[j * 3 + 2] == 0) 22 { 23 alpha = 0f; 24 } 25 else 26 { 27 alpha = (j - start) / widthF; 28 } 29 ptr1[j * 3] = (byte)(ptr1[j * 3] * (1 - alpha) + ptr2[j * 3] * alpha); 30 ptr1[j * 3 + 1] = (byte)(ptr1[j * 3 + 1] * (1 - alpha) + ptr2[j * 3 + 1] * alpha); 31 ptr1[j * 3 + 2] = (byte)(ptr1[j * 3 + 2] * (1 - alpha) + ptr2[j * 3 + 2] * alpha); 32 } 33 } 34 } 35 }
效果:
标签:surf,Mat,src1,Cv2,src2,拼接,opencvsharp,alpha,new From: https://www.cnblogs.com/JustWantToStudy/p/17409214.html