欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > python >内容正文

python

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

发布时间:2025/3/13 python 54 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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):continueregion.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()

 

总结

以上是生活随笔为你收集整理的Python-OpenCV学习--外接摄像头实时检测文本框的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。