likes
comments
collection
share

go调用opencv图片矫正

作者站长头像
站长
· 阅读数 13

图片矫正实现流程

1.获取角度

HoughLines获取角度

HoughLines 返回的是角度,画线坐标点需要计算。[0]像素单位距离 [1]角度;注意问题得到线条有干扰需要控制
HoughLinesPWithParams 返回的是坐标点直接画线

FindContours获取角度

FindContours 得到最大面积轮廓-》得到角度

2.旋转图片

temp2D := gocv.GetRotationMatrix2D(rect.Center, angle, 0.8)
gocv.WarpAffine(reactImg, &desc, temp2D, image.Pt(0, reactImg.Cols()/2))

代码

go调用opencv图片矫正

windowA := gocv.NewWindow("watch")
	defer windowA.Close()

	root := getCurrentAbPathByCaller()
	img1 := gocv.IMRead(root+string(os.PathSeparator)+"tp.jfif", gocv.IMReadColor)
	img2 := gocv.NewMat()
	gocv.Canny(img1, &img2, 80, 160)
	//img3, _ := img2.ToImage()
	/*
			RetrievalExternal 最外侧轮廓
		    RETR_LIST:返回所有轮廓线,不建立等级关系
			RETR_CCOMP :返回所有轮廓,包含两个层级结构
			RETR_TREE :返回所有轮廓,建立完整的层次结构
	*/
	pointVecotr := gocv.FindContours(img2, gocv.RetrievalExternal, gocv.ChainApproxNone)
	gocv.DrawContours(&img1, pointVecotr, -1, color.RGBA{255, 0, 0, 0}, 1)

	maxindex := getMaxArea(pointVecotr)
	react := gocv.BoundingRect(pointVecotr.At(maxindex))
	reactImg := img1.Region(react)

	rect := gocv.MinAreaRect(pointVecotr.At(maxindex))
	points := rect.Points
	for i := 0; i < len(points); i++ {
		fmt.Println("%d %d", points[i].X, points[i].Y)
	}

	//
	line1 := math.Sqrt(math.Pow(float64(points[1].Y-points[0].Y), 2) + math.Pow(float64(points[1].X-points[0].X), 2))
	line2 := math.Sqrt(math.Pow(float64(points[3].Y-points[0].Y), 2) + math.Pow(float64(points[3].X-points[0].X), 2))

	//角度
	var angle = rect.Angle

	if line1 > line2 {
		angle = 90 + angle
	}

	desc := gocv.NewMat()

	/*
	GetAffineTransform 原图像点-》转换后图像点
	*/
	temp2D := gocv.GetRotationMatrix2D(rect.Center, angle, 0.8)
	gocv.WarpAffine(reactImg, &desc, temp2D, image.Pt(0, reactImg.Cols()/2))

	//reactImg := img1.Region(react)
	//gocv.BoxPoints(gocv.MinAreaRect(pointVecotr.At(getMaxArea(pointVecotr))), &img2)
	windowA.IMShow(desc)
	windowA.WaitKey(0)