当前位置:   article > 正文

Python OpenCV提取物体轮廓_python 轮廓提取

python 轮廓提取

一、基础实验

#coding=gbk
import numpy as np
import matplotlib.pyplot as plt
import cv2


# 读入图像
img = cv2.imread('snake.png')

img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# 将颜色更改为RGB(从BGR)

plt.imshow(img_rgb)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

在这里插入图片描述

gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#灰度图
ret, binary = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
plt.imshow(binary, cmap='gray')
  • 1
  • 2
  • 3
  • 4

在这里插入图片描述

contours, hierarchy = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
contours_image = np.copy(img)
contours_image = cv2.drawContours(contours_image, contours, -1, (0,255,0), 3)
 #二进制阈值图像
plt.imshow(contours_image)
  • 1
  • 2
  • 3
  • 4
  • 5

在这里插入图片描述

练习: 找到每个轮廓的方向

def orientations(contours):
    angles = []
    for contour in contours:
        if len(contour) < 5:
            continue     
        # 拟合椭圆
        ellipse = cv2.fitEllipse(contour)
        # 提取角度
        angle = ellipse[2]
        angles.append(angle)

    return angles

# ---------------------------------------------------------- #
# 打印方向值
angles = orientations(contours)
print('Angles of each contour (in degrees): ' + str(angles))

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
Angles of each contour (in degrees): [92.56619262695312, 0.0, 0.0, 96.2242660522461, 47.50788879394531, 1.298294186592102, 0.0029462939128279686]
  • 1

边界矩形

## TODO: 完成此功能,以便
## 它会返回原始图像的新裁剪版本
def left_hand_crop(image, selected_contour):
    """
    Left hand crop 
    :参数图像:原始图像
    :参数selectec_contour:将用于裁剪的轮廓
    :返回值: cropped_image, 左手周围的裁剪图像
    """
    
    ## TODO: 检测左手轮廓的边界矩形
    
    x, y, w, h = cv2.boundingRect(selected_contour)
    box_image = cv2.rectangle(contours_image, (x,y), (x+w,y+h), (200,0,200),2)
    
    ## TODO: 使用边界矩形的尺寸裁剪图像
    # 复制图像进行裁剪
    
    cropped_image = np.copy(box_image)
    cropped_image = box_image[y: y + h, x: x + w]
    
    return cropped_image


## TODO: 从列表中选择左侧轮廓
## 替换此值
selected_contour = contours[1]


# ---------------------------------------------------------- #
# 如果选择了轮廓
if(selected_contour is not None):
    # 调用带有该轮廓的裁剪函数作为参数
    cropped_image = left_hand_crop(img, selected_contour)
    plt.imshow(cropped_image)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/356186
推荐阅读
相关标签
  

闽ICP备14008679号