这是一个简单的方法:
-
获取二值图像。 Load image,转换为grayscale,
Gaussian blur,然后是Otsu's threshold。
-
找到扭曲的边界矩形轮廓。我们find contours 然后使用contour area 过滤以隔离矩形轮廓。接下来,我们找到带有cv2.minAreaRect() 的扭曲边界矩形并将其绘制到空白蒙版上。
-
查找角点。我们使用已实现为 cv2.goodFeaturesToTrack() 的 Shi-Tomasi 角点检测器进行角点检测。查看this 了解每个参数的说明。
检测到的边界矩形-> 掩码-> 检测到的角
角点
(188, 351)
(47, 348)
(194, 32)
(53, 29)
代码
import cv2
import numpy as np
# Load image, grayscale, blur, Otsu's threshold
image = cv2.imread('1.png')
mask = np.zeros(image.shape[:2], dtype=np.uint8)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5,5), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
# Find distorted bounding rect
cnts = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
area = cv2.contourArea(c)
if area > 5000:
# Find distorted bounding rect
rect = cv2.minAreaRect(c)
box = cv2.boxPoints(rect)
box = np.int0(box)
cv2.fillPoly(mask, [box], (255,255,255))
# Find corners
corners = cv2.goodFeaturesToTrack(mask,4,.8,100)
offset = 15
for corner in corners:
x,y = corner.ravel()
cv2.circle(image,(x,y),5,(36,255,12),-1)
x, y = int(x), int(y)
cv2.rectangle(image, (x - offset, y - offset), (x + offset, y + offset), (36,255,12), 3)
print("({}, {})".format(x,y))
cv2.imshow('thresh', thresh)
cv2.imshow('image', image)
cv2.imshow('mask', mask)
cv2.waitKey()