使用opencv的多边形拟合获取到的角点可能会存在很多个,对文字扭曲纠正,我本来是想找到4个角的坐标点,再使用透视变换纠正变形的文字,但自己研究,苦于没有找到好的方法,在此就自己写了个方法,还有一些问题存在,希望能提供一些指导及思路
#coding:utf-8
import numpy as np
hull=[[[31, 12]],[[21, 18]], [[6, 19]], [[8, 41]], [[35, 30]]]
def getfourpoints(hull,value=12,boder=0):
alllist=[]
minlist=sorted(hull)
#左上角坐标
left=(minlist[0][0][0]+boder,minlist[0][0][1]+boder)
# 左下角坐标
leftbottom=[]
for i,p in enumerate(minlist):
if i>0:
if p[0][1]-minlist[0][0][1]>value:
leftbottom=(p[0][0]+boder,p[0][1]+boder)
break
elif p[0][1]-minlist[0][0][1]<-value:
leftbottom = left
left = (p[0][0]+boder,p[0][1]+boder)
break
else:
continue
#右下角坐标
data = np.array(hull)
flist=data[np.lexsort(-data.T)]
# 第一行的差值
wjh = abs(flist[0][0][0][0] - flist[0][0][0][1])
# 第二行的差值
pwjh = abs(flist[0][1][0][0] - flist[0][1][0][1])
# 第一行宽减第二行宽
ojtw = flist[0][0][0][0] - flist[0][1][0][0]
# 第一行高减第二行高
ojth = flist[0][0][0][1] - flist[0][1][0][1]
if ojtw < 0 and pwjh <= wjh:
rightbottom = (flist[0][1][0][0] + boder, flist[0][1][0][1] + boder)
else:
rightbottom = (flist[0][0][0][0] + boder, flist[0][0][0][1] + boder)
zlist=data[np.lexsort(data.T)][0]
# 右上角坐标
righttop=[]
for i,p in enumerate(zlist):
if i>0:
if p[0][0]-left[0]>value:
righttop=(p[0][0]+boder,p[0][1]+boder)
break
else:
continue
else:
if p[0][0] - left[0]>value:
righttop = (p[0][0]+boder,p[0][1]+boder)
break
alllist.append(left)
alllist.append(leftbottom)
alllist.append(rightbottom)
alllist.append(righttop)
#如果存在空则未找全4个角坐标
if len(left)==0 or len(leftbottom)==0 or len(rightbottom)==0 or len(righttop)==0:
alllist=[]
return alllist
输出的4角坐标: