python - Python-OpenCV 数字分割
问题描述
对于我的图像处理课程,我自己选择了数字识别项目。在这个项目中,目的是识别模拟水煤气表上的数字。我的第一个目标是找到数字所在的位置并在它们上画一个矩形。稍后我想拍摄矩形图像并在其上应用机器学习来识别数字。目前我被困在数字分割部分。你有什么建议?
import cv2
import imutils
from imutils.perspective import four_point_transform
from imutils import contours
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
img = cv2.imread('/Users/USER/Desktop/digitSegmentation/picture2.jpg')
# Grayscaling
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#Image blurring
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
# Thresholding
ret, thresh_img = cv2.threshold(img, 120, 255, cv2.THRESH_BINARY)
# Canny edge detection
edges = cv2.Canny(blurred, 50, 200, 255)
cnts = cv2.findContours(edges.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)
displayCnt = None
for c in cnts:
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.02 * peri, True)
if len(approx) == 4:
displayCnt = approx
break
thresh = cv2.threshold(edges, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2, 6))
thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
lower_blue = np.array([50, 50, 0])
upper_blue = np.array([120, 255, 255])
mask = cv2.inRange(hsv, lower_blue, upper_blue)
img_rect = cv2.rectangle(img, (384, 0), (510, 128), (0, 255, 0), 3)
cv2.imshow('Original image', img)
cv2.imshow('Gray image', gray)
cv2.imshow("Threshold image", thresh_img)
cv2.imshow('Edged image', edges)
cv2.imshow('Rectangle drawing', img_rect)
cv2.imshow('kernel',kernel)
cv2.imshow('Thresholding with Canny',thresh)
cv2.imshow('Masked image',mask)
cv2.waitKey(0)
cv2.destroyAllWindows()
解决方案
我需要更多解释/上下文来给你一个合适的答案。你能提供更多的图片吗?一种通用的方法是使用 ocr(如 tesseract,它很容易使用,您可以在 opencv 中使用它)来查找出现的五位数字、逗号然后是 3 digist 和立方米单位。这也会给你周围的边界框(也许它会被检测为单独的单词,所以你可能需要一个合并步骤。)
如果你真的想进行某种分割来找到黑色区域,一种方法可能是用一个简单的阈值对图像进行二值化,用一点形态关闭来关闭对象并选择具有适当统计的区域(是好的范围?形状看起来像一个矩形?里面有 11 个白色区域吗?等等...)但我认为它比使用 tesseract 更难设置
推荐阅读
- c# - 如何修复 Xamarin.Forms android 应用程序中的 Java.Lang.OutOfMemoryError?
- python - 如何从历史中访问指标
- python - 如何在 Flask 应用程序中共享请求的 Session 对象
- java - 如何解决 windows 10 操作系统下 selenium 中的连接不安全问题?请帮助 SLENIUM firefox 测试自动化社区
- flutter - Flutter TypeAhead 问题
- python - 将多处理与共享内存一起用于大全局数据
- vba - 保存项目时需要运行代码
- docker - Docker 构建未能到达 debian repo
- ios - iOS 13 中第二个视图控制器的导航栏按钮对齐错误
- spring-boot - 如何将外部 ssl 证书导入 java 本地密钥库?