opencv: 轮廓绘制 详细拆解(图示+源码)

过程图解

第一步

读取要进行处理的原图:

origin_pic = './pic/6.jpg'
save_folder = './generated_pics'

img = cv2.imread(origin_pic)

此时原图如下:
这里写图片描述

第二步

将原图转换成单通道图(例如本例中用cv2.cvtColor转换成灰度图):

imgray = cv2.cvtColor(src=img, code=cv2.COLOR_BGR2GRAY)

转换后的单通道图如下:
这里写图片描述

第三步

对得到的单通道图进行阀值处理:

_, thresh = cv2.threshold(src=imgray, thresh=150, maxval=200, type=0)

得到阀值图片如下:
这里写图片描述

第四步

寻找轮廓并记录在返回的 contours列表 中:

image, contours, _1 = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

第五步

根据轮廓数据表,在三通道彩色图片上绘制轮廓:

contoured_colored_img = cv2.drawContours(img, contours, -1, (0, 0, 255), 2)

结果图如下:
这里写图片描述

也可以在黑白三通道图片上绘制轮廓:

thresh_expanded = np.expand_dims(thresh, axis=2)
gray_img = np.concatenate([thresh_expanded, thresh_expanded, thresh_expanded], axis=2)
contoured_gray_img = cv2.drawContours(gray_img, contours, -1, (0, 0, 255), 2)

结果图如下:
这里写图片描述

完整源码

我自己写的完整源码如下:

# coding=utf-8

import numpy as np
import cv2

origin_pic = './pic/6.jpg'
save_folder = './generated_pics'

import shutil
try:
    shutil.rmtree(save_folder)
except OSError:
    pass
import os
os.makedirs(save_folder)

img = cv2.imread(origin_pic)
imgray = cv2.cvtColor(src=img, code=cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(src=imgray, thresh=150, maxval=200, type=0)
image, contours, _1 = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
thresh_expanded = np.expand_dims(thresh, axis=2)
gray_img = np.concatenate([thresh_expanded, thresh_expanded, thresh_expanded], axis=2)
contoured_gray_img = cv2.drawContours(gray_img, contours, -1, (0, 0, 255), 2)
contoured_colored_img = cv2.drawContours(img, contours, -1, (0, 0, 255), 2)

cv2.imwrite(os.path.join(save_folder, 'imgray.jpg'), imgray)
cv2.imshow('imgray', imgray)
cv2.waitKey(2000)

cv2.imwrite(os.path.join(save_folder, 'thresh.jpg'), thresh)
cv2.imshow('thresh', thresh)
cv2.waitKey(2000)

cv2.imwrite(os.path.join(save_folder, 'image.jpg'), image)
cv2.imshow('image', image)
cv2.waitKey(2000)

cv2.imwrite(os.path.join(save_folder, 'contoured_gray_img.jpg'), contoured_gray_img)
cv2.imshow('contoured_gray_img', contoured_gray_img)
cv2.waitKey(2000)

cv2.imwrite(os.path.join(save_folder, 'contoured_colored_img.jpg'), contoured_colored_img)
cv2.imshow('', contoured_colored_img)
cv2.waitKey(2000)
cv2.destroyAllWindows()
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值