欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

OpenCV的等高线画法

程序员文章站 2022-06-01 08:37:22
...

用于圈出图片上颜色深浅不同的区域

处理步骤:gray + threshold + open + distanceTransform + medianBlur + find_contours

from skimage import io,color
import numpy as np
import cv2
from matplotlib import pyplot as plt
from IPython.display import display
from ipywidgets import interact,interactive,fixed
plt.style.use('classic')

1.读取图片,并二值化

OpenCV的等高线画法

OpenCV的等高线画法

img = io.imread('img.JPG')
img2 = io.imread('img2.JPG')

gray = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY)
# ret 值多凭感觉
thresh = np.ones_like(gray)
ret = 168
thresh[gray < ret] = 255
thresh[gray > ret] = 0

fig = plt.figure(figsize=(16, 6))
plt.subplot(131),plt.imshow(img)
plt.subplot(132),plt.imshow(gray,'gray')
plt.subplot(133),plt.imshow(thresh,'gray')
plt.show()

OpenCV的等高线画法

2.降噪,扩张并获得距离参数

# noise removal
kernel = np.ones((3,3),np.uint8)
opening = cv2.morphologyEx(thresh,cv2.MORPH_OPEN,kernel, iterations = 2)

# sure background area
sure_bg = cv2.dilate(opening,kernel,iterations=3)

# Finding sure foreground area
dist_transform = cv2.distanceTransform(opening,cv2.DIST_L2,5)

# distanceTransform
fig = plt.figure(figsize=(16, 6))
plt.subplot(131),plt.imshow(opening,'gray')
plt.subplot(132),plt.imshow(sure_bg,'gray')
plt.subplot(133),plt.imshow(dist_transform,'gray')

plt.show()

OpenCV的等高线画法

3.滑动调节等高线高度,绘制等高线


def distance(dist_transform,thresh=0.1):
    ret, sure_fg = cv2.threshold(dist_transform,thresh*dist_transform.max(),255,0)
    sure_fg = np.uint8(sure_fg)
    median_img = cv2.medianBlur(sure_fg,17)
    fig = plt.figure(figsize=(20,18))
    plt.subplot(121),plt.imshow(median_img,'gray'),plt.xticks([]),plt.yticks([])

    im2, contours, hierarchy = cv2.findContours(median_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    img_ground = img2.copy()
    cv2.drawContours(img_ground,contours,-1,(0,255,225),5)

    plt.subplot(122),plt.imshow(img_ground),plt.xticks([]),plt.yticks([])
    plt.show()

    return median_img,img_ground

lims = (0.0,1.0,0.05)
w = interactive(distance,dist_transform = fixed(dist_transform),thresh = lims)
display(w)

可以拖动进度条调整阈值,以改变等高线位置

OpenCV的等高线画法

相关标签: opencv color