您可以应用此管道:转换为灰度 -> 应用阈值处理(转换为白色和黑色)-> 查找轮廓 -> 选择正确形状的轮廓。
这里是示例代码:
#!/usr/bin/env python
import cv2
BLACK_THRESHOLD = 200
THIN_THRESHOLD = 10
ANNOTATION_COLOUR = (222,0,222)
img = cv2.imread('template.png')
orig = img.copy()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, thresh=BLACK_THRESHOLD, maxval=255, type=cv2.THRESH_BINARY_INV)[1]
# Optional: save thesholded image
cv2.imwrite("temp_thres.png", thresh)
# Find contours on the thresholded image
contours = cv2.findContours(thresh,cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[1]
for cont in contours:
# Find bounding rectangle of a contour
x,y,w,h = cv2.boundingRect(cont)
# Skip thin contours (vertical and horizontal lines)
if h<THIN_THRESHOLD or w<THIN_THRESHOLD:
continue
# Does the countour has the right shape (roughly four times longer than high)?
if 3*h<w<5*h:
roi = orig[y:y+h,x:x+w]
cv2.imwrite("four_letters.png",roi)
# Optional: draw annotations
cv2.rectangle(img,(x,y),(x+w,y+h),ANNOTATION_COLOUR,3)
# Optional: save annotated image
cv2.imwrite("temp_cont.png",img)
(可以删除三个可选步骤。它们仅用于生成图像temp_thres.png和temp_cont.png。)
输入图片template.png:
阈值图像temp_thres.png:
找到轮廓temp_cont.png:
四个字母空格four_letters.png: