opencv_day13

#图像轮廓
#绘制一幅图像内的所有轮廓
import cv2
img=cv2.imread('./image/1.jpg')
cv2.imshow('original',img)
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,binary=cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
contours, hierarchy =cv2.findContours(binary,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
#参数依次表示待绘制轮廓的图像,需要绘制的轮廓,需要绘制的边缘索引,绘制的颜色,画笔的粗细
img=cv2.drawContours(img,contours,-1,(0,0,255),1)
cv2.imshow('result',img)
cv2.waitKey()
cv2.destroyAllWindows()

输出:

在这里插入图片描述

#逐个显示一幅图像内的边缘信息
#需要设置contoursIdx的值
import cv2
import numpy as np
img=cv2.imread('./image/1.jpg')
cv2.imshow('original',img)
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,binary=cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
contours,hierarchy=cv2.findContours(binary,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
n=len(contours)
contoursImg=[]
for i in range(n):
    temp=np.zeros(img.shape,np.uint8)
    contoursImg.append(temp)
    contoursImg[i]=cv2.drawContours(
        contoursImg[i],contours,i,(255,255,255),5
    )
    cv2.imshow('contours['+str(i)+']',contoursImg[i])
cv2.waitKey()
cv2.destroyAllWindows()

输出:
在这里插入图片描述

#使用轮廓绘制功能,提取前景图像
#将函数cv2.drawContours()的参数thickness设置为-1,绘制实心轮廓
#将实心轮廓与原始图像进行按位与原始图像,即可将前景对象从原始图像中拉取出来
import cv2
import numpy as np
img=cv2.imread('./image/feather.jpg')
cv2.imshow('original',img)
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,binary=cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
contours,hierarchy=cv2.findContours(binary,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
mask=np.zeros(img.shape,np.uint8)
#在黑色背景图片上绘制外轮廓
mask=cv2.drawContours(mask,contours,-1,(255,255,255),-1)
cv2.imshow('mask',mask)
loc=cv2.bitwise_and(img,mask)
cv2.imshow('location',loc)
cv2.waitKey()
cv2.destroyAllWindows()

输出:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值