OpenCV踩坑(一)为什么你的cv2.drawContours()绘制轮廓失败

活不多说,先上代码:(错的哈!!!)

import cv2

# 读入银行卡数字的模板图片 灰度图
template = cv2.imread('ocr_a_reference.png')
template = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)
# 对模板图片进行二值化
template_thresh = cv2.threshold(template, 10, 255, cv2.THRESH_BINARY_INV)[1]
cv2.imshow('template_thresh', template_thresh)
cv2.waitKey(0)
# 轮廓检测 cv2.RETR_EXTERNAL--检测外侧轮廓
contours, hierarchy = cv2.findContours(template_thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
print(contours)
# 轮廓绘制
res = cv2.drawContours(template_thresh.copy(), contours, -1, (0, 0, 255), 3) 
cv2.imshow('res', res)
cv2.waitKey(0)
cv2.destroyAllWindows()

搞定,没报错-->运行

图片预处理之后(嗯,没毛病...)

接下来,看到绘制轮廓的图我傻了...

what??? 这是啥?这咋还变瘦了呢?

 

 

因为:绘制轮廓要在原图像上绘制,而代码里面是在二值化后的图像上进行处理的 

import cv2

# 读入银行卡数字的模板图片 灰度图
template = cv2.imread('ocr_a_reference.png')
template_gray = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)
# 对模板图片进行二值化
template_thresh = cv2.threshold(template_gray, 10, 255, cv2.THRESH_BINARY_INV)[1]
cv2.imshow('template_thresh', template_thresh)
cv2.waitKey(0)
# 轮廓检测 cv2.RETR_EXTERNAL--检测外侧轮廓
contours, hierarchy = cv2.findContours(template_thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
print(contours)
# 轮廓绘制
res = cv2.drawContours(template.copy(), contours, -1, (0, 0, 255), 3) #注意这里!!!
cv2.imshow('res', res)
cv2.waitKey(0)
cv2.destroyAllWindows()

 

总算好了... 

 

 

但是,到这里就结束了么?nonono,假装(划掉)认真 学习的我,要接着探索:

当在第一段代码里,将绘制轮廓的颜色换为:(255, 0, 0)

res = cv2.drawContours(template_thresh.copy(), contours, -1, (255, 0, 0), 3)
#template_thresh 是经过预处理的二值图像

res 会变成这样(加个原图作对比)

没错,他变胖了!!! 

 

 

对比前面的“变瘦”,我猜测:

在二值化图像上进行轮廓绘制之后,会再一次地被进行二值化;在本例中,绿色和红色的轮廓被二值化成黑色,而蓝色则成了白色,所以照片上的数字发生了粗细变化...

当然,拿出源码分析是最好的,所以先记录一下,日后补坑,也欢迎有路过的大佬替我解答。

评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值