python五角星中间不填充_drawContours()取消填充字符内的圆(Python、OpenCV)

要绘制char而不填充闭合的内部区域:find the contours on the threshed binary image with hierarchy.

find the outer contours that don't have inner objects (by flag hierarchyi).

for each outer contour:

3.1 fill it(maybe need check whether needed);

3.2 then iterate in it's inner children contours, fill then with other color(such as inversed color).

combine with the crop code, crop them.

maybe you need sort them, resplit them, normalize them.

maybe, now you can do ocr with the trained model.

找到目标,填充内部封闭区域。在

refill内部闭合区域的核心代码如下:#!/usr/bin/python3

# 2018.01.14 09:48:15 CST

# 2018.01.15 17:56:32 CST

# 2018.01.15 20:52:42 CST

import numpy as np

import cv2

img = cv2.imread('img02.png')

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

## Threshold

ret, threshed = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV|cv2.THRESH_OTSU)

## FindContours

cnts, hiers = cv2.findContours(threshed, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[-2:]

canvas = np.zeros_like(img)

n = len(cnts)

hiers = hiers[0]

for i in range(n):

if hiers[i][3] != -1:

## If is inside, the continue

continue

## draw

cv2.drawContours(canvas, cnts, i, (0,255,0), -1, cv2.LINE_AA)

## Find all inner contours and draw

ch = hiers[i][2]

while ch!=-1:

print(" {:02} {}".format(ch, hiers[ch]))

cv2.drawContours(canvas, cnts, ch, (255,0,255), -1, cv2.LINE_AA)

ch = hiers[ch][0]

cv2.imwrite("001_res.png", canvas)

使用此图像运行此代码:

您将获得:

当然,这是针对两个层次的。我已经两次以上没有考试了。有需要的可以自己做测试。在

更新:

注意在不同的OpenCVs中,cv2.findContours返回不同的值。为了保持代码的可执行性,我们只需获得最后两个返回值:cnts,hiers=cv2.findContours(…)[-2:]

在OpenCV 3.4中:

在OpenCV 4.0中:

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值