图1 原图像
假如你有一张如图1的影像,你想把这三个目标的轮廓画出来,那么可以用以下代码实现。
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpathes
from skimage import io
import cv2
image= io.imread('1.png')#rgb三通道影像
image2 = np.zeros((image.shape[0],image.shape[1],image.shape[2]),dtype = np.uint8)
imgray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
thresh = imgray
thresh[thresh!=0]=255
print(np.unique(thresh))
#thresh为转换成黑白色的二值图
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(image2,contours,-1,(0,0,255),5) #(0,0,255)为轮廓颜色,5为轮廓线粗细
io.imsave('2.png',image2.astype(np.uint8))
至此,大功告成!!!