OpenCV的等高线画法

布满荆棘的人生 2022-06-08 02:48 613阅读 0赞

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

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

  1. from skimage import io,color
  2. import numpy as np
  3. import cv2
  4. from matplotlib import pyplot as plt
  5. from IPython.display import display
  6. from ipywidgets import interact,interactive,fixed
  7. plt.style.use('classic')

1.读取图片,并二值化

原始图片img

通道转换后的图片img2

  1. img = io.imread('img.JPG')
  2. img2 = io.imread('img2.JPG')
  3. gray = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY)
  4. # ret 值多凭感觉
  5. thresh = np.ones_like(gray)
  6. ret = 168
  7. thresh[gray < ret] = 255
  8. thresh[gray > ret] = 0
  9. fig = plt.figure(figsize=(16, 6))
  10. plt.subplot(131),plt.imshow(img)
  11. plt.subplot(132),plt.imshow(gray,'gray')
  12. plt.subplot(133),plt.imshow(thresh,'gray')
  13. plt.show()

原图-灰度图-二值化图

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

  1. # noise removal
  2. kernel = np.ones((3,3),np.uint8)
  3. opening = cv2.morphologyEx(thresh,cv2.MORPH_OPEN,kernel, iterations = 2)
  4. # sure background area
  5. sure_bg = cv2.dilate(opening,kernel,iterations=3)
  6. # Finding sure foreground area
  7. dist_transform = cv2.distanceTransform(opening,cv2.DIST_L2,5)
  8. # distanceTransform
  9. fig = plt.figure(figsize=(16, 6))
  10. plt.subplot(131),plt.imshow(opening,'gray')
  11. plt.subplot(132),plt.imshow(sure_bg,'gray')
  12. plt.subplot(133),plt.imshow(dist_transform,'gray')
  13. plt.show()

1240

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

  1. def distance(dist_transform,thresh=0.1):
  2. ret, sure_fg = cv2.threshold(dist_transform,thresh*dist_transform.max(),255,0)
  3. sure_fg = np.uint8(sure_fg)
  4. median_img = cv2.medianBlur(sure_fg,17)
  5. fig = plt.figure(figsize=(20,18))
  6. plt.subplot(121),plt.imshow(median_img,'gray'),plt.xticks([]),plt.yticks([])
  7. im2, contours, hierarchy = cv2.findContours(median_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
  8. img_ground = img2.copy()
  9. cv2.drawContours(img_ground,contours,-1,(0,255,225),5)
  10. plt.subplot(122),plt.imshow(img_ground),plt.xticks([]),plt.yticks([])
  11. plt.show()
  12. return median_img,img_ground
  13. lims = (0.0,1.0,0.05)
  14. w = interactive(distance,dist_transform = fixed(dist_transform),thresh = lims)
  15. display(w)

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

效果图

发表评论

表情:
评论列表 (有 0 条评论,613人围观)

还没有评论,来说两句吧...

相关阅读

    相关 SAI眉毛画法

    效果图: ![format_png][]   具体绘制教程: 1.创建钢笔图层,使用曲线工具结合笔压工具一条条画出眉毛。详细教程可以参考:[http://www.pla

    相关 Arcmap等高线

    通过高程数据采样点来获取该工作范围的等高线常规方法: 方法一:高程点数据内插法: 1. Kriging插值:Spatial Analyst Tools -> Interpo

    相关 SAI臀部画法

    男性臀部特点:比较窄小,线条不那么圆润,起伏不平,多画一些线条表现出男性肌肉力量。 女性臀部特点:整体比较圆润,线条过渡很流畅自然,臀部比较宽大。   效果图参考:

    相关 数据流图画法

    数据流图的画法 数据流图也称为数据流程图date flow diagram , DFD,是一种便于用户理解和分析系统数据流程的图形工具,他摆脱了系统和具体内容,精确的在逻辑上

    相关 数据流图画法

    数据流图(DFD)     数据流图,简称DFD,是SA方法中用于表示系统逻辑模型的一种工具,它以图形的方式描绘数据在系统中流动和处理的过程,由于它只反映系统必须完成的逻辑

    相关 数据流图画法

    数据流图的画法 数据流图也称为数据流程图date flow diagram , DFD,是一种便于用户理解和分析系统数据流程的图形工具,他摆脱了系统和具体内容,精确的在逻辑上