原理:
道格拉斯-普克算法(Douglas-Peucker)来实现。该算法也以Douglas-Peucker算法和迭代终点拟合算法为名。是将曲线近似表示为一系列点,并减少点的数量的一种算法。该算法的原始类型分别由乌尔斯·拉默(Urs Ramer)于1972年以及大卫·道格拉斯(David Douglas)和托马斯·普克(Thomas Peucker)于1973年提出,并在之后的数十年中由其他学者予以完善。
经典的Douglas-Peucker算法描述如下:
(1)在曲线首尾两点A,B之间连接一条直线AB,该直线为曲线的弦;
(2)得到曲线上离该直线段距离最大的点C,计算其与AB的距离d;
(3)比较该距离与预先给定的阈值threshold的大小,如果小于threshold,则该直线段作为曲线的近似,该段曲线处理完毕。
(4)如果距离大于阈值,则用C将曲线分为两段AC和BC,并分别对两段取信进行1~3的处理。
(5)当所有曲线都处理完毕时,依次连接各个分割点形成的折线,即可以作为曲线的近似。
实现:
里面有些细节;如标记连通区域,连通区域属性用法,如何在图上叠加字符,反正切函数的应用等等
#encoding=utf-8
import cv2
import numpy as np
from skimage import measure
from skimage import morphology
import torch
import math
def threshold_demo(image):
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
#//ret, binary = cv2.threshold(gray, 0, 255, 100)
#//print("threshold value %s"%ret)
binary = np.zeros((720,1280),dtype=np.uint8)
for u in range(720):
for v in range(1280):
if gray[u, v] < 10:
binary[u, v] = 255
return binary
if __name__ == '__main__':
oimg = cv2.imread('111.jpg')
img = threshold_demo(oimg)
cv2.imwrite("11111111.jpg", img)
flagimg = np.zeros((720,1280),dtype=np.uint8)
for u in range(720):
for v in range(1280):
if img[u, v] > 200:
flagimg[u, v] = 1
skeleton =morphology.skeletonize(flagimg)
flagimgx = np.zeros((720,1280),dtype=np.uint8)
for u in range(720):
for v in range(1280):
if skeleton[u, v] > 0:
flagimgx[u, v] = 255
lable = measure.label(flagimgx, connectivity = 2)
props = measure.regionprops(lable, intensity_image=None, cache=True)
for i in range(len(props)):
y0, x0, y1, x1 = props[i].bbox
flagmax = 0;
labelv = props[i].label
for j in range(len(props[i].coords)):
y,x = props[i].coords[j]
flag = 0
if y > 1 and y < 720 - 1 and x > 1 and x < 1280 - 1:
for l in range(y -1 ,y + 2):
for r in range(x -1 ,x + 2):
if lable[l ,r] == labelv:
flag += 1
if flag > flagmax:
flagmax = flag
if flag >= 4:
flagimgx[y, x] = 0
cv2.imwrite("middle.jpg", flagimgx)
lable = measure.label(flagimgx, connectivity = 2)
props = measure.regionprops(lable, intensity_image=None, cache=True)
num = 0
for i in range(len(props)):
are = props[i].area
#print("are = ", are)
if are > 172 and are < 200:
approx = cv2.approxPolyDP(props[i].coords, 1, False)
for u in range(len(approx) - 1):
y,x = approx[u][0]
flagimgx[y, x] = 100
font=cv2.FONT_HERSHEY_SIMPLEX
numx ='%d'%num
flagimgx = cv2.putText(flagimgx,numx,(x, y),font,0.5,(255,255,255),1)
y1,x1 = approx[u + 1][0]
# 斜率
aratio = (y1 - y) / (x1 - x)
print("num = ", aratio)
ang = math.atan(aratio)
ang = (ang * 180) / 3.1415926
print("ang = ", ang)
num = num + 1
cv2.imwrite("22222222.jpg", flagimgx)