Ark*_*rka 5 python opencv image-processing computer-vision mnist
我有这种类型的图像,我只想提取字符.
二值化之后,我得到了这张图片
img = cv2.imread('the_image.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 9)
Run Code Online (Sandbox Code Playgroud)
然后在此图像上找到轮廓.
(im2, cnts, _) = cv2.findContours(thresh.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)
for contour in cnts[:2000]:
x, y, w, h = cv2.boundingRect(contour)
aspect_ratio = h/w
area = cv2.contourArea(contour)
cv2.drawContours(img, [contour], -1, (0, 255, 0), 2)
Run Code Online (Sandbox Code Playgroud)
我正进入(状态
我需要一种方法来过滤轮廓,以便它只选择字符.所以我可以找到边界框并提取roi.
我可以找到轮廓并根据区域的大小过滤它们,但源图像的分辨率不一致.这些图像来自移动相机.
此外,框的边框是断开的.我无法准确检测到这些盒子.
编辑:
如果我取消选择宽高比小于0.4的盒子.然后它在某种程度上起作用.但我不知道它是否适用于不同分辨率的图像.
for contour in cnts[:2000]:
x, y, w, h = cv2.boundingRect(contour)
aspect_ratio = h/w
area = cv2.contourArea(contour)
if aspect_ratio < 0.4:
continue
print(aspect_ratio)
cv2.drawContours(img, [contour], -1, (0, 255, 0), 2)
Run Code Online (Sandbox Code Playgroud)
没那么难...
import cv2
img = cv2.imread('img.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow('gray', gray)
ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU)
cv2.imshow('thresh', thresh)
im2, ctrs, hier = cv2.findContours(thresh.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
sorted_ctrs = sorted(ctrs, key=lambda ctr: cv2.boundingRect(ctr)[0])
for i, ctr in enumerate(sorted_ctrs):
x, y, w, h = cv2.boundingRect(ctr)
roi = img[y:y + h, x:x + w]
area = w*h
if 250 < area < 900:
rect = cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.imshow('rect', rect)
cv2.waitKey(0)
Run Code Online (Sandbox Code Playgroud)
结果
您可以根据需要调整代码(这里可以使用原始图像保存 ROI;为了最终进行 OCR 识别,您必须将它们保存为二进制格式 - 可以使用比按区域排序更好的方法)
资料来源:使用 Python 和 OpenCV以及我的一些知识从图像中提取 ROI。
开玩笑,看看我的问题/答案。
| 归档时间: |
|
| 查看次数: |
1780 次 |
| 最近记录: |