opencv—常用函数学习_“干货“_5

目录

十五、图像分割

简单阈值分割 (threshold)

自适应阈值分割 (adaptiveThreshold)

颜色范围分割 (inRange)

分水岭算法 (watershed)

泛洪填充 (floodFill)

GrabCut算法 (grabCut)

距离变换 (distanceTransform)

最大稳定极值区域检测 (MSER)

均值漂移滤波 (pyrMeanShiftFiltering)

十六、连通域

计算连通组件 (connectedComponents)

计算连通组件并返回统计信息 (connectedComponentsWithStats)

解释

http://t.csdnimg.cn/i8pqt —— opencv—常用函数学习_“干货“_总(VIP)

散的正在一部分一部分发,不需要VIP。

资料整理不易,有用话给个赞和收藏吧。


十五、图像分割

        在OpenCV中,图像分割是将图像分割成不同区域或对象的过程,常用于对象检测、识别和图像分析。下面介绍一些常用的图像分割函数及其使用示例。

图像分割函数
threshold adaptiveThreshold inRange watershed floodFill
简单阈值分割 自适应阈值分割 颜色范围分割 分水岭算法 泛洪填充
grabCut distanceTransform MSER pyrMeanShiftFiltering
GrabCut算法 距离变换 最大稳定极值区域检测 均值漂移滤波
简单阈值分割 (threshold)
import cv2
import numpy as np

# 读取图像
image = cv2.imread('path_to_image.jpg', cv2.IMREAD_GRAYSCALE)

# 应用简单阈值分割
_, binary_image = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY)
cv2.imshow('Binary Image', binary_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
自适应阈值分割 (adaptiveThreshold)
# 应用自适应阈值分割
adaptive_thresh = cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                                        cv2.THRESH_BINARY, 11, 2)
cv2.imshow('Adaptive Threshold Image', adaptive_thresh)
cv2.waitKey(0)
cv2.destroyAllWindows()
颜色范围分割 (inRange)
# 读取彩色图像
color_image = cv2.imread('path_to_image.jpg')

# 定义颜色范围
lower_bound = np.array([0, 120, 70])
upper_bound = np.array([10, 255, 255])

# 转换到HSV颜色空间
hsv_image = cv2.cvtColor(color_image, cv2.COLOR_BGR2HSV)

# 应用颜色范围分割
mask = cv2.inRange(hsv_image, lower_bound, upper_bound)
cv2.imshow('Mask', mask)
cv2.waitKey(0)
cv2.destroyAllWindows()
分水岭算法 (watershed)
# 读取图像并转换为灰度图
gray = cv2.cvtColor(color_image, cv2.COLOR_BGR2GRAY)
_, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)

# 确定背景区域
kernel = np.ones((3, 3), np.uint8)
sure_bg = cv2.dilate(binary, kernel, iterations=3)

# 确定前景区域
dist_transform = cv2.distanceTransform(binary, cv2.DIST_L2, 5)
_, sure_fg = cv2.threshold(dist_transform, 0.7 * dist_transform.max(), 255, 0)

# 确定未知区域
sure_fg = np.uint8(sure_fg)
unknown = cv2.subtract(sure_bg, sure_fg)

# 标记连通组件
_, markers = cv2.connectedComponents(sure_fg)

# 为确保背景为1,增加1
markers = markers + 1

# 将未知区域标记为0
markers[unknown == 255] = 0

# 应用分水岭算法
markers = cv2.watershed(color_image, markers)
color_image[markers == -1] = [0, 0, 255]

