在当前工作中其实很多时候需要拍摄一些显示器或者是电视的画面当作素材写到报告中给到领导或者客人,图像要求比较严苛,但有时候自己手抖加脑子抽了拍了图片回去写报告才发现:wtf这tm我当时拍的啥玩意,也没法再重排,这时候其实可以利用opencv中的WarpPerspective 投影变换对图像进行矫正,下面出两个API的使用方法。
基础知识这篇博主介绍的很详细完整:https://blog.csdn.net/guduruyu/article/details/72518340
public static Mat GetPerspectiveTransform(IEnumerable src, IEnumerable dst)
由四对点计算透射变换
WarpPerspective(InputArray src, OutputArray dst, float[,] m, Size dsize, InterpolationFlags flags = InterpolationFlags.Linear, BorderTypes borderMode = BorderTypes.Constant, Scalar? borderValue = default(Scalar?));
下面进行实例演示
Mat src = new Mat(@"D:\BaiduNetdiskDownload\电视.jpg", ImreadModes.Color);
Cv2.PyrDown(src, src);
//Cv2.Resize(src, src, new Size(src.Width / 3, src.Height / 3));//or
Cv2.Resize(src, src, new Size(0, 0),1.0f/3.0f,1.0f/3.0f);
Mat gray = new Mat();
Cv2.CvtColor(src, gray, ColorConversionCodes.BGR2GRAY);
Cv2.Threshold(gray, gray, 100, 255, ThresholdTypes.Binary);//二值化
Mat stElem= Cv2.GetStructuringElement(MorphShapes.Rect, new Size(5, 5));
Cv2.MorphologyEx(gray, gray, MorphTypes.Open, stElem,new Point(-1,-1),5);//来五次开操作把无关点滤掉
Cv2.MorphologyEx(gray, gray, MorphTypes.Dilate, stElem);//膨胀扩大下范围
//新建两个point数组,用作GetPerspectiveTransform参数,变换前和变换后的四个点需要根据实际情况自己定位;
//也可以配合我上篇将的直线检测得到的线段端点进行取舍
Point2f[] srcPt=new Point2f[4];
Point2f[] dstPt = new Point2f[4];
srcPt[0] = new Point2f(32, 120);
srcPt[1] = new Point2f(617, 127);
srcPt[2] = new Point2f(611, 429);
srcPt[3] = new Point2f(50, 490);
dstPt[0] = new Point2f(30, 120);
dstPt[1] = new Point2f(620, 120);
dstPt[2] = new Point2f(620, 490);
dstPt[3] = new Point2f(30, 490);
Mat final = new Mat();
Mat warpmatrix = Cv2.GetPerspectiveTransform(srcPt, dstPt);//获得变换矩阵
Cv2.WarpPerspective(src, final, warpmatrix, src.Size());//投射变换,将结果赋给final
Cv2.ImShow("dst", final);
Cv2.WaitKey();