如何通过python的opencv找到数字轮廓,想找出图片中的数字区域,然后单独把每一个数字放进一个列表里面
如何通过python的opencv找到数字轮廓,想找出图片中的数字区域,然后单独把每一个数字放进一个列表里面
自己写了一个,问题是提取的时候,5和7会粘连,不知道有什么办法可以解决
# -*- coding: utf-8 -*-
import cv2
# 对框进行排序
def sort_contours(cnts, method="left-to-right"):
reverse = False
i = 0
if method == "right-to-left" or method == "bottom-to-top":
reverse = True
if method == "top-to-bottom" or method == "bottom-to-top":
i = 1
boundingBoxes = [cv2.boundingRect(c) for c in cnts] # 用一个最小的矩形,把找到的形状包起来x,y,h,w
(cnts, boundingBoxes) = zip(*sorted(zip(cnts, boundingBoxes),
key=lambda b: b[1][i], reverse=reverse))
return cnts, boundingBoxes
# 调整图片尺寸大小
def resize(image, width=None, height=None, inter=cv2.INTER_AREA):
dim = None
(h, w) = image.shape[:2]
if width is None and height is None:
return image
if width is None:
r = height / float(h)
dim = (int(w * r), height)
else:
r = width / float(w)
dim = (width, int(h * r))
resized = cv2.resize(image, dim, interpolation=inter)
return resized
# 定义cv2展示函数
def cv_show(name, img):
cv2.imshow(name, img)
cv2.waitKey(0)
cv2.destroyAllWindows()
src_img = 'png/test2.png'
img = cv2.imread(src_img)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh1 = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU | cv2.THRESH_BINARY_INV)
rect_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (15, 3))
dilation = cv2.dilate(thresh1, rect_kernel, iterations=1)
# dilation = cv2.erode(thresh1, rect_kernel, iterations=3)
contours, hierarchy = cv2.findContours(dilation, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
im2 = img.copy()
x, y, w, h = cv2.boundingRect(contours[0])
cv2.rectangle(im2, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv_show('final', im2)
bk = 5
group = gray[y - bk:y + h + bk, x - bk:x + w + bk]
# cv_show("group", group)
group = resize(group, width=300)
blur = cv2.GaussianBlur(group, (1, 1), 0)
ret, th = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
contours, hierarchy = cv2.findContours(th, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
refCnts = sort_contours(contours, method="left-to-right")[0]
for contour in refCnts:
[x, y, w, h] = cv2.boundingRect(contour)
print(x, y, w, h)
if h > 20:
cv2.rectangle(group, (x, y), (x + w, y + h), (255, 0, 255), 0)
roi = th[y:y + h, x:x + w]
cv_show("dan shu zi", roi)