更新时间:2023-11-27 20:12:34
对于轮廓图像
我认为想要类似
对于打开的数字,例如1
,2
,5
,很容易做到:从整个图像中裁剪,或绘制新图像.对于0
,6
,8
,9
之类的闭合数字,需要执行更多步骤.这是5
的示例,您将获得.
For opened number such as 1
, 2
, 5
, it is easy to do: Crop from the whole image, or draw on new image. For closed number such as 0
, 6
, 8
, 9
, more steps are needed. Here is example for 5
, you will get .
详细信息和描述在代码中.
#!/usr/bin/python3
# 2018.01.14 09:48:15 CST
# 2018.01.14 11:39:03 CST
import numpy as np
import cv2
im = cv2.imread('test.png')
imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(imgray, 127, 255, 0)
contours = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[-2]
## this contour is a 3D numpy array
cnt = contours[4]
res = cv2.drawContours(im,[cnt],0,(255,0,0), -1)
cv2.imwrite("contours.png", res)
## Method 1: crop the region
x,y,w,h = cv2.boundingRect(cnt)
croped = res[y:y+h, x:x+w]
cv2.imwrite("croped.png", croped)
## Method 2: draw on blank
# get the 0-indexed coords
offset = cnt.min(axis=0)
cnt = cnt - cnt.min(axis=0)
max_xy = cnt.max(axis=0) + 1
w,h = max_xy[0][0], max_xy[0][1]
# draw on blank
canvas = np.ones((h,w,3), np.uint8)*255
cv2.drawContours(canvas, [cnt], -1, (255,0,0), -1)
cv2.imwrite("canvas.png", canvas)