cv2.imshow('Watershed', color_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
泛洪填充 (floodFill)
# 应用泛洪填充
flood_filled = color_image.copy()
h, w = flood_filled.shape[:2]
mask = np.zeros((h + 2, w + 2), np.uint8)
cv2.floodFill(flood_filled, mask, (0, 0), (255, 0, 0))

cv2.imshow('Flood Fill', flood_filled)
cv2.waitKey(0)
cv2.destroyAllWindows()
GrabCut算法 (grabCut)
# 初始化掩码
mask = np.zeros(color_image.shape[:2], np.uint8)

# 定义矩形
rect = (50, 50, 450, 290)

# 定义模型
bgdModel = np.zeros((1, 65), np.float64)
fgdModel = np.zeros((1, 65), np.float64)

# 应用GrabCut算法
cv2.grabCut(color_image, mask, rect, bgdModel, fgdModel, 5, cv2.GC_INIT_WITH_RECT)
mask2 = np.where((mask == 2) | (mask == 0), 0, 1).astype('uint8')
grabcut_image = color_image * mask2[:, :, np.newaxis]

cv2.imshow('GrabCut', grabcut_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
距离变换 (distanceTransform)
# 应用距离变换
dist_transform = cv2.distanceTransform(binary, cv2.DIST_L2, 5)
cv2.imshow('Distance Transform', dist_transform)
cv2.waitKey(0)
cv2.destroyAllWindows()
最大稳定极值区域检测 (MSER)
# 创建MSER对象
mser = cv2.MSER_create()

# 检测MSER区域
regions, _ = mser.detectRegions(gray)

# 绘制检测到的区域
output = color_image.copy()
for p in regions:
    hull = cv2.convexHull(p.reshape(-1, 1, 2))
    cv2.polylines(output, [hull], 1, (0, 255, 0))

cv2.imshow('MSER', output)
cv2.waitKey(0)
cv2.destroyAllWindows()
均值漂移滤波 (pyrMeanShiftFiltering)
# 应用均值漂移滤波
mean_shift_image = cv2.pyrMeanShiftFiltering(color_image, 21, 51)
cv2.imshow('Mean Shift Filtering', mean_shift_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

        这些示例展示了如何使用OpenCV中的各种图像分割函数来处理图像。根据具体的应用需求,可以灵活运用这些函数来实现复杂的图像分割任务。

十六、连通域

        在OpenCV中,连通域分析是图像处理中的一个重要步骤,用于检测和标记图像中的连通区域。主要有两个函数:connectedComponentsconnectedComponentsWithStats。下面介绍这些函数及其使用示例。

连通域分析函数
connectedComponents connectedComponentsWithStats
计算连通组件 计算连通组件并返回统计信息
计算连通组件 (connectedComponents)
import cv2
import numpy as np

# 读取图像并转换为灰度图
image = cv2.imread('path_to_image.jpg', cv2.IMREAD_GRAYSCALE)

# 应用阈值处理
_, binary_image = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY)

# 计算连通组件
num_labels, labels = cv2.connectedComponents(binary_image)

# 显示结果
label_hue = np.uint8(179 * labels / np.max(labels))
blank_ch = 255 * np.ones_like(label_hue)
labeled_img = cv2.merge([label_hue, blank_ch, blank_ch])

# 转换到BGR颜色空间
labeled_img = cv2.cvtColor(labeled_img, cv2.COLOR_HSV2BGR)

# 设置背景为黑色
labeled_img[label_hue == 0] = 0

cv2.imshow('Connected Components', labeled_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
计算连通组件并返回统计信息 (connectedComponentsWithStats)
# 计算连通组件及统计信息
num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(binary_image)

# 输出每个连通组件的统计信息
for i in range(num_labels):
    print(f"Component {i}:")
    print(f"  Bounding box: {stats[i, cv2.CC_STAT_LEFT]}, {stats[i, cv2.CC_STAT_TOP]}, "
          f"{stats[i, cv2.CC_STAT_WIDTH]}, {stats[i, cv2.CC_STAT_HEIGHT]}")
    print(f"  Area: {stats[i, cv2.CC_STAT_AREA]}")
    print(f"  Centroid: {centroids[i]}")
    
# 显示结果
label_hue = np.uint8(179 * labels / np.max(labels))
blank_ch = 255 * np.ones_like(label_hue)
labeled_img = cv2.merge([label_hue, blank_ch, blank_ch])

# 转换到BGR颜色空间
labeled_img = cv2.cvtColor(labeled_img, cv2.COLOR_HSV2BGR)

# 设置背景为黑色
labeled_img[label_hue == 0] = 0

cv2.imshow('Connected Components with Stats', labeled_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
解释
  • connectedComponents:此函数返回连通组件的数量和每个像素所属的标签。
  • connectedComponentsWithStats:此函数除了返回标签外,还返回每个连通组件的统计信息(如边界框、面积)和重心。

        这些示例展示了如何使用OpenCV中的连通域分析函数来处理图像。根据具体的应用需求,可以灵活运用这些函数来实现复杂的连通域检测和分析任务。

相关推荐

  1. opencv函数学习_“干货“_5

    2024-07-18 19:44:04       25 阅读
  2. opencv函数学习_“干货“_总

    2024-07-18 19:44:04       22 阅读
  3. opencv函数学习_“干货“_9

    2024-07-18 19:44:04       31 阅读
  4. opencv函数学习_“干货“_10

    2024-07-18 19:44:04       30 阅读
  5. opencv函数学习_“干货“_7

    2024-07-18 19:44:04       22 阅读
  6. opencv函数学习_“干货“_8

    2024-07-18 19:44:04       24 阅读
  7. opencv函数学习_“干货“_11

    2024-07-18 19:44:04       24 阅读
  8. opencv函数学习_“干货“_6

    2024-07-18 19:44:04       18 阅读
  9. opencv函数学习_“干货“_4

    2024-07-18 19:44:04       21 阅读
  10. opencv函数学习_“干货“_3

    2024-07-18 19:44:04       16 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-18 19:44:04       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-18 19:44:04       71 阅读
  3. 在Django里面运行非项目文件

    2024-07-18 19:44:04       58 阅读
  4. Python语言-面向对象

    2024-07-18 19:44:04       69 阅读

热门阅读

  1. 光伏储能剑指何方

    2024-07-18 19:44:04       20 阅读
  2. Web前端-Web开发CSS基础5-浮动

    2024-07-18 19:44:04       18 阅读
  3. 【J1期末测试】学习之星

    2024-07-18 19:44:04       24 阅读
  4. MySQL 溢出页、页分裂、表空间碎片

    2024-07-18 19:44:04       23 阅读
  5. mysql8和mysql5版本在使用mybatis框架时的注意事项

    2024-07-18 19:44:04       24 阅读
  6. C++基础语法:STL之容器(3)--序列容器中的deque

    2024-07-18 19:44:04       18 阅读
  7. 一文搞懂C语言

    2024-07-18 19:44:04       22 阅读