Python-OpenCV学习--外接摄像头实时检测文本框

 

一、Windows7 系统下 Python 3.x版本  , 台式机外接摄像头 使用分水岭算法 腐蚀 膨胀等,识别文本的区域。

import numpy as np
import cv2
from matplotlib import pyplot as plt
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FPS, 15)
while True:

    ret, frame = cap.read()

    # 转化成灰度图
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

# 利用Sobel边缘检测生成二值图
    sobel = cv2.Sobel(gray, cv2.CV_8U, 1, 0, ksize=3)
# 二值化
    ret, binary = cv2.threshold(sobel, 0, 255, cv2.THRESH_OTSU + cv2.THRESH_BINARY)

# 膨胀、腐蚀
    element1 = cv2.getStructuringElement(cv2.MORPH_RECT, (30, 9))
    element2 = cv2.getStructuringElement(cv2.MORPH_RECT, (24, 6))

# 膨胀一次,让轮廓突出
    dilation = cv2.dilate(binary, element2, iterations=1)

# 腐蚀一次,去掉细节
    erosion = cv2.erode(dilation, element1, iterations=1)

# 再次膨胀,让轮廓明显一些
    dilation2 = cv2.dilate(erosion, element2, iterations=2)

#  查找轮廓和筛选文字区域
    region = []
    contours, hierarchy = cv2.findContours(dilation2, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    for i in range(len(contours)):
        cnt = contours[i]

    # 计算轮廓面积,并筛选掉面积小的
    area = cv2.contourArea(cnt)
    if (area < 1000):
        continue

    # 找到最小的矩形
    rect = cv2.minAreaRect(cnt)
    print("rect is: ")
    print(rect)

    # box是四个点的坐标
    box = cv2.boxPoints(rect)
    box = np.int0(box)

    # 计算高和宽
    height = abs(box[0][1] - box[2][1])
    width = abs(box[0][0] - box[2][0])

    # 根据文字特征,筛选那些太细的矩形,留下扁的
    if (height > width * 1.3):
        continue

    region.append(box)

# 绘制轮廓
    for box in region:
        cv2.drawContours(frame, [box], 0, (0, 255, 0), 2)

    cv2.imshow('img', frame)

    if cv2.waitKey(10) == ord("q"):
        break
#随时准备按q退出
cap.release()
cv2.destroyAllWindows()

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值