栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

OpenCV简单图像分割

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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)

效果:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/753641.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号