OpenCV简单图像分割

这里主要基于 OpenCV 和 Scikit-learn 实现四种图像分割:

基于 K-means
基于 Contour Detection
基于 Thresholding
基于 Color Masking HSV颜色空间,就不演示了。
HSV颜色空间阈值调节器在我的opencv工具内

原图:
在这里插入图片描述

K-means

import numpy as np
import cv2


def cv_show(neme, img):
    cv2.namedWindow(neme, cv2.WINDOW_NORMAL)
    cv2.imshow(neme, img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


path = 'image2.jpg'
img = cv2.imread(path)

img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
twoDimage = img.reshape((-1, 3))
twoDimage = np.float32(twoDimage)

criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
K = 2
attempts = 10

# Kmeans
ret, label, center = cv2.kmeans(twoDimage, K, None, criteria, attempts, cv2.KMEANS_PP_CENTERS)
center = np.uint8(center)
res = center[label.flatten()]
result_image = res.reshape((img.shape))
cv_show('neme', result_image)

效果:
在这里插入图片描述

Contour Detection

path = 'image2.jpg'
img = cv2.imread(path)
img = cv2.resize(img, (256, 256))

# 图像预处理
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
_, thresh = cv2.threshold(gray, np.mean(gray), 255, cv2.THRESH_BINARY_INV)
edges = cv2.dilate(cv2.Canny(thresh, 0, 255), None)

# 轮廓检测
cnt = sorted(cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[-2], key=cv2.contourArea)[-1]  # 轮廓检测与排序
mask = np.zeros((256, 256), np.uint8)
masked = cv2.drawContours(mask, [cnt], -1, 255, -1)

# 区域分割
dst = cv2.bitwise_and(img, img, mask=mask)
segmented = cv2.cvtColor(dst, cv2.COLOR_BGR2RGB)
cv_show('neme', segmented)

在这里插入图片描述

Thresholding

pip install scikit-image    
import numpy as np
from skimage.filters import threshold_otsu
import cv2

path = 'image2.jpg'
img = cv2.imread(path)

img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY)


def filter_image(image, mask):
    r = image[:, :, 0] * mask
    g = image[:, :, 1] * mask
    b = image[:, :, 2] * mask
    return np.dstack([r, g, b])


thresh = threshold_otsu(img_gray)  # 找阈值
img_otsu = img_gray < thresh
filtered = filter_image(img, img_otsu)
cv_show('neme', filtered)

效果:
在这里插入图片描述

  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

默执_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值